Python eth_utils.keccak() Examples

The following are 19 code examples of eth_utils.keccak(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_utils , or try the search function .
Example #1
Source File: test_factory.py    From vyper with Apache License 2.0 5 votes vote down vote up
def factory(get_contract):
    with open("examples/factory/Exchange.vy") as f:
        code = f.read()

    exchange_interface = vyper.compile_code(code, output_formats=["bytecode_runtime"])
    exchange_deployed_bytecode = exchange_interface["bytecode_runtime"]

    with open("examples/factory/Factory.vy") as f:
        code = f.read()

    # NOTE: We deploy the factory with the hash of the exchange's expected deployment bytecode
    return get_contract(code, keccak(hexstr=exchange_deployed_bytecode)) 
Example #2
Source File: zero_ex_transaction_encoder_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _struct_hash(primaryType: str, data: any, types) -> str:
    return keccak(_encode_data(primaryType, data, types)) 
Example #3
Source File: zero_ex_transaction_encoder_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _type_hash(primaryType: str, types) -> str:
    return keccak(_encode_type(primaryType, types).encode()) 
Example #4
Source File: zero_ex_transaction_encoder_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _encode_data(primaryType: str, data: any, types) -> str:
    encodedTypes = ['bytes32']
    encodedValues = [_type_hash(primaryType, types)]

    for field in types[primaryType]:
        value = data[field['name']]

        if field['type'] == 'string':
            hashValue = keccak(text=value)
            encodedTypes.append('bytes32')
            encodedValues.append(hashValue)

        elif field['type'] == 'bytes':
            hashValue = keccak(hexstr=value)
            encodedTypes.append('bytes32')
            encodedValues.append(hashValue)

        elif field['type'] in types:
            encodedTypes.append('bytes32')
            hashValue = keccak(_encode_data(field['type'], value, types).encode())
            encodedValues.append(hashValue)

        elif field['type'] == 'uint256':
            encodedTypes.append('uint256')
            encodedValues.append(int(value))

        else:
            encodedTypes.append(field['type'])
            normalizedValue = _normalize_value(field['type'], value)
            encodedValues.append(normalizedValue)

    return encode_abi(encodedTypes, encodedValues) 
Example #5
Source File: zero_ex_transaction_encoder_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def generate_typed_data_hash(typedData: EIP712TypedData) -> str:
    return '0x' + keccak(
        b"\x19\x01" +
        _struct_hash('EIP712Domain', typedData['domain'], typedData['types']) +
        _struct_hash(typedData['primaryType'], typedData['message'], typedData['types'])
    ).hex() 
Example #6
Source File: hash.py    From research with MIT License 5 votes vote down vote up
def hash(x): return keccak(x) 
Example #7
Source File: channel.py    From raiden-contracts with MIT License 5 votes vote down vote up
def get_participants_hash(A: HexAddress, B: HexAddress) -> bytes:
    A_canonical = to_canonical_address(A)
    B_canonical = to_canonical_address(B)
    if A_canonical == B_canonical:
        raise ValueError("get_participants_hash got the same address twice")
    return (
        keccak(A_canonical + B_canonical)
        if A_canonical < B_canonical
        else keccak(B_canonical + A_canonical)
    ) 
Example #8
Source File: pending_transfers.py    From raiden-contracts with MIT License 5 votes vote down vote up
def get_pending_transfers_tree(
    web3: Web3,
    unlockable_amounts: Collection[int],
    expired_amounts: Collection[int],
    min_expiration_delta: Optional[int] = None,
    max_expiration_delta: Optional[int] = None,
) -> PendingTransfersTree:
    types = ["uint256", "uint256", "bytes32"]
    packed_transfers = b""
    (unlockable_locks, expired_locks) = get_pending_transfers(
        web3=web3,
        unlockable_amounts=unlockable_amounts,
        expired_amounts=expired_amounts,
        min_expiration_delta=min_expiration_delta,
        max_expiration_delta=max_expiration_delta,
    )

    pending_transfers = unlockable_locks + expired_locks

    hashed_pending_transfers = [
        Web3.solidityKeccak(types, transfer_data[:-1])  # pylint: disable=E1120
        for transfer_data in pending_transfers
    ]

    if len(pending_transfers) > 0:
        hashed_pending_transfers, pending_transfers = zip(
            *sorted(zip(hashed_pending_transfers, pending_transfers))
        )
        pending_transfers = list(pending_transfers)
        packed_transfers = get_packed_transfers(pending_transfers=pending_transfers, types=types)

    locked_amount = get_locked_amount(pending_transfers)

    return PendingTransfersTree(
        transfers=pending_transfers,
        unlockable=unlockable_locks,
        expired=expired_locks,
        packed_transfers=packed_transfers,
        hash_of_packed_transfers=keccak(packed_transfers),
        locked_amount=locked_amount,
    ) 
Example #9
Source File: accounts.py    From raiden-services with MIT License 5 votes vote down vote up
def private_keys() -> List[PrivateKey]:
    offset = 14789632
    return [PrivateKey(keccak(offset + i)) for i in range(NUMBER_OF_NODES)] 
Example #10
Source File: utils.py    From raiden-services with MIT License 5 votes vote down vote up
def public_key_to_address(public_key: PublicKey) -> Address:
    """ Converts a public key to an Ethereum address. """
    key_bytes = public_key.format(compressed=False)
    return Address(keccak(key_bytes[1:])[-20:]) 
Example #11
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def sha3_256(x):
    if isinstance(x, bytearray):
        x = bytes(x)
    if not isinstance(x, bytes):
        raise RuntimeError("sha3_256 only accepts bytes or bytearray")
    # TODO: keccak accepts more types than bytes
    return keccak(x) 
Example #12
Source File: test_clampers.py    From vyper with Apache License 2.0 5 votes vote down vote up
def _make_tx(w3, address, signature, values):
    # helper function to broadcast transactions that fail clamping check
    sig = keccak(signature.encode()).hex()[:8]
    data = "".join(int(i).to_bytes(32, "big", signed=i < 0).hex() for i in values)
    w3.eth.sendTransaction({"to": address, "data": f"0x{sig}{data}"}) 
Example #13
Source File: models.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, private_key=None, wei_target_balance=None, wei_topup_threshold=None):

        if private_key:
            self.private_key = private_key
        else:
            self.private_key = Web3.toHex(keccak(os.urandom(4096)))

        self.wei_target_balance = wei_target_balance
        self.wei_topup_threshold = wei_topup_threshold

