Esempio n. 1
0
def get_cancel_order_hash(order_hash):
    '''
    Returns the final signable EIP712 hash for a cancel order API call.
    '''
    action_hash = Web3.solidityKeccak(
        ['string'],
        [EIP712_CANCEL_ACTION]
    ).hex()
    orders_hash = Web3.solidityKeccak(
        ['bytes32'],
        [order_hash]
    ).hex()
    struct_hash = Web3.solidityKeccak(
        [
            'bytes32',
            'bytes32',
            'bytes32',
        ],
        [
            hash_string(EIP712_CANCEL_ORDER_STRUCT_STRING),
            action_hash,
            orders_hash,
        ]
    ).hex()
    return get_eip712_hash(get_domain_hash(), struct_hash)
Esempio n. 2
0
def ec_recover_typed_signature(
    hashVal,
    typed_signature,
):
    if len(strip_hex_prefix(typed_signature)) != 66 * 2:
        raise Exception('Unable to ecrecover signature: ' + typed_signature)

    sig_type = int(typed_signature[-2:], 16)
    prepended_hash = ''
    if sig_type == constants.SIGNATURE_TYPE_NO_PREPEND:
        prepended_hash = hashVal
    elif sig_type == constants.SIGNATURE_TYPE_DECIMAL:
        prepended_hash = Web3.solidityKeccak(
            ['string', 'bytes32'],
            [PREPEND_DEC, hashVal],
        )
    elif sig_type == constants.SIGNATURE_TYPE_HEXADECIMAL:
        prepended_hash = Web3.solidityKeccak(
            ['string', 'bytes32'],
            [PREPEND_HEX, hashVal],
        )
    else:
        raise Exception('Invalid signature type: ' + sig_type)

    if not prepended_hash:
        raise Exception('Invalid hash: ' + hashVal)

    signature = typed_signature[:-2]

    address = w3.eth.account.recoverHash(prepended_hash, signature=signature)
    return address
Esempio n. 3
0
def combine_nodes(n1: bytes, n2: bytes) -> bytes:
    # NOTE: sorts s.t. the smaller byte array always first.
    # Meant to be identical to https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/MerkleProof.sol
    if n1 <= n2:
        hb = Web3.solidityKeccak(['bytes32', 'bytes32'], [n1, n2])
    else:
        hb = Web3.solidityKeccak(['bytes32', 'bytes32'], [n2, n1])

    return bytes(hb)
Esempio n. 4
0
 def pair_for(factory, token_a, token_b):
     prefix = Web3.toHex(hexstr="ff")
     encoded_tokens = Web3.solidityKeccak(["address", "address"],
                                          UniswapV2Utils.sort_tokens(
                                              token_a, token_b))
     suffix = Web3.toHex(
         hexstr=
         "96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f")
     raw = Web3.solidityKeccak(["bytes", "address", "bytes", "bytes"],
                               [prefix, factory, encoded_tokens, suffix])
     return Web3.toChecksumAddress(Web3.toHex(raw)[-40:])
Esempio n. 5
0
 def pair_for(factory, token_a, token_b):
     prefix = Web3.toHex(hexstr="ff")
     encoded_tokens = Web3.solidityKeccak(["address", "address"],
                                          BakerySwapUtils.sort_tokens(
                                              token_a, token_b))
     suffix = Web3.toHex(
         hexstr=
         "e2e87433120e32c4738a7d8f3271f3d872cbe16241d67537139158d90bac61d3")
     raw = Web3.solidityKeccak(["bytes", "address", "bytes", "bytes"],
                               [prefix, factory, encoded_tokens, suffix])
     return Web3.toChecksumAddress(Web3.toHex(raw)[-40:])
Esempio n. 6
0
 def pair_for(factory, token_a, token_b):
     prefix = Web3.toHex(hexstr="ff")
     encoded_tokens = Web3.solidityKeccak(["address", "address"],
                                          PancakeUtils.sort_tokens(
                                              token_a, token_b))
     # init code pair hash
     suffix = Web3.toHex(
         hexstr=
         "d0d4c4cd0848c93cb4fd1f498d7013ee6bfb25783ea21593d5834f5d250ece66")
     raw = Web3.solidityKeccak(["bytes", "address", "bytes", "bytes"],
                               [prefix, factory, encoded_tokens, suffix])
     return Web3.toChecksumAddress(Web3.toHex(raw)[-40:])
Esempio n. 7
0
    def test_solidityKeccak_ens(self, web3, types, values, expected):
        with ens_addresses(
                web3, {
                    'one.eth': "0x49EdDD3769c0712032808D86597B84ac5c2F5614",
                    'two.eth': "0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5",
                }):
            # when called as class method, any name lookup attempt will fail
            with pytest.raises(InvalidAddress):
                Web3.solidityKeccak(types, values)

            # when called as instance method, ens lookups can succeed
            actual = web3.solidityKeccak(types, values)
            assert actual == expected
