Пример #1
0
class ENRFactory(factory.Factory):  # type: ignore
    class Meta:
        model = ENR

    sequence_number = factory.Faker("pyint", min_value=0, max_value=100)
    kv_pairs = factory.LazyAttribute(
        lambda o: merge(
            {
                b"id": b"v4",
                b"secp256k1": keys.PrivateKey(
                    o.private_key
                ).public_key.to_compressed_bytes(),
                b"ip": o.address.ip_packed,
                b"udp": o.address.udp_port,
                b"tcp": o.address.tcp_port,
            },
            o.custom_kv_pairs,
        )
    )
    signature = factory.LazyAttribute(
        lambda o: UnsignedENR(o.sequence_number, o.kv_pairs)
        .to_signed_enr(o.private_key)
        .signature
    )

    class Params:
        private_key = factory.Faker("binary", length=V4IdentityScheme.private_key_size)
        address = factory.SubFactory(AddressFactory)
        custom_kv_pairs: Dict[bytes, Any] = {}

    @classmethod
    def minimal(cls) -> ENRAPI:
        private_key = PrivateKeyFactory()
        kv_pairs = {
            b"id": b"v4",
            b"secp256k1": private_key.public_key.to_compressed_bytes(),
        }
        return cls(private_key=private_key.to_bytes(), kv_pairs=kv_pairs)
def test_unsigned_to_eip155_signed_transaction(txn_fixture, transaction_class):
    if txn_fixture['chainId'] is None:
        pytest.skip('No chain id for EIP155 signing')
    elif transaction_class in {FrontierTransaction, HomesteadTransaction}:
        pytest.skip('Transaction class is not chain aware')

    key = keys.PrivateKey(decode_hex(txn_fixture['key']))
    unsigned_txn = transaction_class.create_unsigned_transaction(
        nonce=txn_fixture['nonce'],
        gas_price=txn_fixture['gasPrice'],
        gas=txn_fixture['gas'],
        to=(
            to_canonical_address(txn_fixture['to'])
            if txn_fixture['to']
            else b''
        ),
        value=txn_fixture['value'],
        data=decode_hex(txn_fixture['data']),
    )
    signed_txn = unsigned_txn.as_signed_transaction(key, chain_id=txn_fixture['chainId'])

    assert is_same_address(signed_txn.sender, key.public_key.to_canonical_address())
    assert signed_txn.chain_id == txn_fixture['chainId']
Пример #3
0
 def generate_tx_from_msg(self, msg):
     # TODO: Perhaps this check should be in the client, and not the Shard class
     # TODO 'msg.base_hash == self.chain.get_block_by_hash(msg.base_hash).header.hash' is a check hack in lack of py-evm documentation
     assert msg.target_shard_id == self.shard_id, "Expected target_shard_id to be this shard"
     assert msg.tx.to in self.accounts[
         'addresses'], "Expected 'to' in this shard's accounts"
     assert msg.base_hash == self.chain.get_block_by_hash(
         msg.base_hash).header.hash, "Expected base in this shard"
     magic_sender_pri_key = keys.PrivateKey(decode_hex(MAGIC_PRI_KEY))
     magic_sender_address = Address(
         magic_sender_pri_key.public_key.to_canonical_address())
     nonce = self.vm.state.account_db.get_nonce(magic_sender_address)
     tx = self.vm.create_unsigned_transaction(
         nonce=nonce,
         gas_price=msg.tx.gas_price,
         gas=msg.tx.gas,
         to=msg.tx.to,
         value=msg.tx.value,
         # TODO: data should reflect message info
         data='msg_data'.encode('utf-8'),
     )
     tx = tx.as_signed_transaction(magic_sender_pri_key)
     return tx
Пример #4
0
def sign_message_preparing_for_ec_recover(msg, priv_key):
    privkey = PrivateKey(bytes(bytearray.fromhex(priv_key)), raw=True)
    private_key = keys.PrivateKey(privkey.private_key)

    address = private_key.public_key.to_checksum_address()

    #log("address", address)

    message_hash = my_eth_sign_sha3(msg)

    #log(Web3.toHex(message_hash))

    signed_message = web3.eth.account.signHash(message_hash,
                                               private_key=private_key)

    #log(signed_message)

    ec_recover_args = (msghash, v, r,
                       s) = (Web3.toHex(signed_message.messageHash),
                             signed_message.v, to_32byte_hex(signed_message.r),
                             to_32byte_hex(signed_message.s))

    return ec_recover_args