# https://stackoverflow.com/questions/20830118/creating-a-self-referencing-m2m-relationship-in-sqlalchemy-flask 
Example #14
Source File: models.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def _cipher_suite():
        fernet_encryption_key = base64.b64encode(keccak(text=config.SECRET_KEY))
        return Fernet(fernet_encryption_key) 
Example #15
Source File: blockchain_address.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def encrypt_private_key(self, unencoded_private_key):

        fernet_encryption_key = base64.b64encode(keccak(text=current_app.config['SECRET_KEY']))
        cipher_suite = Fernet(fernet_encryption_key)

        return cipher_suite.encrypt(unencoded_private_key.encode('utf-8')).decode('utf-8') 
Example #16
Source File: blockchain_address.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def decrypted_private_key(self):

        fernet_encryption_key = base64.b64encode(keccak(text=current_app.config['SECRET_KEY']))
        cipher_suite = Fernet(fernet_encryption_key)

        return cipher_suite.decrypt(self.encoded_private_key.encode('utf-8')).decode('utf-8') 
Example #17
Source File: misc.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def encrypt_string(raw_string):

    fernet_encryption_key = base64.b64encode(keccak(text=current_app.config['SECRET_KEY']))
    cipher_suite = Fernet(fernet_encryption_key)

    return cipher_suite.encrypt(raw_string.encode('utf-8')).decode('utf-8') 
Example #18
Source File: misc.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def decrypt_string(encryped_string):

    fernet_encryption_key = base64.b64encode(keccak(text=current_app.config['SECRET_KEY']))
    cipher_suite = Fernet(fernet_encryption_key)

    return cipher_suite.decrypt(encryped_string.encode('utf-8')).decode('utf-8') 
Example #19
Source File: __init__.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def encrypt_string(raw_string):
    import base64
    from cryptography.fernet import Fernet
    from eth_utils import keccak

    fernet_encryption_key = base64.b64encode(keccak(text=config.SECRET_KEY))
    cipher_suite = Fernet(fernet_encryption_key)

    return cipher_suite.encrypt(raw_string.encode('utf-8')).decode('utf-8')