blockcerts-merkletools


Nameblockcerts-merkletools JSON
Version 1.0.3 PyPI version JSON
download
home_pagehttps://github.com/blockchain-certificates/blockcerts-pymerkletools
SummaryMerkle Tools
upload_time2023-09-12 02:58:25
maintainer
docs_urlNone
authorBlockcerts
requires_python
licenseMIT
keywords merkle tree blockchain
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # blockcerts-pymerkletools
[![PyPI version](https://badge.fury.io/py/blockcerts-merkletools.svg)](https://badge.fury.io/py/blockcerts-merkletools)

This is a Python port of [solidity-pymerkletools](https://github.com/f8n/solidity-pymerkletools), which supports Web3's solidity keccak hashing function.  This fork supports updated dependencies per Blockcerts project requirements.

Tools for creating Merkle trees, generating merkle proofs, and verification of merkle proofs.

## Installation

```
pip install blockcerts-merkletools
```

### Create MerkleTools Object

```python
import blockcerts_merkletools

mt = MerkleTools()  # default hash algorithm is Web3.solidity_keccak
```

## Methods

### add_leaf(value, do_hash)

Adds a value as a leaf or a list of leafs to the tree. The value must be a hex string.

```python
mt.add_leaf("0x4b39F7b0624b9dB86AD293686bc38B903142dbBc")
mt.add_leaf("0x71b4a2d9B91726bdb5849D928967A1654D7F3de7")
```

### get_leaf_count()

Returns the number of leaves that are currently added to the tree. 

```python
leaf_count =  mt.get_leaf_count();
```

### get_leaf(index)

Returns the value of the leaf at the given index as a hex string.

```python
leaf_value =  mt.get_leaf(1)
```

### reset_tree()

Removes all the leaves from the tree, prepararing to to begin creating a new tree.

```python
mt.reset_tree()
```

### make_tree()

Generates the merkle tree using the leaves that have been added.

```python
mt.make_tree();
```

### is_ready 

`.is_ready` is a boolean property indicating if the tree is built and ready to supply its root and proofs. The `is_ready` state is `True` only after calling 'make_tree()'.  Adding leaves or resetting the tree will change the ready state to False.

```python
is_ready = mt.is_ready 
```

### get_merkle_root()

Returns the merkle root of the tree as a hex string. If the tree is not ready, `None` is returned.

```python
root_value = mt.get_merkle_root();
```

### get_proof(index)

Returns the proof as an array of hash objects for the leaf at the given index. If the tree is not ready or no leaf exists at the given index, null is returned.  

```python
proof = mt.get_proof(1)
```

The proof array contains a set of merkle sibling objects. Each object contains the sibling hash, with the key value of either right or left. The right or left value tells you where that sibling was in relation to the current hash being evaluated. This information is needed for proof validation, as explained in the following section.

### validate_proof(proof, target_hash, merkle_root)

Returns a boolean indicating whether or not the proof is valid and correctly connects the `target_hash` to the `merkle_root`. `proof` is a proof array as supplied by the `get_proof` method. The `target_hash` and `merkle_root` parameters must be a hex strings.

```python
proof = [
   { right: '09096dbc49b7909917e13b795ebf289ace50b870440f10424af8845fb7761ea5' },
   { right: 'ed2456914e48c1e17b7bd922177291ef8b7f553edf1b1f66b6fc1a076524b22f' },
   { left: 'eac53dde9661daf47a428efea28c81a021c06d64f98eeabbdcff442d992153a8' },
]
target_hash = '36e0fd847d927d68475f32a94efff30812ee3ce87c7752973f4dd7476aa2e97e'
merkle_root = 'b8b1f39aa2e3fc2dde37f3df04e829f514fb98369b522bfb35c663befa896766'

is_valid = mt.validate_proof(proof, targetHash, merkleRoot)
```

The proof process uses all the proof objects in the array to attempt to prove a relationship between the `target_hash` and the `merkle_root` values. The steps to validate a proof are:

1. Concatenate `target_hash` and the first hash in the proof array. The right or left designation specifies which side of the concatenation that the proof hash value should be on.
2. Hash the resulting value.
3. Concatenate the resulting hash with the next hash in the proof array, using the same left and right rules.
4. Hash that value and continue the process until you’ve gone through each item in the proof array.
5. The final hash value should equal the `merkle_root` value if the proof is valid, otherwise the proof is invalid.

## Common Usage

### Creating a tree and generating the proofs

```python
mt = MerkleTools()

mt.add_leaf("tierion", True)
mt.add_leaf(["bitcoin", "blockchain"], True)

mt.make_tree()

print "root:", mt.get_merkle_root()  # root: '765f15d171871b00034ee55e48ffdf76afbc44ed0bcff5c82f31351d333c2ed1'

print mt.get_proof(1)  # [{left: '2da7240f6c88536be72abe9f04e454c6478ee29709fc3729ddfb942f804fbf08'},
                       #  {right: 'ef7797e13d3a75526946a3bcf00daec9fc9c9c4d51ddc7cc5df888f74dd434d1'}] 

print mt.validate_proof(mt.get_proof(1), mt.get_leaf(1), mt.get_merkle_root())  # True
```

## Notes

### About tree generation

1. Internally, leaves are stored as `bytearray`. When the tree is built, it is generated by hashing together the `bytearray` values. 
2. Lonely leaf nodes are promoted to the next level up, as depicted below.

                         ROOT=Hash(H+E)
                         /        \
                        /          \
                 H=Hash(F+G)        E
                 /       \           \
                /         \           \
         F=Hash(A+B)    G=Hash(C+D)    E
          /     \        /     \        \
         /       \      /       \        \

        A         B    C         D        E



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/blockchain-certificates/blockcerts-pymerkletools",
    "name": "blockcerts-merkletools",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "merkle tree,blockchain",
    "author": "Blockcerts",
    "author_email": "info@blockcerts.org",
    "download_url": "https://files.pythonhosted.org/packages/c9/1c/bc7c9cc009f2d33cec48589af8b7686ea99bcd8c3ddff3b7e72065ed3794/blockcerts-merkletools-1.0.3.tar.gz",
    "platform": null,
    "description": "# blockcerts-pymerkletools\n[![PyPI version](https://badge.fury.io/py/blockcerts-merkletools.svg)](https://badge.fury.io/py/blockcerts-merkletools)\n\nThis is a Python port of [solidity-pymerkletools](https://github.com/f8n/solidity-pymerkletools), which supports Web3's solidity keccak hashing function.  This fork supports updated dependencies per Blockcerts project requirements.\n\nTools for creating Merkle trees, generating merkle proofs, and verification of merkle proofs.\n\n## Installation\n\n```\npip install blockcerts-merkletools\n```\n\n### Create MerkleTools Object\n\n```python\nimport blockcerts_merkletools\n\nmt = MerkleTools()  # default hash algorithm is Web3.solidity_keccak\n```\n\n## Methods\n\n### add_leaf(value, do_hash)\n\nAdds a value as a leaf or a list of leafs to the tree. The value must be a hex string.\n\n```python\nmt.add_leaf(\"0x4b39F7b0624b9dB86AD293686bc38B903142dbBc\")\nmt.add_leaf(\"0x71b4a2d9B91726bdb5849D928967A1654D7F3de7\")\n```\n\n### get_leaf_count()\n\nReturns the number of leaves that are currently added to the tree. \n\n```python\nleaf_count =  mt.get_leaf_count();\n```\n\n### get_leaf(index)\n\nReturns the value of the leaf at the given index as a hex string.\n\n```python\nleaf_value =  mt.get_leaf(1)\n```\n\n### reset_tree()\n\nRemoves all the leaves from the tree, prepararing to to begin creating a new tree.\n\n```python\nmt.reset_tree()\n```\n\n### make_tree()\n\nGenerates the merkle tree using the leaves that have been added.\n\n```python\nmt.make_tree();\n```\n\n### is_ready \n\n`.is_ready` is a boolean property indicating if the tree is built and ready to supply its root and proofs. The `is_ready` state is `True` only after calling 'make_tree()'.  Adding leaves or resetting the tree will change the ready state to False.\n\n```python\nis_ready = mt.is_ready \n```\n\n### get_merkle_root()\n\nReturns the merkle root of the tree as a hex string. If the tree is not ready, `None` is returned.\n\n```python\nroot_value = mt.get_merkle_root();\n```\n\n### get_proof(index)\n\nReturns the proof as an array of hash objects for the leaf at the given index. If the tree is not ready or no leaf exists at the given index, null is returned.  \n\n```python\nproof = mt.get_proof(1)\n```\n\nThe proof array contains a set of merkle sibling objects. Each object contains the sibling hash, with the key value of either right or left. The right or left value tells you where that sibling was in relation to the current hash being evaluated. This information is needed for proof validation, as explained in the following section.\n\n### validate_proof(proof, target_hash, merkle_root)\n\nReturns a boolean indicating whether or not the proof is valid and correctly connects the `target_hash` to the `merkle_root`. `proof` is a proof array as supplied by the `get_proof` method. The `target_hash` and `merkle_root` parameters must be a hex strings.\n\n```python\nproof = [\n   { right: '09096dbc49b7909917e13b795ebf289ace50b870440f10424af8845fb7761ea5' },\n   { right: 'ed2456914e48c1e17b7bd922177291ef8b7f553edf1b1f66b6fc1a076524b22f' },\n   { left: 'eac53dde9661daf47a428efea28c81a021c06d64f98eeabbdcff442d992153a8' },\n]\ntarget_hash = '36e0fd847d927d68475f32a94efff30812ee3ce87c7752973f4dd7476aa2e97e'\nmerkle_root = 'b8b1f39aa2e3fc2dde37f3df04e829f514fb98369b522bfb35c663befa896766'\n\nis_valid = mt.validate_proof(proof, targetHash, merkleRoot)\n```\n\nThe proof process uses all the proof objects in the array to attempt to prove a relationship between the `target_hash` and the `merkle_root` values. The steps to validate a proof are:\n\n1. Concatenate `target_hash` and the first hash in the proof array. The right or left designation specifies which side of the concatenation that the proof hash value should be on.\n2. Hash the resulting value.\n3. Concatenate the resulting hash with the next hash in the proof array, using the same left and right rules.\n4. Hash that value and continue the process until you\u2019ve gone through each item in the proof array.\n5. The final hash value should equal the `merkle_root` value if the proof is valid, otherwise the proof is invalid.\n\n## Common Usage\n\n### Creating a tree and generating the proofs\n\n```python\nmt = MerkleTools()\n\nmt.add_leaf(\"tierion\", True)\nmt.add_leaf([\"bitcoin\", \"blockchain\"], True)\n\nmt.make_tree()\n\nprint \"root:\", mt.get_merkle_root()  # root: '765f15d171871b00034ee55e48ffdf76afbc44ed0bcff5c82f31351d333c2ed1'\n\nprint mt.get_proof(1)  # [{left: '2da7240f6c88536be72abe9f04e454c6478ee29709fc3729ddfb942f804fbf08'},\n                       #  {right: 'ef7797e13d3a75526946a3bcf00daec9fc9c9c4d51ddc7cc5df888f74dd434d1'}] \n\nprint mt.validate_proof(mt.get_proof(1), mt.get_leaf(1), mt.get_merkle_root())  # True\n```\n\n## Notes\n\n### About tree generation\n\n1. Internally, leaves are stored as `bytearray`. When the tree is built, it is generated by hashing together the `bytearray` values. \n2. Lonely leaf nodes are promoted to the next level up, as depicted below.\n\n                         ROOT=Hash(H+E)\n                         /        \\\n                        /          \\\n                 H=Hash(F+G)        E\n                 /       \\           \\\n                /         \\           \\\n         F=Hash(A+B)    G=Hash(C+D)    E\n          /     \\        /     \\        \\\n         /       \\      /       \\        \\\n\n        A         B    C         D        E\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Merkle Tools",
    "version": "1.0.3",
    "project_urls": {
        "Homepage": "https://github.com/blockchain-certificates/blockcerts-pymerkletools"
    },
    "split_keywords": [
        "merkle tree",
        "blockchain"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b4d11ff8b6fce02328b1d730efa247e930a8627f805a5318f3c1ddc2026fd9fc",
                "md5": "1bf03d6e09b7d0cb708898a505d0eda3",
                "sha256": "4f9747959d750b0f1617d0604a9962df57a4ced315accbb1b49f0210b4390765"
            },
            "downloads": -1,
            "filename": "blockcerts_merkletools-1.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1bf03d6e09b7d0cb708898a505d0eda3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 5908,
            "upload_time": "2023-09-12T02:58:24",
            "upload_time_iso_8601": "2023-09-12T02:58:24.043501Z",
            "url": "https://files.pythonhosted.org/packages/b4/d1/1ff8b6fce02328b1d730efa247e930a8627f805a5318f3c1ddc2026fd9fc/blockcerts_merkletools-1.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c91cbc7c9cc009f2d33cec48589af8b7686ea99bcd8c3ddff3b7e72065ed3794",
                "md5": "9188d01fa143b58d1d4670cf82e4ae8a",
                "sha256": "75a628038d8a25f5551a74d6e9ddd3654ff79458d2aba09bd60b43532525cc63"
            },
            "downloads": -1,
            "filename": "blockcerts-merkletools-1.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "9188d01fa143b58d1d4670cf82e4ae8a",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 8483,
            "upload_time": "2023-09-12T02:58:25",
            "upload_time_iso_8601": "2023-09-12T02:58:25.950710Z",
            "url": "https://files.pythonhosted.org/packages/c9/1c/bc7c9cc009f2d33cec48589af8b7686ea99bcd8c3ddff3b7e72065ed3794/blockcerts-merkletools-1.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-12 02:58:25",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "blockchain-certificates",
    "github_project": "blockcerts-pymerkletools",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "blockcerts-merkletools"
}
        
Elapsed time: 0.15101s