Пример #5
0
def create_account():
    from eth_utils import (
        keccak, )
    from web3._utils.encoding import (
        to_bytes, )

    from eth_utils import (
        to_hex, )
    from eth_keys import (keys)

    # acct = web3.account.Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
    acct = account.Account.privateKeyToAccount(keccak(to_bytes(text="456")))

    private_key = to_hex(acct.privateKey)
    print("privateKey:", private_key)

    pk = keys.PrivateKey(acct.privateKey)
    public_key = "0x04" + pk.public_key.to_hex()[2:]

    print("public_key:", pk.public_key.to_hex()[2:])
    print("public_key:", public_key)

    print(acct.address)
    print("address:", acct.address)
Пример #6
0
import os
from eth_keys import keys
from eth_utils import decode_hex

INFURA_URL = os.environ['BN_CONSENSUS_INFURA_URL']
PRIVATE_KEY = os.environ['BN_CONSENSUS_PRIVATE_KEY']
ADDRESS = keys.PrivateKey(
    decode_hex(PRIVATE_KEY)).public_key.to_checksum_address()

GAS = int(os.environ['BN_CONSENSUS_GAS'])
GAS_PRICE = int(os.environ['BN_CONSENSUS_GAS_PRICE'])
TO_ADDRESS = os.environ['BN_CONSENSUS_TO_ADDRESS']

SNAPSHOTS_PERIOD = int(os.environ['BN_CONSENSUS_SNAPSHOTS_PERIOD'])
SNAPSHOTS_PATH = "/snapshots/dump_{}.zip"

APPLY_URL = os.environ['BN_CONSENSUS_APPLY_URL']
DUMP_URL = os.environ['BN_CONSENSUS_DUMP_URL']
MAX_COLLECTION_SIZE = os.environ['BN_CONSENSUS_MAX_COLLECTION_SIZE']

