### Specify backend at runtime (Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/quickstart.md Shows how to explicitly instantiate the Keccak256 hasher with a specific backend (pysha3) at runtime. This provides direct control over which hashing implementation is used. ```python from eth_hash.backends import pysha3 from eth_hash import Keccak256 keccak = Keccak256(pysha3) keccak(b'') # Expected output: b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" ``` -------------------------------- ### Compute Keccak256 hash (Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/quickstart.md Computes a Keccak256 hash of an empty byte string using the automatically selected backend. This is a basic example demonstrating the core hashing functionality. ```python from eth_hash.auto import keccak keccak(b'') # Expected output: b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" ``` -------------------------------- ### Copy and use incremental hash object (Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/quickstart.md Shows how to create a Keccak256 hash object, copy it, update the original and the copy independently, and then digest both. This highlights the ability to branch hashing processes. ```python from eth_hash.auto import keccak preimage = keccak.new(b'part-a') preimage_copy = preimage.copy() preimage.update(b'part-b') preimage.digest() preimage_copy.update(b'part-c') preimage_copy.digest() # Expected output for preimage.digest(): b'6\x91l\xdd50\xd6[\x7f\xf9B\xff\xc9SW\x98\xc3\xaal\xd9\xde\xdd6I\xb7\x91\x9e\xf4`pl\x08' # Expected output for preimage_copy.digest(): b'\xffcy45\xea\xdd\xdf\x8e(\x1c\xfcF\xf3\xd4\xa1S\x0f\xdf\xd8\x01!\xb2(\xe1\xc7\xc6\xa3\x08\xc3\n\x0b' ``` -------------------------------- ### Specify backend via environment variable (Shell/Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/quickstart.md Demonstrates how to run a Python script using a specific hashing backend ('pysha3' in this case) by setting the ETH_HASH_BACKEND environment variable. This allows for backend selection without modifying the code. ```shell $ ETH_HASH_BACKEND="pysha3" python >>> from eth_hash.auto import keccak # This runs with the pysha3 backend >>> keccak(b'') # Expected output: b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" ``` -------------------------------- ### Install eth-hash with pycryptodome or pysha3 backend Source: https://context7.com/ethereum/eth-hash/llms.txt Installs the eth-hash library with a specified cryptographic backend. The `pycryptodome` backend is recommended and supports PyPy3. The `pysha3` backend is an alternative option. ```bash # Install with pycryptodome backend (recommended, supports pypy3) python -m pip install "eth-hash[pycryptodome]" # Or install with pysha3 backend python -m pip install "eth-hash[pysha3]" ``` -------------------------------- ### Install eth-hash with pycryptodome backend Source: https://github.com/ethereum/eth-hash/blob/main/README.md This command installs the eth-hash library along with the pycryptodome backend, which is recommended for cryptographic operations. It uses pip, Python's package installer. ```sh python -m pip install "eth-hash[pycryptodome]" ``` -------------------------------- ### Compute Keccak256 hash incrementally (Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/quickstart.md Demonstrates incremental Keccak256 hashing by creating a new hash object, updating it with multiple byte strings, and then digesting the result. This is useful for hashing large data in chunks. ```python from eth_hash.auto import keccak preimage = keccak.new(b'part-a') preimage.update(b'part-b') preimage.digest() # Expected output: b'6\x91l\xdd50\xd6[\x7f\xf9B\xff\xc9SW\x98\xc3\xaal\xd9\xde\xdd6I\xb7\x91\x9e\xf4`pl\x08' ``` -------------------------------- ### Using Supported Keccak256 Backends in Python Source: https://context7.com/ethereum/eth-hash/llms.txt Shows how to use the two supported Keccak-256 hashing backends: pycryptodome (recommended) and pysha3. Both backends provide identical Keccak-256 hash results but differ in their underlying implementation and dependencies. This example demonstrates importing and using functions from each backend. ```python from eth_hash.backends import SUPPORTED_BACKENDS print(SUPPORTED_BACKENDS) # ['pycryptodome', 'pysha3'] # pycryptodome backend - recommended, supports pypy3 from eth_hash.backends.pycryptodome import backend as crypto_backend from eth_hash.backends.pycryptodome import keccak256 as crypto_keccak result = crypto_keccak(b'test') print(f"pycryptodome: {result.hex()}") # pysha3 backend - alternative implementation from eth_hash.backends.pysha3 import backend as sha3_backend from eth_hash.backends.pysha3 import keccak256 as sha3_keccak result = sha3_keccak(b'test') print(f"pysha3: {result.hex()}") # Both produce identical results assert crypto_keccak(b'ethereum') == sha3_keccak(b'ethereum') ``` -------------------------------- ### Handling Errors with eth-hash in Python Source: https://context7.com/ethereum/eth-hash/llms.txt Demonstrates common error scenarios and exception handling when using the eth-hash library. It covers `TypeError` for invalid input data types, `ImportError` when no hashing backend is installed, and `ValueError` for unsupported environment backend configurations. ```python from eth_hash.auto import keccak # TypeError for invalid input types try: keccak("string") # Must be bytes or bytearray except TypeError as e: print(f"TypeError: {e}") # TypeError: Can only compute the hash of `bytes` or `bytearray` values, not 'string' try: keccak(123) # Numbers not allowed except TypeError as e: print(f"TypeError: {e}") # TypeError: Can only compute the hash of `bytes` or `bytearray` values, not 123 # ImportError when no backend is installed # (This would occur if eth-hash is installed without any backend extras) try: from eth_hash.auto import keccak keccak(b'test') except ImportError as e: print(f"ImportError: {e}") # ImportError: None of these hashing backends are installed: ['pycryptodome', 'pysha3']. # Install with `python -m pip install "eth-hash[pycryptodome]"`. # ValueError for invalid environment backend import os os.environ["ETH_HASH_BACKEND"] = "invalid_backend" try: from eth_hash.utils import load_environment_backend load_environment_backend("invalid_backend") except ValueError as e: print(f"ValueError: {e}") # ValueError: The backend specified in ETH_HASH_BACKEND, 'invalid_backend', is not supported. ``` -------------------------------- ### Implement Custom Hashing Backend with Python Source: https://context7.com/ethereum/eth-hash/llms.txt Demonstrates how to create a custom hashing backend by extending the BackendAPI and PreImageAPI abstract classes. This allows for custom Keccak-256 implementations or integration with other hashing algorithms. It shows how to define `keccak256` for one-shot hashing and `preimage` for incremental hashing. ```python from eth_hash.abc import BackendAPI, PreImageAPI import hashlib class CustomPreimage(PreImageAPI): """Custom preimage implementation using hashlib.""" def __init__(self, value: bytes) -> None: # Note: This is SHA3-256, not Keccak-256 (they differ!) # This is just for demonstration purposes self._hash = hashlib.sha3_256(value) self._parts = [value] def update(self, value: bytes) -> None: self._hash.update(value) self._parts.append(value) def digest(self) -> bytes: return self._hash.digest() def copy(self) -> "CustomPreimage": new_preimage = CustomPreimage(b".join(self._parts)) return new_preimage class CustomBackend(BackendAPI): """Custom backend implementation.""" def keccak256(self, in_data: bytearray | bytes) -> bytes: # Real implementation would use actual Keccak-256 return hashlib.sha3_256(in_data).digest() def preimage(self, in_data: bytearray | bytes) -> PreImageAPI: return CustomPreimage(in_data) # Use custom backend from eth_hash import Keccak256 custom_keccak = Keccak256(CustomBackend()) result = custom_keccak(b'custom backend') ``` -------------------------------- ### Configure eth-hash backend via environment variable Source: https://context7.com/ethereum/eth-hash/llms.txt Configures the hashing backend for `eth-hash` by setting the `ETH_HASH_BACKEND` environment variable. This allows switching between backends like `pysha3` or `pycryptodome` without modifying the Python code. ```bash # Set backend via environment variable before running Python export ETH_HASH_BACKEND="pysha3" python -c "from eth_hash.auto import keccak; print(keccak(b'test').hex())" # Or set inline ETH_HASH_BACKEND="pycryptodome" python your_script.py ``` -------------------------------- ### Initialize Keccak256 Hashing with Preimage (Python) Source: https://github.com/ethereum/eth-hash/blob/main/docs/eth_hash.md Initializes the Keccak256 hashing object with a given preimage. The preimage can be provided as a bytearray or bytes. This is a core step before performing hashing operations. ```python from eth_hash.main import Keccak256 preimage_bytes = b'some data' keccak_hasher = Keccak256(preimage_bytes) ``` -------------------------------- ### Direct Keccak256 backend usage with eth-hash Source: https://context7.com/ethereum/eth-hash/llms.txt Demonstrates explicit backend selection using the `Keccak256` class from `eth_hash`. This allows specifying a backend like `pycryptodome` or `pysha3` at runtime for deterministic hashing behavior. ```python from eth_hash import Keccak256 from eth_hash.backends import pycryptodome # Create hasher with explicit backend keccak = Keccak256(pycryptodome) # One-shot hashing result = keccak(b'ethereum') print(result.hex()) # 541b31c1baf6c6b15ada3d9c9fc9e028c879bae6b58b42a5d55ace1cbb75a77c # Incremental hashing preimage = keccak.new(b'block-') preimage.update(b'header') print(preimage.digest().hex()) # Using pysha3 backend instead from eth_hash.backends import pysha3 keccak_sha3 = Keccak256(pysha3) result = keccak_sha3(b'ethereum') # Same result, different backend implementation ``` -------------------------------- ### Programmatic eth-hash backend configuration via environment variable Source: https://context7.com/ethereum/eth-hash/llms.txt Sets the `ETH_HASH_BACKEND` environment variable programmatically within a Python script to configure the hashing backend. This must be done before importing `eth_hash.auto` to take effect. ```python import os # Set environment variable programmatically (before importing eth_hash.auto) os.environ["ETH_HASH_BACKEND"] = "pycryptodome" from eth_hash.auto import keccak result = keccak(b'configured via env') print(result.hex()) ``` -------------------------------- ### Incremental Hashing with PreImageAPI in Python Source: https://context7.com/ethereum/eth-hash/llms.txt Illustrates the usage of the PreImageAPI for incremental hashing. This interface allows for hashing data in chunks, maintaining the hash state across multiple updates. It demonstrates the `update`, `digest`, and `copy` methods for managing the hashing process and its state. ```python from eth_hash.auto import keccak # Create a preimage object preimage = keccak.new(b'initial') # update(value: bytes) - Add more data to hash preimage.update(b'-middle') preimage.update(b'-final') # digest() -> bytes - Get current hash (doesn't reset state) hash1 = preimage.digest() hash2 = preimage.digest() # Same result, state preserved assert hash1 == hash2 # copy() -> PreImageAPI - Clone current state for branching original = keccak.new(b'base') clone = original.copy() original.update(b'-path-1') clone.update(b'-path-2') # Different hashes from same starting point assert original.digest() != clone.digest() print(f"Original: {original.digest().hex()}") print(f"Clone: {clone.digest().hex()}") ``` -------------------------------- ### Perform incremental Keccak-256 hashing with eth-hash Source: https://context7.com/ethereum/eth-hash/llms.txt Utilizes the `keccak.new()` method from `eth_hash.auto` to create a preimage object for incremental hashing. This object supports `update()`, `digest()`, and `copy()` methods, allowing hash computation from multiple data chunks or branching hash calculations. ```python from eth_hash.auto import keccak # Create preimage and build hash incrementally preimage = keccak.new(b'part-a') preimage.update(b'part-b') result = preimage.digest() print(result.hex()) # 36916cdd3530d65b7ff942ffc95357983caa6cd9dedd3649b7919ef460706c08 # Equivalent to hashing concatenated data assert keccak(b'part-apart-b') == result # Continue updating after digest (hash state is preserved) preimage.update(b'part-c') new_result = preimage.digest() print(new_result.hex()) # Different hash including all three parts # Copy preimage to branch hash computation preimage = keccak.new(b'common-prefix') preimage_copy = preimage.copy() preimage.update(b'-branch-a') preimage_copy.update(b'-branch-b') result_a = preimage.digest() result_b = preimage_copy.digest() print(f"Branch A: {result_a.hex()}") print(f"Branch B: {result_b.hex()}") # Two different hashes from common starting point ``` -------------------------------- ### Calculate keccak256 hash of empty bytes Source: https://github.com/ethereum/eth-hash/blob/main/README.md This Python code snippet demonstrates how to use the `keccak` function from `eth_hash.auto` to compute the keccak256 hash of an empty byte string. The result is the 32-byte hash value. ```python >>> from eth_hash.auto import keccak >>> keccak(b'') b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" ``` -------------------------------- ### Compute Keccak-256 hash using eth-hash (one-shot) Source: https://context7.com/ethereum/eth-hash/llms.txt Computes the Keccak-256 hash of bytes or bytearray data in a single function call using the `eth_hash.auto.keccak` function. It returns a 32-byte hash digest. The function enforces type checking, accepting only `bytes` or `bytearray`. ```python from eth_hash.auto import keccak # Hash empty bytes result = keccak(b'') print(result) # b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';{\xfa\xd8\x04]\x85\xa4p" # Hash a simple message result = keccak(b'hello world') print(result.hex()) # 47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad # Works with bytearray as well data = bytearray(b'ethereum') result = keccak(data) print(result.hex()) # 541b31c1baf6c6b15ada3d9c9fc9e028c879bae6b58b42a5d55ace1cbb75a77c # Type checking - only bytes/bytearray accepted try: keccak("string not allowed") except TypeError as e: print(f"Error: {e}") # Error: Can only compute the hash of `bytes` or `bytearray` values, not 'string not allowed' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.