### Install merklelib Source: https://github.com/vpaliy/merklelib/blob/master/README.md Installation command for the library. ```bash pip install merklelib ``` -------------------------------- ### Complete Workflow Example Source: https://context7.com/vpaliy/merklelib/llms.txt Illustrates a comprehensive workflow for a certificate transparency log, encompassing tree creation, proof generation, verification, and consistency checks. ```APIDOC ## Complete Workflow Example This example demonstrates a complete workflow for a certificate transparency log, showing tree construction, proof generation, verification, and consistency checks. ```python import hashlib from merklelib import MerkleTree, verify_leaf_inclusion, verify_tree_consistency def sha256(value): return hashlib.sha256(value).hexdigest() # === Certificate Authority maintains the log === certificates = [ 'cert:example.com:2024-01', 'cert:mysite.org:2024-01', 'cert:secure.net:2024-02', 'cert:trusted.io:2024-02' ] log = MerkleTree(certificates, sha256) print(f"Log root: {log.merkle_root}") print(f"Log size: {len(log)}") # === Client requests proof for their certificate === client_cert = 'cert:mysite.org:2024-01' proof = log.get_proof(client_cert) trusted_root = log.merkle_root ``` ``` -------------------------------- ### Install Graphviz Dependencies Source: https://github.com/vpaliy/merklelib/blob/master/README.md System-level commands to install Graphviz for image export support. ```bash brew install graphviz ``` ```bash sudo apt-get install graphviz ``` -------------------------------- ### export - Export Tree to File Source: https://context7.com/vpaliy/merklelib/llms.txt Learn how to export the Merkle tree structure to a file in JSON format, or as an image (JPG, PNG) if graphviz is installed, facilitating persistence and sharing. ```APIDOC ## export - Export Tree to File The `export` function saves the Merkle tree structure to a file. It supports JSON format by default and image formats (JPG, PNG) when graphviz is installed. This is useful for persistence, sharing, and documentation. ```python from merklelib import MerkleTree, export # Build tree transactions = ['tx1', 'tx2', 'tx3', 'tx4'] tree = MerkleTree(transactions) # Export to JSON (default) export(tree, filename='merkle_tree') # Creates: merkle_tree.json # Export to image (requires graphviz) export(tree, filename='merkle_tree', ext='png') # Creates: merkle_tree.png export(tree, filename='merkle_tree', ext='jpg') # Creates: merkle_tree.jpg # Export with absolute path export(tree, filename='/path/to/output/tree', ext='json') ``` ``` -------------------------------- ### Execute Certificate Transparency Workflow Source: https://context7.com/vpaliy/merklelib/llms.txt Demonstrates a complete workflow including tree construction, proof generation, and verification for certificate logs. ```python import hashlib from merklelib import MerkleTree, verify_leaf_inclusion, verify_tree_consistency def sha256(value): return hashlib.sha256(value).hexdigest() # === Certificate Authority maintains the log === certificates = [ 'cert:example.com:2024-01', 'cert:mysite.org:2024-01', 'cert:secure.net:2024-02', 'cert:trusted.io:2024-02' ] log = MerkleTree(certificates, sha256) print(f"Log root: {log.merkle_root}") print(f"Log size: {len(log)}") # === Client requests proof for their certificate === client_cert = 'cert:mysite.org:2024-01' proof = log.get_proof(client_cert) trusted_root = log.merkle_root ``` -------------------------------- ### Clone and Run Benchmark Source: https://github.com/vpaliy/merklelib/blob/master/README.md Commands to clone the repository and execute the built-in benchmark script. ```bash $ git clone git clone https://github.com/vpaliy/merklelib.git $ cd merklelib ``` ```bash $ python3 benchmark --size=2048 -a=8 ``` -------------------------------- ### MerkleTree.get_proof and MerkleTree.verify_leaf_inclusion Source: https://context7.com/vpaliy/merklelib/llms.txt Demonstrates how to generate a proof for a specific file and verify its inclusion in the Merkle tree. Also shows how verification fails with tampered data. ```APIDOC ## MerkleTree.get_proof and MerkleTree.verify_leaf_inclusion ### Description Generates a proof for a target file and verifies its inclusion within the Merkle tree. This example also illustrates how attempting to verify tampered data or a non-existent file will result in a `False` outcome. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example ```python # Assuming 'tree' is an initialized MerkleTree object target_file = 'file2.txt' proof = tree.get_proof(target_file) is_included = tree.verify_leaf_inclusion(target_file, proof) print(f"'{target_file}' is in tree: {is_included}") is_included = tree.verify_leaf_inclusion('tampered_file.txt', proof) print(f"Tampered file in tree: {is_included}") ``` ### Response #### Success Response (200) N/A (Illustrative code) #### Response Example ``` 'file2.txt' is in tree: True Tampered file in tree: False ``` ``` -------------------------------- ### Custom Benchmark Script Source: https://github.com/vpaliy/merklelib/blob/master/README.md A simple script using timeit to measure the time required to build a Merkle tree with 65536 leaves. ```python >>> import os >>> import timeit >>> from merklelib import MerkleTree >>> leaves = [os.urandom(2048) for i in range(2**16)] >>> def timeav(code, n=20): >>> return timeit.timeit( ... code, setup="from __main__ import MerkleTree, leaves", number=n)/n >>> # time taken to build the tree >>> print timeav("MerkleTree(leaves)") 0.70325 ``` -------------------------------- ### Build a Merkle Tree with merklelib Source: https://context7.com/vpaliy/merklelib/llms.txt Initialize a MerkleTree with a collection of data and an optional custom hash function. The tree is built automatically upon instantiation. ```python import hashlib from merklelib import MerkleTree # Define a custom hash function (optional - SHA-256 is default) def hashfunc(value): return hashlib.sha256(value).hexdigest() # Build a Merkle tree from a list of transactions transactions = ['tx1', 'tx2', 'tx3', 'tx4', 'tx5', 'tx6', 'tx7', 'tx8'] tree = MerkleTree(transactions, hashfunc) # Access the Merkle root hash print(f"Merkle Root: {tree.merkle_root}") # Output: Merkle Root: a1b2c3d4e5f6... (64-char hex string) # Get number of leaves print(f"Number of leaves: {len(tree)}") # Output: Number of leaves: 8 # Access all leaf hashes as hexadecimal strings print(f"Leaf hashes: {tree.hexleaves}") # Build an empty tree and add data later empty_tree = MerkleTree() print(f"Empty tree root: {empty_tree.merkle_root}") # Output: Empty tree root: None ``` -------------------------------- ### Build Merkle Tree and Verify Leaf Inclusion Source: https://github.com/vpaliy/merklelib/blob/master/README.md Demonstrates creating a tree with a custom hash function and verifying the existence of a leaf using an audit proof. ```python import string import hashlib from merklelib import MerkleTree # a sample hash function # you can also omit it and the default hash function will be used def hashfunc(value): return hashlib.sha256(value).hexdigest() # a list of all ASCII letters data = list(string.ascii_letters) # build a Merkle tree for that list tree = MerkleTree(data, hashfunc) # generate an audit proof the letter A proof = tree.get_proof(hashfunc('A')) # now verify that A is in the tree # you can also pass in the hash value of 'A' # it will hash automatically if the user forgot to hash it if tree.verify_leaf_inclusion('A', proof): print('A is in the tree') else: exit('A is not in the tree') ``` -------------------------------- ### Hasher - Custom Hash Functions Source: https://context7.com/vpaliy/merklelib/llms.txt Demonstrates how to create and use a custom Hasher with MerkleTree for enhanced security by preventing second preimage attacks. ```APIDOC ## Hasher - Custom Hash Functions with Security The `Hasher` class wraps hash functions to prevent second preimage attacks by prepending `\x00` to leaves and `\x01` to internal nodes before hashing. This ensures attackers cannot create trees with different structures that produce the same root. ```python import hashlib from merklelib import MerkleTree from merklelib.merkle import Hasher # Create a custom hasher with SHA-512 def sha512_hash(value): return hashlib.sha512(value).hexdigest() hasher = Hasher(sha512_hash) # Hasher prepends bytes for security leaf_data = b'my_data' leaf_hash = hasher.hash_leaf(leaf_data) # Internally computes: sha512(b'\x00' + leaf_data) # For combining child nodes left_hash = hasher.hash_leaf(b'left') right_hash = hasher.hash_leaf(b'right') parent_hash = hasher.hash_children(left_hash, right_hash) # Internally computes: sha512(b'\x01' + left_hash + right_hash) # Use hasher with MerkleTree tree = MerkleTree(['data1', 'data2', 'data3'], hasher) print(f"Tree with custom hasher: {tree.merkle_root}") ``` ``` -------------------------------- ### Verify Leaf Inclusion in a Merkle Tree Source: https://context7.com/vpaliy/merklelib/llms.txt Demonstrates how to generate a proof for a leaf and verify its inclusion in the tree, including handling tampered data. ```python target_file = 'file2.txt' proof = tree.get_proof(target_file) # Verify the file is in the tree is_included = tree.verify_leaf_inclusion(target_file, proof) print(f"'{target_file}' is in tree: {is_included}") # Output: 'file2.txt' is in tree: True # Verify with tampered data fails is_included = tree.verify_leaf_inclusion('tampered_file.txt', proof) print(f"Tampered file in tree: {is_included}") # Output: Tampered file in tree: False ``` -------------------------------- ### Manage Log Growth Source: https://context7.com/vpaliy/merklelib/llms.txt Captures a snapshot of the current log state before appending new entries. ```python snapshot_root = log.merkle_root snapshot_size = len(log) log.append('cert:newdomain.com:2024-03') log.append('cert:another.org:2024-03') ``` -------------------------------- ### verify_tree_consistency - Verifying Tree Consistency Source: https://context7.com/vpaliy/merklelib/llms.txt Explains and demonstrates the `verify_tree_consistency` function, which checks if a newer Merkle tree contains all data from an older tree in the correct order. ```APIDOC ## verify_tree_consistency - Verifying Tree Consistency ### Description The `verify_tree_consistency` function verifies that a newer tree contains all the same data as an older tree in the same order, with any new data appended at the end. This is essential for append-only logs and certificate transparency. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example ```python from merklelib import MerkleTree, verify_tree_consistency # Original database state original_data = ['entry1', 'entry2', 'entry3'] old_tree = MerkleTree(original_data) old_root = old_tree.merkle_root old_size = len(old_tree) # Database grows over time new_data = ['entry1', 'entry2', 'entry3', 'entry4', 'entry5'] new_tree = MerkleTree(new_data) # Verify consistency - new tree contains old tree's data is_consistent = verify_tree_consistency(new_tree, old_root, old_size) print(f"Trees are consistent: {is_consistent}") # Inconsistent if data was modified tampered_data = ['entry1', 'MODIFIED', 'entry3', 'entry4'] tampered_tree = MerkleTree(tampered_data) is_consistent = verify_tree_consistency(tampered_tree, old_root, old_size) print(f"Tampered tree consistent: {is_consistent}") ``` ### Response #### Success Response (200) N/A (Illustrative code) #### Response Example ``` Trees are consistent: True Tampered tree consistent: False ``` ``` -------------------------------- ### Visualize Merkle Tree in Terminal Source: https://github.com/vpaliy/merklelib/blob/master/README.md Uses the beautify function to print a visual representation of the Merkle tree to the terminal. ```python from merklelib import MerkleTree, beautify transactions = get_transactions(user) # random data tree = MerkleTree(transactions) beautify(tree) # print the tree in the terminal ``` -------------------------------- ### beautify - Terminal Tree Visualization Source: https://context7.com/vpaliy/merklelib/llms.txt Utilize the `beautify` function to render a visual representation of the Merkle tree structure directly in the terminal, aiding in debugging and understanding tree hierarchy. ```APIDOC ## beautify - Terminal Tree Visualization The `beautify` function prints a visual representation of the Merkle tree structure to the terminal. It displays the tree hierarchy with hash values, making it easy to understand and debug tree structures. ```python from merklelib import MerkleTree, beautify # Build a small tree for visualization data = ['A', 'B', 'C', 'D'] tree = MerkleTree(data) # Print tree structure to terminal beautify(tree) # Output: # e11a20bae8379fdc0ed560561ba33f30c877e0e95051aed5acebcb9806f6521f # ├── 862532e6a3c9aafc2016810598ed0cc3025af5640db73224f586b6f1138385f4 # │ ├── 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9 # │ └── 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b # └── f4685cb09ef9f1c86b2d8f544d89f1c1d3592a3654beb8feecad11e9545e0e72 # ├── d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35 # └── 4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce ``` ``` -------------------------------- ### Visualize Tree in Terminal Source: https://context7.com/vpaliy/merklelib/llms.txt The beautify function prints a visual representation of the Merkle tree structure to the terminal for debugging purposes. ```python from merklelib import MerkleTree, beautify # Build a small tree for visualization data = ['A', 'B', 'C', 'D'] tree = MerkleTree(data) # Print tree structure to terminal beautify(tree) # Output: # e11a20bae8379fdc0ed560561ba33f30c877e0e95051aed5acebcb9806f6521f # ├── 862532e6a3c9aafc2016810598ed0cc3025af5640db73224f586b6f1138385f4 # │ ├── 5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9 # │ └── 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b # └── f4685cb09ef9f1c86b2d8f544d89f1c1d3592a3654beb8feecad11e9545e0e72 # ├── d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab35 # └── 4e07408562bedb8b60ce05c1decfe3ad16b72230967de01f640b7e4729b49fce ``` -------------------------------- ### Clone merklelib repository Source: https://github.com/vpaliy/merklelib/blob/master/README.md Command to clone the source code from GitHub. ```bash $ git clone git clone https://github.com/vpaliy/merklelib.git ``` -------------------------------- ### Compare Merkle Trees Source: https://context7.com/vpaliy/merklelib/llms.txt Uses comparison operators to verify that a current log contains all certificates from an older snapshot. ```python old_snapshot = MerkleTree(certificates, sha256) if log >= old_snapshot: print("Current log contains all original certificates") ``` -------------------------------- ### Generate Audit Proofs Source: https://context7.com/vpaliy/merklelib/llms.txt Retrieve an audit proof for a specific leaf to verify its inclusion in the tree. Proofs can be requested using the original data or its hash. ```python from merklelib import MerkleTree # Build tree with transaction data transactions = ['tx_alice_bob', 'tx_bob_carol', 'tx_carol_dave', 'tx_dave_eve'] tree = MerkleTree(transactions) # Get audit proof for a specific transaction proof = tree.get_proof('tx_bob_carol') print(f"Proof contains {len(proof)} nodes") # Output: Proof contains 2 nodes (log2 of 4) # Proof can also be retrieved using the hash value leaf_hash = tree.hexleaves[1] # Hash of 'tx_bob_carol' proof_by_hash = tree.get_proof(leaf_hash) # Invalid leaves return empty proof invalid_proof = tree.get_proof('nonexistent') print(f"Invalid proof length: {len(invalid_proof)}") # Output: Invalid proof length: 0 ``` -------------------------------- ### verify_leaf_inclusion - Standalone Verification Function Source: https://context7.com/vpaliy/merklelib/llms.txt Explains and demonstrates the standalone `verify_leaf_inclusion` function, which allows for leaf verification without direct access to the Merkle tree, using only the root hash. ```APIDOC ## verify_leaf_inclusion - Standalone Verification Function ### Description The standalone `verify_leaf_inclusion` function verifies leaf inclusion without requiring access to the original tree. It takes the target leaf, proof, hash function, and a trusted root hash—useful for client-side verification where only the root hash is known from a trusted authority. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example ```python from merklelib import MerkleTree, verify_leaf_inclusion import hashlib def hashfunc(value): return hashlib.sha256(value).hexdigest() # Server builds the tree server_tree = MerkleTree(['record1', 'record2', 'record3', 'record4'], hashfunc) trusted_root = server_tree.merkle_root # Server provides proof to client proof = server_tree.get_proof('record2') # Client verifies without access to full tree is_valid = verify_leaf_inclusion( target='record2', proof=proof, hashobj=hashfunc, root_hash=trusted_root ) print(f"Record verified: {is_valid}") # Verification fails with wrong root fake_root = "0" * 64 is_valid = verify_leaf_inclusion('record2', proof, hashfunc, fake_root) print(f"Verification with fake root: {is_valid}") ``` ### Response #### Success Response (200) N/A (Illustrative code) #### Response Example ``` Record verified: True Verification with fake root: False ``` ``` -------------------------------- ### Compare Merkle Trees via Operators Source: https://context7.com/vpaliy/merklelib/llms.txt Uses comparison operators to verify tree consistency and equality. ```python from merklelib import MerkleTree # Version 1 of database v1_tree = MerkleTree(['record_a', 'record_b', 'record_c']) # Version 2 adds more records v2_tree = MerkleTree(['record_a', 'record_b', 'record_c', 'record_d', 'record_e']) # Check if v2 is consistent with v1 (contains v1's data) if v2_tree >= v1_tree: print("v2 is a valid extension of v1") # Output: v2 is a valid extension of v1 # Reverse check if v1_tree <= v2_tree: print("v1 is a valid subset of v2") # Output: v1 is a valid subset of v2 # Equality check same_tree = MerkleTree(['record_a', 'record_b', 'record_c']) if v1_tree == same_tree: print("Trees are identical") # Output: Trees are identical ``` -------------------------------- ### MerkleTree Comparison Operators - Consistency via Operators Source: https://context7.com/vpaliy/merklelib/llms.txt Explains how MerkleTree supports comparison operators (`>=`, `<=`, `>`, `<`) to efficiently check tree consistency, ensuring one tree contains the data of another. ```APIDOC ## MerkleTree Comparison Operators - Consistency via Operators ### Description MerkleTree supports comparison operators (`>=`, `<=`, `>`, `<`) to check tree consistency. The `>=` operator verifies that the left tree contains all data from the right tree in the same order. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example ```python from merklelib import MerkleTree # Version 1 of database v1_tree = MerkleTree(['record_a', 'record_b', 'record_c']) # Version 2 adds more records v2_tree = MerkleTree(['record_a', 'record_b', 'record_c', 'record_d', 'record_e']) # Check if v2 is consistent with v1 (contains v1's data) if v2_tree >= v1_tree: print("v2 is a valid extension of v1") # Reverse check if v1_tree <= v2_tree: print("v1 is a valid subset of v2") # Equality check same_tree = MerkleTree(['record_a', 'record_b', 'record_c']) if v1_tree == same_tree: print("Trees are identical") ``` ### Response #### Success Response (200) N/A (Illustrative code) #### Response Example ``` v2 is a valid extension of v1 v1 is a valid subset of v2 Trees are identical ``` ``` -------------------------------- ### MerkleTree.get_proof - Generating Audit Proofs Source: https://context7.com/vpaliy/merklelib/llms.txt The `get_proof` method generates an audit proof for a specific leaf. An audit proof is a collection of sibling hashes needed to reconstruct the path from the leaf to the Merkle root, enabling verification that a data item exists in the tree without accessing all data. ```APIDOC ## MerkleTree.get_proof - Generating Audit Proofs ### Description Generates an audit proof (list of sibling hashes) for a given data item or its hash, which can be used to verify the item's inclusion in the Merkle tree. ### Method `get_proof` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **leaf_identifier** (any) - Required - The data item or its hash for which to generate the proof. ### Request Example ```python from merklelib import MerkleTree transactions = ['tx_alice_bob', 'tx_bob_carol', 'tx_carol_dave', 'tx_dave_eve'] tree = MerkleTree(transactions) proof = tree.get_proof('tx_bob_carol') # proof will be a list of sibling hashes leaf_hash = tree.hexleaves[1] proof_by_hash = tree.get_proof(leaf_hash) ``` ### Response #### Success Response (200) - **proof** (list) - A list of hexadecimal strings representing the sibling hashes required for verification. #### Response Example ```json { "proof": ["sibling_hash1", "sibling_hash2"] } ``` ``` -------------------------------- ### Configure Custom Hasher Source: https://context7.com/vpaliy/merklelib/llms.txt Use the Hasher class to define custom hashing logic that prevents second preimage attacks by prepending specific bytes to leaves and internal nodes. ```python import hashlib from merklelib import MerkleTree from merklelib.merkle import Hasher # Create a custom hasher with SHA-512 def sha512_hash(value): return hashlib.sha512(value).hexdigest() hasher = Hasher(sha512_hash) # Hasher prepends bytes for security leaf_data = b'my_data' leaf_hash = hasher.hash_leaf(leaf_data) # Internally computes: sha512(b'\x00' + leaf_data) # For combining child nodes left_hash = hasher.hash_leaf(b'left') right_hash = hasher.hash_leaf(b'right') parent_hash = hasher.hash_children(left_hash, right_hash) # Internally computes: sha512(b'\x01' + left_hash + right_hash) # Use hasher with MerkleTree tree = MerkleTree(['data1', 'data2', 'data3'], hasher) print(f"Tree with custom hasher: {tree.merkle_root}") ``` -------------------------------- ### Export Tree to File Source: https://context7.com/vpaliy/merklelib/llms.txt Save the Merkle tree structure to a file in JSON, JPG, or PNG formats. Graphviz is required for image exports. ```python from merklelib import MerkleTree, export # Build tree transactions = ['tx1', 'tx2', 'tx3', 'tx4'] tree = MerkleTree(transactions) # Export to JSON (default) export(tree, filename='merkle_tree') # Creates: merkle_tree.json # Export to image (requires graphviz) export(tree, filename='merkle_tree', ext='png') # Creates: merkle_tree.png export(tree, filename='merkle_tree', ext='jpg') # Creates: merkle_tree.jpg # Export with absolute path export(tree, filename='/path/to/output/tree', ext='json') ``` -------------------------------- ### Verify Tree Consistency with Function Source: https://github.com/vpaliy/merklelib/blob/master/README.md Uses the verify_tree_consistency function to check if a new tree version is consistent with an older one. ```python from merkelib import MerkleTree, verify_tree_consistency ... ... ... # information that we need to provide old_hash_root = old_tree.merkle_hash old_tree_size = len(old_tree) # check if the new tree contains the same items ``` -------------------------------- ### MerkleTree - Building a Merkle Tree Source: https://context7.com/vpaliy/merklelib/llms.txt The MerkleTree class is the core component for creating and managing Merkle trees. It accepts a collection of data items and an optional hash function (defaults to SHA-256). The tree is automatically built upon initialization, computing the Merkle root hash that represents the integrity of all data. ```APIDOC ## MerkleTree - Building a Merkle Tree ### Description Initializes a Merkle tree with a collection of data items and an optional custom hash function. The Merkle root is computed automatically. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (list) - Required - A list of data items to include in the tree. - **hash_function** (function) - Optional - A custom hash function to use. Defaults to SHA-256. ### Request Example ```python import hashlib from merklelib import MerkleTree def hashfunc(value): return hashlib.sha256(value).hexdigest() transactions = ['tx1', 'tx2', 'tx3', 'tx4', 'tx5', 'tx6', 'tx7', 'tx8'] tree = MerkleTree(transactions, hashfunc) ``` ### Response #### Success Response (200) - **merkle_root** (str) - The hexadecimal string of the Merkle root hash. - **leaves** (list) - A list of the leaf hashes in hexadecimal format. - **size** (int) - The number of leaves in the tree. #### Response Example ```json { "merkle_root": "a1b2c3d4e5f6...", "leaves": ["hash1", "hash2", ...], "size": 8 } ``` ``` -------------------------------- ### Verify Log Consistency Source: https://context7.com/vpaliy/merklelib/llms.txt Checks that the current log state is consistent with a previous snapshot to ensure append-only integrity. ```python is_consistent = verify_tree_consistency(log, snapshot_root, snapshot_size) print(f"Log is append-only: {is_consistent}") ``` -------------------------------- ### Perform Merkle Tree Consistency Check Source: https://github.com/vpaliy/merklelib/blob/master/README.md Compares two versions of a Merkle tree using comparison operators to ensure data consistency. ```python tree = MerkleTree(get_data()) ... ... ... new_tree = MerkleTree(get_new_data()) # check if the new tree contains the same items # and in the same order as the old version if tree <= new_tree: print('Versions are consistent') else: exit('Versions are different') ``` -------------------------------- ### Verify Merkle Tree Consistency Source: https://github.com/vpaliy/merklelib/blob/master/README.md Checks if a new tree version is consistent with an old hash root and tree size. ```python if verify_tree_consistency(new_tree, old_hash_root, old_tree_size): print('Versions are consistent') else: exit('Versions are different') ``` -------------------------------- ### Verify Tree Consistency Source: https://context7.com/vpaliy/merklelib/llms.txt Checks if a newer tree is a valid extension of an older tree, ensuring data integrity for append-only logs. ```python from merklelib import MerkleTree, verify_tree_consistency # Original database state original_data = ['entry1', 'entry2', 'entry3'] old_tree = MerkleTree(original_data) old_root = old_tree.merkle_root old_size = len(old_tree) # Database grows over time new_data = ['entry1', 'entry2', 'entry3', 'entry4', 'entry5'] new_tree = MerkleTree(new_data) # Verify consistency - new tree contains old tree's data is_consistent = verify_tree_consistency(new_tree, old_root, old_size) print(f"Trees are consistent: {is_consistent}") # Output: Trees are consistent: True # Inconsistent if data was modified tampered_data = ['entry1', 'MODIFIED', 'entry3', 'entry4'] tampered_tree = MerkleTree(tampered_data) is_consistent = verify_tree_consistency(tampered_tree, old_root, old_size) print(f"Tampered tree consistent: {is_consistent}") # Output: Tampered tree consistent: False ``` -------------------------------- ### Export Merkle Tree Source: https://github.com/vpaliy/merklelib/blob/master/README.md Exports the Merkle tree structure to a file, such as a JPG image or JSON file. ```python from merklelib import MerkleTree, export transactions = get_transactions(user) # random data tree = MerkleTree(transactions) export(tree, filename='transactions', ext='jpg') ``` -------------------------------- ### Clear and Repopulate Tree Source: https://context7.com/vpaliy/merklelib/llms.txt The clear method resets the tree to an empty state, allowing for subsequent data population. ```python from merklelib import MerkleTree # Build tree with data tree = MerkleTree(['a', 'b', 'c', 'd']) print(f"Before clear: {len(tree)} leaves") # Output: Before clear: 4 leaves # Clear all data tree.clear() print(f"After clear: {len(tree)} leaves") print(f"Root after clear: {tree.merkle_root}") # Output: After clear: 0 leaves # Output: Root after clear: None # Repopulate the tree tree.extend(['x', 'y', 'z']) print(f"After repopulate: {len(tree)} leaves") # Output: After repopulate: 3 leaves ``` -------------------------------- ### MerkleTree.append - Adding Leaves to Tree Source: https://context7.com/vpaliy/merklelib/llms.txt The `append` method adds a new leaf to the end of an existing Merkle tree. The tree is automatically rebalanced and the Merkle root is recalculated. This is efficient for incrementally building trees without reconstructing from scratch. ```APIDOC ## MerkleTree.append - Adding Leaves to Tree ### Description Appends a single data item to the end of the Merkle tree, automatically rebalancing and recalculating the Merkle root. ### Method `append` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data_item** (any) - Required - The data item to append to the tree. ### Request Example ```python from merklelib import MerkleTree tree = MerkleTree(['block1', 'block2', 'block3']) tree.append('block4') ``` ### Response #### Success Response (200) - **merkle_root** (str) - The updated Merkle root hash. - **size** (int) - The new number of leaves in the tree. #### Response Example ```json { "merkle_root": "new_root_hash", "size": 4 } ``` ``` -------------------------------- ### jsonify - Convert Tree to JSON String Source: https://context7.com/vpaliy/merklelib/llms.txt Convert a Merkle tree into a JSON string representation using the `jsonify` function, ideal for API responses, logging, or immediate data manipulation. ```APIDOC ## jsonify - Convert Tree to JSON String The `jsonify` function converts a Merkle tree to a JSON string representation. This is useful for API responses, logging, or when you need the JSON data without writing to a file. ```python from merklelib import MerkleTree, jsonify import json # Build tree data = ['item1', 'item2', 'item3', 'item4'] tree = MerkleTree(data) # Convert to JSON string json_str = jsonify(tree) print(json_str) # Output: {"name": "root_hash", "children": [...]} # Parse and use the JSON tree_data = json.loads(json_str) print(f"Root node: {tree_data['name']}") ``` ``` -------------------------------- ### MerkleTree.verify_leaf_inclusion - Verifying Data Inclusion Source: https://context7.com/vpaliy/merklelib/llms.txt The `verify_leaf_inclusion` method verifies that a leaf is included in the tree using an audit proof. It reconstructs the path to the root and compares against the stored Merkle root. This is the primary method for validating data integrity. ```APIDOC ## MerkleTree.verify_leaf_inclusion - Verifying Data Inclusion ### Description Verifies if a given data item is included in the Merkle tree using its audit proof. It reconstructs the path to the root and compares it with the tree's actual Merkle root. ### Method `verify_leaf_inclusion` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **leaf** (any) - Required - The data item to verify. - **proof** (list) - Required - The audit proof (list of sibling hashes) for the leaf. ### Request Example ```python from merklelib import MerkleTree files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt'] tree = MerkleTree(files) leaf_to_verify = 'file2.txt' proof_for_leaf = tree.get_proof(leaf_to_verify) is_valid = tree.verify_leaf_inclusion(leaf_to_verify, proof_for_leaf) print(f"Is '{leaf_to_verify}' included? {is_valid}") ``` ### Response #### Success Response (200) - **is_valid** (boolean) - True if the leaf is verified to be included in the tree, False otherwise. #### Response Example ```json { "is_valid": true } ``` ``` -------------------------------- ### Bulk Add Leaves with extend Source: https://context7.com/vpaliy/merklelib/llms.txt The extend method allows adding multiple leaves from an iterable or merging another MerkleTree instance into the current tree. ```python from merklelib import MerkleTree # Create initial tree tree = MerkleTree(['a', 'b', 'c']) # Extend with a list new_data = ['d', 'e', 'f', 'g'] tree.extend(new_data) print(f"Size after extend: {len(tree)}") # Output: Size after extend: 7 # Extend with another MerkleTree other_tree = MerkleTree(['h', 'i', 'j']) tree.extend(other_tree) print(f"Size after merging trees: {len(tree)}") # Output: Size after merging trees: 10 ``` -------------------------------- ### Verify Leaf Inclusion Source: https://context7.com/vpaliy/merklelib/llms.txt Verifies if a specific leaf exists within the Merkle tree using a proof and a trusted root. ```python is_valid = verify_leaf_inclusion( client_cert, proof, sha256, trusted_root ) print(f"Certificate verified: {is_valid}") ``` -------------------------------- ### MerkleTree.extend - Bulk Adding Leaves Source: https://context7.com/vpaliy/merklelib/llms.txt The `extend` method appends multiple leaves to the tree at once. It accepts any iterable collection or another MerkleTree instance, iterating through each item and appending it to the tree. ```APIDOC ## MerkleTree.extend - Bulk Adding Leaves ### Description Appends multiple data items from an iterable or another MerkleTree to the current tree, updating the Merkle root. ### Method `extend` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (iterable or MerkleTree) - Required - An iterable collection of data items or another MerkleTree instance to merge. ### Request Example ```python from merklelib import MerkleTree tree = MerkleTree(['a', 'b', 'c']) new_data = ['d', 'e', 'f', 'g'] tree.extend(new_data) other_tree = MerkleTree(['h', 'i', 'j']) tree.extend(other_tree) ``` ### Response #### Success Response (200) - **merkle_root** (str) - The updated Merkle root hash. - **size** (int) - The new total number of leaves in the tree. #### Response Example ```json { "merkle_root": "final_root_hash", "size": 10 } ``` ``` -------------------------------- ### Convert Tree to JSON String Source: https://context7.com/vpaliy/merklelib/llms.txt Use jsonify to obtain a JSON string representation of the tree for API responses or logging. ```python from merklelib import MerkleTree, jsonify import json # Build tree data = ['item1', 'item2', 'item3', 'item4'] tree = MerkleTree(data) # Convert to JSON string json_str = jsonify(tree) print(json_str) # Output: {"name": "root_hash", "children": [...]} # Parse and use the JSON tree_data = json.loads(json_str) print(f"Root node: {tree_data['name']}") ``` -------------------------------- ### Append Leaves to a Merkle Tree Source: https://context7.com/vpaliy/merklelib/llms.txt Use the append method to add a single leaf to an existing tree, which triggers automatic rebalancing and root recalculation. ```python from merklelib import MerkleTree # Start with initial data tree = MerkleTree(['block1', 'block2', 'block3']) print(f"Initial root: {tree.merkle_root}") print(f"Initial size: {len(tree)}") # Append new blocks tree.append('block4') print(f"After append root: {tree.merkle_root}") print(f"After append size: {len(tree)}") # Output: After append size: 4 # Append multiple items one at a time for i in range(5, 10): tree.append(f'block{i}') print(f"Final size: {len(tree)}") # Output: Final size: 9 ``` -------------------------------- ### Standalone Leaf Inclusion Verification Source: https://context7.com/vpaliy/merklelib/llms.txt Verifies leaf inclusion without requiring the full tree object, using only the target, proof, hash function, and root hash. ```python from merklelib import MerkleTree, verify_leaf_inclusion import hashlib def hashfunc(value): return hashlib.sha256(value).hexdigest() # Server builds the tree server_tree = MerkleTree(['record1', 'record2', 'record3', 'record4'], hashfunc) trusted_root = server_tree.merkle_root # Server provides proof to client proof = server_tree.get_proof('record2') # Client verifies without access to full tree # Only needs: target data, proof, hash function, trusted root is_valid = verify_leaf_inclusion( target='record2', proof=proof, hashobj=hashfunc, root_hash=trusted_root ) print(f"Record verified: {is_valid}") # Output: Record verified: True # Verification fails with wrong root fake_root = "0" * 64 is_valid = verify_leaf_inclusion('record2', proof, hashfunc, fake_root) print(f"Verification with fake root: {is_valid}") # Output: Verification with fake root: False ``` -------------------------------- ### Update Merkle Tree Leaf Values Source: https://context7.com/vpaliy/merklelib/llms.txt Replaces an existing leaf with a new value and automatically recalculates the Merkle root. ```python from merklelib import MerkleTree # Build tree with user balances balances = ['alice:100', 'bob:200', 'carol:150', 'dave:300'] tree = MerkleTree(balances) print(f"Original root: {tree.merkle_root}") # Update Bob's balance tree.update('bob:200', 'bob:250') print(f"Updated root: {tree.merkle_root}") # Root changes after update # Can also update using hash values old_hash = tree.hexleaves[2] # carol's hash # tree.update(old_hash, new_hash) # Update by hash # Invalid old value raises KeyError try: tree.update('nonexistent', 'new_value') except KeyError as e: print(f"Error: {e}") # Output: Error: 'Invalid old value.' ``` -------------------------------- ### Verify Leaf Inclusion Source: https://context7.com/vpaliy/merklelib/llms.txt Validate data integrity by verifying that a leaf exists in the tree using its audit proof. ```python from merklelib import MerkleTree # Build tree with file hashes files = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt'] tree = MerkleTree(files) ``` -------------------------------- ### MerkleTree.clear - Clearing the Tree Source: https://context7.com/vpaliy/merklelib/llms.txt Resets the Merkle tree to an empty state by removing all leaves and nodes using the `clear` method, allowing for repopulation. ```APIDOC ## MerkleTree.clear - Clearing the Tree The `clear` method removes all leaves and nodes from the tree, resetting it to an empty state. The tree can then be repopulated using `append` or `extend`. ```python from merklelib import MerkleTree # Build tree with data tree = MerkleTree(['a', 'b', 'c', 'd']) print(f"Before clear: {len(tree)} leaves") # Output: Before clear: 4 leaves # Clear all data tree.clear() print(f"After clear: {len(tree)} leaves") print(f"Root after clear: {tree.merkle_root}") # Output: After clear: 0 leaves # Output: Root after clear: None # Repopulate the tree tree.extend(['x', 'y', 'z']) print(f"After repopulate: {len(tree)} leaves") # Output: After repopulate: 3 leaves ``` ``` -------------------------------- ### MerkleTree.update - Updating Leaf Values Source: https://context7.com/vpaliy/merklelib/llms.txt Details the `update` method for modifying existing leaf values in a Merkle tree and recalculating the root. It also covers error handling for invalid old values. ```APIDOC ## MerkleTree.update - Updating Leaf Values ### Description The `update` method replaces an existing leaf with a new value and recalculates the affected path up to the root. Both the old and new values must be of the same type. The Merkle root is automatically updated to reflect the change. ### Method N/A (Illustrative code) ### Endpoint N/A (Illustrative code) ### Parameters N/A ### Request Example ```python from merklelib import MerkleTree # Build tree with user balances balances = ['alice:100', 'bob:200', 'carol:150', 'dave:300'] tree = MerkleTree(balances) print(f"Original root: {tree.merkle_root}") # Update Bob's balance tree.update('bob:200', 'bob:250') print(f"Updated root: {tree.merkle_root}") # Invalid old value raises KeyError try: tree.update('nonexistent', 'new_value') except KeyError as e: print(f"Error: {e}") ``` ### Response #### Success Response (200) N/A (Illustrative code) #### Response Example ``` Original root: [some_hash_value] Updated root: [new_hash_value] Error: 'Invalid old value.' ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.