VOTING_ABI = [{
    'constant': True,
    'inputs': [],
    'name': 'hasInitialized',
    'outputs': [{
        'name': '',
        'type': 'bool'
    }],
    'payable': False,
    'stateMutability': 'view',
    'type': 'function'
Пример #7
0
def random_private_key():
    return keys.PrivateKey(random_hash())
def priv2addr(private_key):
    pk = keys.PrivateKey(bytes.fromhex(private_key))
    return pk.public_key.to_checksum_address()
Пример #9
0
def privatekey_to_publickey(private_key_bin: PrivateKey) -> PublicKey:
    """ Returns public key in bitcoins 'bin' encoding. """
    if not ishash(private_key_bin):
        raise ValueError("private_key_bin format mismatch. maybe hex encoded?")
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
Пример #10
0
async def test_handshake():
    # TODO: this test should be re-written to not depend on functionality in the `ETHPeer` class.
    cancel_token = CancelToken("test_handshake")
    use_eip8 = False
    initiator_remote = kademlia.Node(
        keys.PrivateKey(test_values['receiver_private_key']).public_key,
        kademlia.Address('0.0.0.0', 0, 0))
    initiator = HandshakeInitiator(
        initiator_remote,
        keys.PrivateKey(test_values['initiator_private_key']), use_eip8,
        cancel_token)
    initiator.ephemeral_privkey = keys.PrivateKey(
        test_values['initiator_ephemeral_private_key'])

    responder_remote = kademlia.Node(
        keys.PrivateKey(test_values['initiator_private_key']).public_key,
        kademlia.Address('0.0.0.0', 0, 0))
    responder = HandshakeResponder(
        responder_remote, keys.PrivateKey(test_values['receiver_private_key']),
        use_eip8, cancel_token)
    responder.ephemeral_privkey = keys.PrivateKey(
        test_values['receiver_ephemeral_private_key'])

    # Check that the auth message generated by the initiator is what we expect. Notice that we
    # can't use the auth_init generated here because the non-deterministic prefix would cause the
    # derived secrets to not match the expected values.
    _auth_init = initiator.create_auth_message(test_values['initiator_nonce'])
    assert len(_auth_init) == len(test_values['auth_plaintext'])
    assert _auth_init[65:] == test_values['auth_plaintext'][
        65:]  # starts with non deterministic k

    # Check that encrypting and decrypting the auth_init gets us the orig msg.
    _auth_init_ciphertext = initiator.encrypt_auth_message(_auth_init)
    assert _auth_init == ecies.decrypt(_auth_init_ciphertext,
                                       responder.privkey)

    # Check that the responder correctly decodes the auth msg.
    auth_msg_ciphertext = test_values['auth_ciphertext']
    initiator_ephemeral_pubkey, initiator_nonce, _ = decode_authentication(
        auth_msg_ciphertext, responder.privkey)
    assert initiator_nonce == test_values['initiator_nonce']
    assert initiator_ephemeral_pubkey == (keys.PrivateKey(
        test_values['initiator_ephemeral_private_key']).public_key)

    # Check that the auth_ack msg generated by the responder is what we expect.
    auth_ack_msg = responder.create_auth_ack_message(
        test_values['receiver_nonce'])
    assert auth_ack_msg == test_values['authresp_plaintext']

    # Check that the secrets derived from ephemeral key agreements match the expected values.
    auth_ack_ciphertext = test_values['authresp_ciphertext']
    aes_secret, mac_secret, egress_mac, ingress_mac = responder.derive_secrets(
        initiator_nonce, test_values['receiver_nonce'],
        initiator_ephemeral_pubkey, auth_msg_ciphertext, auth_ack_ciphertext)
    assert aes_secret == test_values['aes_secret']
    assert mac_secret == test_values['mac_secret']
    # Test values are from initiator perspective, so they're reversed here.
    assert ingress_mac.digest() == test_values['initial_egress_MAC']
    assert egress_mac.digest() == test_values['initial_ingress_MAC']

    # Check that the initiator secrets match as well.
    responder_ephemeral_pubkey, responder_nonce = initiator.decode_auth_ack_message(
        test_values['authresp_ciphertext'])
    (initiator_aes_secret, initiator_mac_secret, initiator_egress_mac,
     initiator_ingress_mac) = initiator.derive_secrets(
         initiator_nonce, responder_nonce, responder_ephemeral_pubkey,
         auth_msg_ciphertext, auth_ack_ciphertext)
    assert initiator_aes_secret == aes_secret
    assert initiator_mac_secret == mac_secret
    assert initiator_ingress_mac.digest() == test_values['initial_ingress_MAC']
    assert initiator_egress_mac.digest() == test_values['initial_egress_MAC']

    # Finally, check that two Peers configured with the secrets generated above understand each
    # other.
    responder_reader = asyncio.StreamReader()
    initiator_reader = asyncio.StreamReader()
    # Link the initiator's writer to the responder's reader, and the responder's writer to the
    # initiator's reader.
    responder_writer = MockStreamWriter(initiator_reader.feed_data)
    initiator_writer = MockStreamWriter(responder_reader.feed_data)
    initiator_peer = DumbPeer(remote=initiator.remote,
                              privkey=initiator.privkey,
                              reader=initiator_reader,
                              writer=initiator_writer,
                              aes_secret=initiator_aes_secret,
                              mac_secret=initiator_mac_secret,
                              egress_mac=initiator_egress_mac,
                              ingress_mac=initiator_ingress_mac,
                              headerdb=None,
                              network_id=1)
    initiator_peer.base_protocol.send_handshake()
    responder_peer = DumbPeer(remote=responder.remote,
                              privkey=responder.privkey,
                              reader=responder_reader,
                              writer=responder_writer,
                              aes_secret=aes_secret,
                              mac_secret=mac_secret,
                              egress_mac=egress_mac,
                              ingress_mac=ingress_mac,
                              headerdb=None,
                              network_id=1)
    responder_peer.base_protocol.send_handshake()

    # The handshake msgs sent by each peer (above) are going to be fed directly into their remote's
    # reader, and thus the read_msg() calls will return immediately.
    responder_hello, _ = await responder_peer.read_msg()
    initiator_hello, _ = await initiator_peer.read_msg()

    assert isinstance(responder_hello, Hello)
    assert isinstance(initiator_hello, Hello)
 def get_nodes_to_connect(self):
     nodekey = keys.PrivateKey(decode_hex(
         "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"))
     remoteid = nodekey.public_key.to_hex()
     yield kademlia.Node(keys.PublicKey(decode_hex(remoteid)),
                         kademlia.Address('127.0.0.1', 30303, 30303))
Пример #12
0
def generate_random_keypair() -> Tuple[bytes, Address]:
    key_object = keys.PrivateKey(
        pad32(int_to_big_endian(random.getrandbits(8 * 32))))
    return key_object.to_bytes(), Address(
        key_object.public_key.to_canonical_address())
Пример #13
0
def test_state_fixtures(fixture, fixture_vm_class):
    header = BlockHeader(
        coinbase=fixture['env']['currentCoinbase'],
        difficulty=fixture['env']['currentDifficulty'],
        block_number=fixture['env']['currentNumber'],
        gas_limit=fixture['env']['currentGasLimit'],
        timestamp=fixture['env']['currentTimestamp'],
        parent_hash=fixture['env']['previousHash'],
    )

    chaindb = ChainDB(get_db_backend())
    vm = fixture_vm_class(header=header, chaindb=chaindb)

    state = vm.state
    apply_state_dict(state.account_db, fixture['pre'])
    state.account_db.persist()

    # Update state_root manually
    vm.block = vm.block.copy(header=vm.block.header.copy(
        state_root=state.state_root))
    if 'secretKey' in fixture['transaction']:
        unsigned_transaction = vm.create_unsigned_transaction(
            nonce=fixture['transaction']['nonce'],
            gas_price=fixture['transaction']['gasPrice'],
            gas=fixture['transaction']['gasLimit'],
            to=fixture['transaction']['to'],
            value=fixture['transaction']['value'],
            data=fixture['transaction']['data'],
        )
        private_key = keys.PrivateKey(fixture['transaction']['secretKey'])
        transaction = unsigned_transaction.as_signed_transaction(
            private_key=private_key)
    elif 'vrs' in fixture['transaction']:
        v, r, s = (
            fixture['transaction']['v'],
            fixture['transaction']['r'],
            fixture['transaction']['s'],
        )
        transaction = vm.create_transaction(
            nonce=fixture['transaction']['nonce'],
            gas_price=fixture['transaction']['gasPrice'],
            gas=fixture['transaction']['gasLimit'],
            to=fixture['transaction']['to'],
            value=fixture['transaction']['value'],
            data=fixture['transaction']['data'],
            v=v,
            r=r,
            s=s,
        )

    try:
        header, receipt, computation = vm.apply_transaction(
            vm.block.header, transaction)
        transactions = vm.block.transactions + (transaction, )
        receipts = vm.block.get_receipts(chaindb) + (receipt, )
        block = vm.set_block_transactions(vm.block, header, transactions,
                                          receipts)
    except ValidationError as err:
        block = vm.block
        transaction_error = err
        logger.warn("Got transaction error", exc_info=True)
    else:
        transaction_error = False

    if not transaction_error:
        log_entries = computation.get_log_entries()
        actual_logs_hash = hash_log_entries(log_entries)
        if 'logs' in fixture['post']:
            expected_logs_hash = fixture['post']['logs']
            assert expected_logs_hash == actual_logs_hash
        elif log_entries:
            raise AssertionError("Got log {0} entries. hash:{1}".format(
                len(log_entries),
                actual_logs_hash,
            ))

        if 'out' in fixture:
            expected_output = fixture['out']
            if isinstance(expected_output, int):
                assert len(computation.output) == expected_output
            else:
                assert computation.output == expected_output

    assert block.header.state_root == fixture['post']['hash']
Пример #14
0
def private_key_to_address(private_key: bytes) -> Address:
    private_key_object = keys.PrivateKey(private_key)
    return Address(private_key_object.public_key.to_canonical_address())
Пример #15
0
 def __init__(self, data: bytes) -> None:
     self.__seckey = keys.PrivateKey(data)
Пример #16
0
def _create_v3_keyfile_json(private_key, password, kdf, work_factor=None):
    salt = Random.get_random_bytes(16)

    if work_factor is None:
        work_factor = get_default_work_factor_for_kdf(kdf)

    if kdf == 'pbkdf2':
        derived_key = _pbkdf2_hash(
            password,
            hash_name='sha256',
            salt=salt,
            iterations=work_factor,
            dklen=DKLEN,
        )
        kdfparams = {
            'c': work_factor,
            'dklen': DKLEN,
            'prf': 'hmac-sha256',
            'salt': encode_hex_no_prefix(salt),
        }
    elif kdf == 'scrypt':
        derived_key = _scrypt_hash(
            password,
            salt=salt,
            buflen=DKLEN,
            r=SCRYPT_R,
            p=SCRYPT_P,
            n=work_factor,
        )
        kdfparams = {
            'dklen': DKLEN,
            'n': work_factor,
            'r': SCRYPT_R,
            'p': SCRYPT_P,
            'salt': encode_hex_no_prefix(salt),
        }
    else:
        raise NotImplementedError("KDF not implemented: {0}".format(kdf))

    iv = big_endian_to_int(Random.get_random_bytes(16))
    encrypt_key = derived_key[:16]
    ciphertext = encrypt_aes_ctr(private_key, encrypt_key, iv)
    mac = keccak(derived_key[16:32] + ciphertext)

    address = keys.PrivateKey(private_key).public_key.to_address()

    return {
        'address': remove_0x_prefix(address),
        'crypto': {
            'cipher': 'aes-128-ctr',
            'cipherparams': {
                'iv': encode_hex_no_prefix(int_to_big_endian(iv)),
            },
            'ciphertext': encode_hex_no_prefix(ciphertext),
            'kdf': kdf,
            'kdfparams': kdfparams,
            'mac': encode_hex_no_prefix(mac),
        },
        'id': str(uuid.uuid4()),
        'version': 3,
    }
Пример #17
0
def address_from_private_key(private_key):
    if isinstance(private_key, str):
        private_key = bytes.fromhex(private_key.replace('0x', ''))
    return keys.PrivateKey(private_key).public_key.to_checksum_address()
Пример #18
0
    def __init__(self, keyfile='', password='', private_key='', provider='', provider_endpoint_uri='',
                 contract_address='', contract_abi={}, gas_price=None, gas_limit=None):
        """Create a new instance of the Token SDK.

        The SDK needs a JSON-RPC provider, contract definitions and (optionally) a wallet private key.

        The user may pass either a provider or a provider endpoint URI, in which case a default
        :class:`web3:providers:HTTPProvider` will be created. If neither private_key nor keyfile+password
        are provided, the SDK can still be used in "anonymous" mode, with only the following functions available:
            - get_address_ether_balance
            - get_transaction_status
            - get_transaction_data
            - monitor_ether_transactions

        :param str private_key: a private key to initialize the wallet with. If either private key or keyfile
            are not provided, the wallet will not be initialized and methods needing the wallet will raise exception.

        :param str keyfile: the path to the keyfile to initialize the wallet with. You will also need to supply
            a password for this keyfile.

        :param str password: a password for the keyfile.

        :param provider: JSON-RPC provider to work with. If not given, a default `web3:providers:HTTPProvider`
            is used, inited with provider_endpoint_uri.
        :type provider: :class:`web3:providers:BaseProvider`

        :param str provider_endpoint_uri: a URI to use with a default HTTPProvider.

        :param str contract_address: the address of the token contract.

        :param list contract_abi: The contract ABI json.

        :param number gas_price: The price of gas in Gwei.

        :param number gas_limit: Transaction gas limit.

        :returns: An instance of the SDK.
        :rtype: :class:`~erc20tokensdk.SDK`

        :raises: :class:`~erc20tokensdk.exceptions.SdkConfigurationError` if some of the configuration
            parameters are invalid.
        """

        if not provider and not provider_endpoint_uri:
            raise SdkConfigurationError('either provider or provider endpoint must be provided')

        try:
            validate_address(contract_address)
        except ValueError as ve:
            raise SdkConfigurationError('invalid token contract address: ' + str(ve))

        try:
            validate_abi(contract_abi)
        except Exception as e:
            raise SdkConfigurationError('invalid token contract abi: ' + str(e))

        if gas_price and not (isinstance(gas_price, int) or isinstance(gas_price, float)):
            raise SdkConfigurationError('gas price must be either integer of float')

        if gas_limit and not isinstance(gas_limit, int):
            raise SdkConfigurationError('gas limit must be integer')

        if provider:
            self.web3 = Web3(provider)
        else:
            self.web3 = Web3(RetryHTTPProvider(provider_endpoint_uri))
        if not self.web3.isConnected():
            raise SdkConfigurationError('cannot connect to provider endpoint')

        self.token_contract = self.web3.eth.contract(contract_address, abi=contract_abi)
        self.private_key = None
        self.address = None

        if keyfile:
            try:
                self.private_key = load_keyfile(keyfile, password)
            except Exception as e:
                raise SdkConfigurationError('cannot load keyfile: ' + str(e))
        elif private_key:
            self.private_key = private_key

        if self.private_key:
            try:
                private_key_bytes = hexstr_if_str(to_bytes, self.private_key)
                pk = keys.PrivateKey(private_key_bytes)
                self.address = self.web3.eth.defaultAccount = pk.public_key.to_checksum_address()
            except ValidationError as e:
                raise SdkConfigurationError('cannot load private key: ' + str(e))

            # init transaction manager
            self._tx_manager = TransactionManager(self.web3, self.private_key, self.address, self.token_contract,
                                                  gas_price, gas_limit)

        # monitoring filter manager
        self._filter_mgr = FilterManager(self.web3)
Пример #19
0
async def test_handshake_eip8():
    cancel_token = CancelToken("test_handshake_eip8")
    use_eip8 = True
    initiator_remote = kademlia.Node(
        keys.PrivateKey(eip8_values['receiver_private_key']).public_key,
        kademlia.Address('0.0.0.0', 0, 0))
    initiator = HandshakeInitiator(
        initiator_remote,
        keys.PrivateKey(eip8_values['initiator_private_key']), use_eip8,
        cancel_token)
    initiator.ephemeral_privkey = keys.PrivateKey(
        eip8_values['initiator_ephemeral_private_key'])

    responder_remote = kademlia.Node(
        keys.PrivateKey(eip8_values['initiator_private_key']).public_key,
        kademlia.Address('0.0.0.0', 0, 0))
    responder = HandshakeResponder(
        responder_remote, keys.PrivateKey(eip8_values['receiver_private_key']),
        use_eip8, cancel_token)
    responder.ephemeral_privkey = keys.PrivateKey(
        eip8_values['receiver_ephemeral_private_key'])

    auth_init_ciphertext = eip8_values['auth_init_ciphertext']

    # Check that we can decrypt/decode the EIP-8 auth init message.
    initiator_ephemeral_pubkey, initiator_nonce, _ = decode_authentication(
        auth_init_ciphertext, responder.privkey)
    assert initiator_nonce == eip8_values['initiator_nonce']
    assert initiator_ephemeral_pubkey == (keys.PrivateKey(
        eip8_values['initiator_ephemeral_private_key']).public_key)

    responder_nonce = eip8_values['receiver_nonce']
    auth_ack_ciphertext = eip8_values['auth_ack_ciphertext']
    aes_secret, mac_secret, egress_mac, ingress_mac = responder.derive_secrets(
        initiator_nonce, responder_nonce, initiator_ephemeral_pubkey,
        auth_init_ciphertext, auth_ack_ciphertext)

    # Check that the secrets derived by the responder match the expected values.
    assert aes_secret == eip8_values['expected_aes_secret']
    assert mac_secret == eip8_values['expected_mac_secret']

    # Also according to https://github.com/ethereum/EIPs/blob/master/EIPS/eip-8.md, running B's
    # ingress-mac keccak state on the string "foo" yields the following hash:
    ingress_mac_copy = ingress_mac.copy()
    ingress_mac_copy.update(b'foo')
    assert ingress_mac_copy.hexdigest() == (
        '0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5')

    responder_ephemeral_pubkey, responder_nonce = initiator.decode_auth_ack_message(
        auth_ack_ciphertext)
    (initiator_aes_secret, initiator_mac_secret, initiator_egress_mac,
     initiator_ingress_mac) = initiator.derive_secrets(
         initiator_nonce, responder_nonce, responder_ephemeral_pubkey,
         auth_init_ciphertext, auth_ack_ciphertext)

    # Check that the secrets derived by the initiator match the expected values.
    assert initiator_aes_secret == eip8_values['expected_aes_secret']
    assert initiator_mac_secret == eip8_values['expected_mac_secret']

    # Finally, check that two Peers configured with the secrets generated above understand each
    # other.
    responder_reader = asyncio.StreamReader()
    initiator_reader = asyncio.StreamReader()
    # Link the initiator's writer to the responder's reader, and the responder's writer to the
    # initiator's reader.
    responder_writer = MockStreamWriter(initiator_reader.feed_data)
    initiator_writer = MockStreamWriter(responder_reader.feed_data)
    initiator_peer = DumbPeer(remote=initiator.remote,
                              privkey=initiator.privkey,
                              reader=initiator_reader,
                              writer=initiator_writer,
                              aes_secret=initiator_aes_secret,
                              mac_secret=initiator_mac_secret,
                              egress_mac=initiator_egress_mac,
                              ingress_mac=initiator_ingress_mac,
                              headerdb=None,
                              network_id=1)
    initiator_peer.base_protocol.send_handshake()
    responder_peer = DumbPeer(remote=responder.remote,
                              privkey=responder.privkey,
                              reader=responder_reader,
                              writer=responder_writer,
                              aes_secret=aes_secret,
                              mac_secret=mac_secret,
                              egress_mac=egress_mac,
                              ingress_mac=ingress_mac,
                              headerdb=None,
                              network_id=1)
    responder_peer.base_protocol.send_handshake()

    # The handshake msgs sent by each peer (above) are going to be fed directly into their remote's
    # reader, and thus the read_msg() calls will return immediately.
    responder_hello, _ = await responder_peer.read_msg()
    initiator_hello, _ = await initiator_peer.read_msg()

    assert isinstance(responder_hello, Hello)
    assert isinstance(initiator_hello, Hello)
Пример #20
0
def test_state_fixtures(fixture, fixture_vm_class):
    header = BlockHeader(
        coinbase=fixture['env']['currentCoinbase'],
        difficulty=fixture['env']['currentDifficulty'],
        block_number=fixture['env']['currentNumber'],
        gas_limit=fixture['env']['currentGasLimit'],
        timestamp=fixture['env']['currentTimestamp'],
        parent_hash=fixture['env']['previousHash'],
    )
    chaindb = ChainDB(get_db_backend())
    vm = fixture_vm_class(header=header, chaindb=chaindb)

    vm_state = vm.state
    with vm_state.mutable_state_db() as state_db:
        setup_state_db(fixture['pre'], state_db)
    # Update state_root manually
    vm.block.header.state_root = vm_state.state_root

    if 'secretKey' in fixture['transaction']:
        unsigned_transaction = vm.create_unsigned_transaction(
            nonce=fixture['transaction']['nonce'],
            gas_price=fixture['transaction']['gasPrice'],
            gas=fixture['transaction']['gasLimit'],
            to=fixture['transaction']['to'],
            value=fixture['transaction']['value'],
            data=fixture['transaction']['data'],
        )
        private_key = keys.PrivateKey(fixture['transaction']['secretKey'])
        transaction = unsigned_transaction.as_signed_transaction(
            private_key=private_key)
    elif 'vrs' in fixture['transaction']:
        v, r, s = (
            fixture['transaction']['v'],
            fixture['transaction']['r'],
            fixture['transaction']['s'],
        )
        transaction = vm.create_transaction(
            nonce=fixture['transaction']['nonce'],
            gas_price=fixture['transaction']['gasPrice'],
            gas=fixture['transaction']['gasLimit'],
            to=fixture['transaction']['to'],
            value=fixture['transaction']['value'],
            data=fixture['transaction']['data'],
            v=v,
            r=r,
            s=s,
        )

    try:
        computation, _ = vm.apply_transaction(transaction)
    except ValidationError as err:
        transaction_error = err
        LOGGER.warn("Got transaction error:")
        LOGGER.warn(traceback.format_exc())
    else:
        transaction_error = False

    if not transaction_error:
        log_entries = computation.get_log_entries()
        actual_logs_hash = hash_log_entries(log_entries)
        if 'logs' in fixture['post']:
            expected_logs_hash = fixture['post']['logs']
            assert expected_logs_hash == actual_logs_hash
        elif log_entries:
            raise AssertionError("Got log {0} entries. hash:{1}".format(
                len(log_entries),
                actual_logs_hash,
            ))

        if 'out' in fixture:
            expected_output = fixture['out']
            if isinstance(expected_output, int):
                assert len(computation.output) == expected_output
            else:
                assert computation.output == expected_output

    assert vm.block.header.state_root == fixture['post']['hash']
Пример #21
0
def funded_address_private_key():
    return keys.PrivateKey(
        decode_hex(
            '0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8'
        ))
Пример #22
0
 def from_seed(cls, seed: bytes, *args: Any,
               **kwargs: Any) -> DiscoveryProtocol:
     privkey = keys.PrivateKey(keccak(seed))
     return cls(*args, privkey=privkey, **kwargs)
Пример #23
0
def privatekey_to_address(private_key_bin: bytes) -> Address:
    return keys.PrivateKey(private_key_bin).public_key.to_canonical_address()
Пример #24
0
    result = decode_message(encoded)
    assert result == message


@given(num_enr_records=st.integers(min_value=0, max_value=5))
def test_found_nodes_message_encoding_round_trip(num_enr_records):
    enrs = tuple(ENRFactory() for _ in range(num_enr_records))
    encoded_enrs = tuple(rlp.encode(enr) for enr in enrs)
    payload = FoundNodesPayload(num_enr_records, encoded_enrs)
    message = FoundNodesMessage(payload)
    encoded = message.to_wire_bytes()
    result = decode_message(encoded)
    assert result.payload == message.payload


PRIVATE_KEY = keys.PrivateKey(b"unicornsrainbowscupcakessparkles")

advertisement_st = st.tuples(
    st.binary(min_size=1, max_size=128), st.binary(min_size=32, max_size=32),
).map(lambda key_and_root: Advertisement.create(*key_and_root, PRIVATE_KEY))


@settings(deadline=500)
@given(advertisements=st.lists(advertisement_st, min_size=1, max_size=5).map(tuple),)
def test_advertisement_message_encoding_round_trip(advertisements):
    message = AdvertiseMessage(advertisements)
    encoded = message.to_wire_bytes()
    result = decode_message(encoded)
    assert result == message

Пример #25
0
import random
from collections import namedtuple

import rlp
from eth_keys import keys
from eth_utils import decode_hex, keccak
from web3.datastructures import AttributeDict

SignedBlockHeader = namedtuple("SignedBlockHeader", "unsignedBlockHeader signature")

_PRIVATE_KEY_DEFAULT = keys.PrivateKey(b"1" * 32)
_TIMESTAMP_DEFAULT = 100

_random_generator = random.Random(0)


def random_hash():
    return bytes(_random_generator.randint(0, 255) for _ in range(32))


def random_number():
    return _random_generator.randint(0, 100)


def random_private_key():
    return keys.PrivateKey(random_hash())


def make_short_block_header_list(block_header):
    """Order the first 11 block header fields into a list.
Пример #26
0
def web3js_private_key(web3js_key):
    return keys.PrivateKey(HexBytes(web3js_key))
Пример #27
0
        HexBytes("0x13978aee95f38490e9769C39B2773Ed763d9cd5F"),
        "value":
        10000000000000000,
        "data":
        "",
        "unsigned":
        "eb8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc1000080808080",  # noqa: 501
        "signed":
        "f86b8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc10000801ba0eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4a014a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1"  # noqa: 501
    },
]

PRIVATE_KEY_AS_BYTES = b'unicorns' * 4
PRIVATE_KEY_AS_HEXSTR = '0x756e69636f726e73756e69636f726e73756e69636f726e73756e69636f726e73'
PRIVATE_KEY_AS_INT = 0x756e69636f726e73756e69636f726e73756e69636f726e73756e69636f726e73
PRIVATE_KEY_AS_OBJ = keys.PrivateKey(PRIVATE_KEY_AS_BYTES)
ACCT_ADDRESS = '0xa79F6f349C853F9Ea0B29636779ae3Cb4E3BA729'

PRIVATE_KEY_AS_BYTES_ALT = b'rainbows' * 4
PRIVATE_KEY_AS_HEXSTR_ALT = '0x7261696e626f77737261696e626f77737261696e626f77737261696e626f7773'
PRIVATE_KEY_AS_INT_ALT = 0x7261696e626f77737261696e626f77737261696e626f77737261696e626f7773
PRIVATE_KEY_AS_OBJ_ALT = keys.PrivateKey(PRIVATE_KEY_AS_BYTES_ALT)
ACCT_ADDRESS_ALT = '0xafd7f0E16A1814B854b45f551AFD493BE5F039F9'


@pytest.fixture(params=[
    PRIVATE_KEY_AS_INT, PRIVATE_KEY_AS_HEXSTR, PRIVATE_KEY_AS_BYTES,
    PRIVATE_KEY_AS_OBJ
])  # noqa: 501
def PRIVATE_KEY(request):
    return request.param
Пример #28
0
def generate_privkey() -> datatypes.PrivateKey:
    """Generate a new SECP256K1 private key and return it"""
    privkey = ec.generate_private_key(CURVE, default_backend())
    return keys.PrivateKey(
        pad32(int_to_big_endian(privkey.private_numbers().private_value)))
Пример #29
0
from tests.trinity.core.integration_test_helpers import FakeAsyncHeaderDB


def get_open_port():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 0))
    s.listen(1)
    port = s.getsockname()[1]
    s.close()
    return port


port = get_open_port()
NETWORK_ID = 99
SERVER_ADDRESS = Address('127.0.0.1', udp_port=port, tcp_port=port)
RECEIVER_PRIVKEY = keys.PrivateKey(eip8_values['receiver_private_key'])
RECEIVER_PUBKEY = RECEIVER_PRIVKEY.public_key
RECEIVER_REMOTE = Node(RECEIVER_PUBKEY, SERVER_ADDRESS)

INITIATOR_PRIVKEY = keys.PrivateKey(eip8_values['initiator_private_key'])
INITIATOR_PUBKEY = INITIATOR_PRIVKEY.public_key
INITIATOR_ADDRESS = Address('127.0.0.1', get_open_port() + 1)
INITIATOR_REMOTE = Node(INITIATOR_PUBKEY, INITIATOR_ADDRESS)


class MockPeerPool:
    is_full = False
    connected_nodes = {}

    def __init__(self):
        self._new_peers = asyncio.Queue()
Пример #30
0
def private_key_to_account(pk: str):
    from eth_keys import keys
    from web3 import Web3

    account = keys.PrivateKey(Web3.toBytes(hexstr=pk))
    return account.public_key.to_checksum_address()