Esempio n. 8
0
    def calculate_merkle_root(self, arr):
        length = len(arr)

        if length == 2:
            result = Web3.solidityKeccak(['bytes32', 'bytes32'],
                                         [arr[0], arr[1]])
        else:
            left_arr = arr[:length // 2]
            right_arr = arr[length // 2:]
            left_hash = self.calculate_merkle_root(left_arr)
            right_hash = self.calculate_merkle_root(right_arr)
            result = Web3.solidityKeccak(['bytes32', 'bytes32'],
                                         [left_hash, right_hash])

        return result
Esempio n. 9
0
def place_bid(contract, val=1, addr=w3.eth.accounts[5]):
    # Demoing...
    if addr == "SELLER":
        addr = SELLER_ADDRESS
    if addr == "BUYER1":
        addr = BUYER1
    elif addr == "BUYER2":
        addr = BUYER2
    # Params
    # val = 100
    fake = False
    secret = bytes("secrets", 'utf-8')
    bid_hash = Web3.solidityKeccak(['uint8', 'bool', 'bytes32'],
                                   [val, fake, secret])
    # print("BID HASH ", (bid_hash.hex()))

    tx_hash = Auction.functions.bid(bid_hash).transact({
        'from': addr,
        'value': val,
        'to': contract
    })
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    # print("hash ", tx_hash)
    # print("rec ", tx_receipt)
    return tx_hash
Esempio n. 10
0
def get_order_hash(order):
    '''
    Returns the final signable EIP712 hash for an order.
    '''
    struct_hash = Web3.solidityKeccak(
        [
            'bytes32',
            'bytes32',
            'uint256',
            'uint256',
            'uint256',
            'uint256',
            'uint256',
            'uint256',
            'bytes32',
            'uint256',
            'uint256'
        ],
        [
            hash_string(EIP712_ORDER_STRUCT_STRING),
            get_order_flags(order['salt'], order['isBuy']),
            int(order['baseMarket']),
            int(order['quoteMarket']),
            int(order['amount']),
            int(order['limitPrice'] * (10**18)),
            int(order['triggerPrice'] * (10**18)),
            int(order['limitFee'] * (10**18)),
            address_to_bytes32(order['makerAccountOwner']),
            int(order['makerAccountNumber']),
            int(order['expiration'])
        ]
    ).hex()
    return get_eip712_hash(get_domain_hash(), struct_hash)
    def get_hash(
        self,
        action,
    ):
        # On mainnet, include an extra onlySignOn parameter.
        if self.network_id == NETWORK_ID_MAINNET:
            eip712_struct_str = EIP712_ONBOARDING_ACTION_STRUCT_STRING
        else:
            eip712_struct_str = EIP712_ONBOARDING_ACTION_STRUCT_STRING_TESTNET

        data = [
            [
                'bytes32',
                'bytes32',
            ],
            [
                util.hash_string(eip712_struct_str),
                util.hash_string(action),
            ],
        ]

        # On mainnet, include an extra onlySignOn parameter.
        if self.network_id == NETWORK_ID_MAINNET:
            data[0].append('bytes32')
            data[1].append(util.hash_string(ONLY_SIGN_ON_DOMAIN_MAINNET))

        struct_hash = Web3.solidityKeccak(*data)
        return self.get_eip712_hash(struct_hash)
Esempio n. 12
0
 def get_hash(
     self,
     method,
     request_path,
     body,
     timestamp,
 ):
     data = [
         [
             'bytes32',
             'bytes32',
             'bytes32',
             'bytes32',
             'bytes32',
         ],
         [
             util.hash_string(EIP712_API_KEY_ACTION_STRUCT_STRING),
             util.hash_string(method),
             util.hash_string(request_path),
             util.hash_string(body),
             util.hash_string(timestamp),
         ],
     ]
     struct_hash = Web3.solidityKeccak(*data)
     return self.get_eip712_hash(struct_hash)
Esempio n. 13
0
def get_order_hash(order):
    """
    Returns the final signable EIP712 hash for an order.
    """
    struct_hash = Web3.solidityKeccak(
        [
            "bytes32",
            "uint256",
            "uint256",
            "uint256",
            "uint256",
            "bytes32",
            "uint256",
            "bytes32",
            "uint256",
            "uint256",
            "uint256",
        ],
        [
            hash_string(EIP712_ORDER_STRUCT_STRING),
            order["makerMarket"],
            order["takerMarket"],
            order["makerAmount"],
            order["takerAmount"],
            address_to_bytes32(order["makerAccountOwner"]),
            order["makerAccountNumber"],
            address_to_bytes32(order["takerAccountOwner"]),
            order["takerAccountNumber"],
            order["expiration"],
            order["salt"],
        ],
    ).hex()
    return get_eip712_hash(get_domain_hash(), struct_hash)
Esempio n. 14
0
def hash_balance_data(transferred_amount: int, locked_amount: int,
                      locksroot: bytes) -> bytes:
    # pylint: disable=E1120
    return Web3.solidityKeccak(
        abi_types=["uint256", "uint256", "bytes32"],
        values=[transferred_amount, locked_amount, locksroot],
    )
Esempio n. 15
0
def signature_of_owner_on_implementation(
    owner_key, identity_implementation, proxy_factory
):
    abi_types = ["bytes1", "bytes1", "address", "address"]
    to_hash = ["0x19", "0x00", proxy_factory.address, identity_implementation.address]
    to_sign = Web3.solidityKeccak(abi_types, to_hash)
    return owner_key.sign_msg_hash(to_sign).to_bytes()
Esempio n. 16
0
 def generatePrivateKey(self):
     UUID = self.UUID
     PIN = self.PIN
     privateKey = server.solidityKeccak(["bytes16"], [b''])
     for k in range(4):
         privateKey = Web3.solidityKeccak(["bytes16", "bytes16", "int8"], [privateKey, UUID, PIN[k]]) # ABI-packed, keccak256 hashed
     self.privateKey = privateKey
Esempio n. 17
0
def get_transfer_erc20_fact(
    recipient,
    token_decimals,
    human_amount,
    token_address,
    salt,
):
    token_amount = float(human_amount) * (10**token_decimals)
    if not token_amount.is_integer():
        raise ValueError(
            'Amount {} has more precision than token decimals {}'.format(
                human_amount,
                token_decimals,
            ))
    hex_bytes = Web3.solidityKeccak(
        [
            'address',
            'uint256',
            'address',
            'uint256',
        ],
        [
            recipient,
            int(token_amount),
            token_address,
            salt,
        ],
    )
    return bytes(hex_bytes)
Esempio n. 18
0
def hash_string(input):
    hash = Web3.solidityKeccak(['string'], [input])
    if not hash:
        raise Exception(
            'ecrecover failed due to invalid signature length: ' + input
        )

    return hash
Esempio n. 19
0
def get_domain_hash():
    return Web3.solidityKeccak(
        ['bytes32', 'bytes32', 'bytes32', 'uint256', 'bytes32'], [
            hash_string(EIP712_DOMAIN_STRING),
            hash_string('LimitOrders'),
            hash_string('1.1'), consts.NETWORK_ID,
            address_to_bytes32(consts.LIMIT_ORDERS_ADDRESS)
        ]).hex()
Esempio n. 20
0
def get_domain_hash():
    return Web3.solidityKeccak(
        ['bytes32', 'bytes32', 'bytes32', 'uint256', 'bytes32'], [
            utils.hash_string(EIP712_DOMAIN_STRING),
            utils.hash_string('P1Orders'),
            utils.hash_string('1.0'), consts.NETWORK_ID,
            utils.address_to_bytes32(consts.P1_ORDERS_ADDRESS)
        ]).hex()
Esempio n. 21
0
def encode_with_selector(function_name, types=None, args=None):
    if types is None:
        types = []
    if args is None:
        args = []
    function_signature = get_function_signature(function_name, types)
    encoded_args = Web3.solidityKeccak(types, args)
    return function_signature + encoded_args
Esempio n. 22
0
def recover_proxy_deployment_signature_owner(web3, factory_address,
                                             implementation_address,
                                             signature):
    abi_types = ["bytes1", "bytes1", "address", "address"]
    signed_values = ["0x19", "0x00", factory_address, implementation_address]
    signed_hash = Web3.solidityKeccak(abi_types, signed_values)
    owner = web3.eth.account.recoverHash(signed_hash, signature=signature)
    return owner
Esempio n. 23
0
    def test_solidityKeccak_ens(
        self, web3: "Web3", types: Sequence[TypeStr], values: Sequence[str], expected: HexBytes
    ) -> None:
        with ens_addresses(web3, {
            'one.eth': ChecksumAddress(
                HexAddress(HexStr("0x49EdDD3769c0712032808D86597B84ac5c2F5614"))
            ),
            'two.eth': ChecksumAddress(
                HexAddress(HexStr("0xA6b759bBbf4B59D24acf7E06e79f3a5D104fdCE5"))
            ),
        }):
            # when called as class method, any name lookup attempt will fail
            with pytest.raises(InvalidAddress):
                Web3.solidityKeccak(types, values)

            # when called as instance method, ens lookups can succeed
            actual = web3.solidityKeccak(types, values)
            assert actual == expected
Esempio n. 24
0
def main():
    # Encryption Process
    # We will use padding because pycryptodome sss supports 16 bytes
    key = get_random_bytes(16)
    key_padded = pad(key, 32)
    key_sol = Web3.toHex(key_padded)
    key_hash = Web3.solidityKeccak(['bytes32'], [key_sol])
    shares = Shamir.split(2, 5, key)

    print("************* ENCRYPTION ************")
    print("Generating Shamir Secrets")
    print()
    print("Padded Key Generated = ", key_sol)
    print("Hash Generated = ", key_hash.hex())
    print()
    print("Shamir Shares")

    for idx, share in shares:
        print("{}-{}".format(idx, Web3.toHex(share)))

    # Decryption Process
    print()
    print("************* DECRYPTION ************")

    # Get shares
    new_shares = []
    for x in range(2):
        inp = input("Input Share: ")
        inp = inp.strip()  # clean white space
        idx, key = inp.split('-')
        byte_key = Web3.toBytes(hexstr=key)
        new_shares.append((int(idx), byte_key))

    # Get Key
    re_key = Shamir.combine(new_shares)
    re_key_pad = pad(re_key, 32)
    re_key_hash = Web3.solidityKeccak(['bytes32'], [re_key_pad])

    print()
    print("Key reconstructed = ", Web3.toHex(re_key))
    print("Padded key = ", Web3.toHex(re_key_pad))
    print("Hash Generated = ", Web3.toHex(re_key_hash))
    print()
    print("Hash Match = {}".format(re_key_hash == key_hash))
def hash_availability_claim(vaults_root: bytes, vaults_height: int,
                            trades_root: bytes, trades_height: int,
                            seq_num: int):
    """
    Prepares the availability claim that the committee signs.
    Hashes the inputs in the format required for the data availability Contract.
    """
    return Web3.solidityKeccak(
        ['bytes32', 'uint256', 'bytes32', 'uint256', 'uint256'],
        [vaults_root, vaults_height, trades_root, trades_height, seq_num])
Esempio n. 26
0
 def __init__(self, principalA, roleNameA, principalB, roleNameB):
     # L'identificativo di una intersection inclusion è generato applicando la funzione di hashing sui propri dati
     # i quali sono anzitutto ordinati in modo da considerare equivalenti le espressioni P1.r1 ∩ P2.r2 e P2.r2 ∩ P1.r1
     if ((HexBytes(principalB) > HexBytes(principalA)) or (HexBytes(principalA) == HexBytes(principalB) and HexBytes(roleNameB) > HexBytes(roleNameA))):
         principalA, roleNameA, principalB, roleNameB = principalB, roleNameB, principalA, roleNameA
     super().__init__(Web3.solidityKeccak(['address', 'bytes2', 'address', 'bytes2'], [principalA, roleNameA, principalB, roleNameB]))
     self.principalA = principalA
     self.roleNameA = roleNameA
     self.principalB = principalB
     self.roleNameB = roleNameB
def get_eip712_hash(struct_hash):
    return Web3.solidityKeccak([
        'bytes2',
        'bytes32',
        'bytes32',
    ], [
        '0x1901',
        get_domain_hash(),
        struct_hash,
    ])
Esempio n. 28
0
def get_domain_hash():
    return Web3.solidityKeccak(
        ["bytes32", "bytes32", "bytes32", "uint256", "bytes32"],
        [
            hash_string(EIP712_DOMAIN_STRING),
            hash_string("LimitOrders"),
            hash_string("1.1"),
            consts.NETWORK_ID,
            address_to_bytes32(consts.LIMIT_ORDERS_ADDRESS),
        ],
    ).hex()
Esempio n. 29
0
def test_ecrecover_output_zero(signature_test_contract: Contract,
                               get_accounts: Callable,
                               get_private_key: Callable) -> None:
    """ ecrecover returns 0 for an incorrect value of the v parameter """
    A = get_accounts(1)[0]
    privatekey = get_private_key(A)
    message_hash = Web3.solidityKeccak(["string", "uint256"], ["hello", 5])
    signature = sign(privatekey, message_hash, v=27)

    assert (signature_test_contract.functions.verifyEcrecoverOutput(
        message_hash, signature[:32], signature[32:64],
        2).call() == EMPTY_ADDRESS)
Esempio n. 30
0
 def __init__(self, g, x):
     y = pow(g, x, DLP.p)
     rr = randrange(1, DLP.q)
     grr = pow(g, rr, DLP.p)
     c = Web3.solidityKeccak(['bytes'], [
         BigNumber.from_py(g).val + BigNumber.from_py(y).val +
         BigNumber.from_py(grr).val
     ])
     c = int.from_bytes(c, byteorder='big') % DLP.q
     rrr = (rr + (c * x) % DLP.q) % DLP.q
     assert (pow(g, rrr, DLP.p) == grr * pow(y, c, DLP.p) % DLP.p)
     self.grr, self.rrr = grr, rrr