def __init__( self, token_network: TokenNetwork, channel_identifier: typing.ChannelID, ): filter_args = get_filter_args_for_specific_event_from_channel( token_network_address=token_network.address, channel_identifier=channel_identifier, event_name=EVENT_CHANNEL_OPENED, ) events = token_network.proxy.contract.web3.eth.getLogs(filter_args) if not len(events) > 0: raise ValueError('Channel is non-existing.') event = decode_event(CONTRACT_MANAGER.get_contract_abi(CONTRACT_TOKEN_NETWORK), events[-1]) participant1 = decode_hex(event['args']['participant1']) participant2 = decode_hex(event['args']['participant2']) if token_network.node_address not in (participant1, participant2): raise ValueError('One participant must be the node address') if token_network.node_address == participant2: participant1, participant2 = participant2, participant1 self.channel_identifier = channel_identifier self.channel_operations_lock = RLock() self.participant1 = participant1 self.participant2 = participant2 self.token_network = token_network
def solidity_resolve_address(hex_code, library_symbol, library_address): """ Change the bytecode to use the given library address. Args: hex_code (bin): The bytecode encoded in hexadecimal. library_name (str): The library that will be resolved. library_address (str): The address of the library. Returns: bin: The bytecode encoded in hexadecimal with the library references resolved. """ if library_address.startswith('0x'): raise ValueError('Address should not contain the 0x prefix') try: decode_hex(library_address) except TypeError: raise ValueError( 'library_address contains invalid characters, it must be hex encoded.') if len(library_symbol) != 40 or len(library_address) != 40: raise ValueError('Address with wrong length') return hex_code.replace(library_symbol, library_address)
def normalize_block_header(header): normalized_header = { 'bloom': big_endian_to_int(decode_hex(header['bloom'])), 'coinbase': to_canonical_address(header['coinbase']), 'difficulty': to_int(header['difficulty']), 'extraData': decode_hex(header['extraData']), 'gasLimit': to_int(header['gasLimit']), 'gasUsed': to_int(header['gasUsed']), 'hash': decode_hex(header['hash']), 'mixHash': decode_hex(header['mixHash']), 'nonce': decode_hex(header['nonce']), 'number': to_int(header['number']), 'parentHash': decode_hex(header['parentHash']), 'receiptTrie': decode_hex(header['receiptTrie']), 'stateRoot': decode_hex(header['stateRoot']), 'timestamp': to_int(header['timestamp']), 'transactionsTrie': decode_hex(header['transactionsTrie']), 'uncleHash': decode_hex(header['uncleHash']), } if 'blocknumber' in header: normalized_header['blocknumber'] = to_int(header['blocknumber']) if 'chainname' in header: normalized_header['chainname'] = header['chainname'] if 'chainnetwork' in header: normalized_header['chainnetwork'] = header['chainnetwork'] return normalized_header
def register_token( self, registry_address_hex: typing.AddressHex, token_address_hex: typing.AddressHex, retry_timeout: typing.NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> TokenNetwork: """ Register a token with the raiden token manager. Args: registry_address: registry address token_address_hex (string): a hex encoded token address. Returns: The token network proxy. """ registry_address = decode_hex(registry_address_hex) token_address = decode_hex(token_address_hex) registry = self._raiden.chain.token_network_registry(registry_address) token_network_address = registry.add_token(token_address) # Register the channel manager with the raiden registry waiting.wait_for_payment_network( self._raiden, registry.address, token_address, retry_timeout, ) return self._raiden.chain.token_network(token_network_address)
def format_int(value, size): assert isinstance(value, int) assert isinstance(size, int) if value >= 0: return decode_hex('{:x}'.format(value).zfill(size // 4)) else: return decode_hex('{:x}'.format((1 << size) + value))
def test_eth_sign(web3, skip_if_testrpc): skip_if_testrpc(web3) private_key_hex = '0x5e95384d8050109aab08c1922d3c230739bc16976553c317e5d0b87b59371f2a' private_key = decode_hex(private_key_hex) # This imports the private key into the running geth instance and unlocks # the account so that it can sign things. # `0xa5df35f30ba0ce878b1061ae086289adff3ba1e0` address = web3.personal.importRawKey(private_key, "password") web3.personal.unlockAccount(address, "password") assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address) assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0' # the data to be signed data = b'1234567890abcdefghijklmnopqrstuvwxyz' # the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3` data_hash = web3.sha3(data, encoding=None) data_hash_bytes = decode_hex(data_hash) assert force_bytes(data_hash) == sha3(data) priv_key = PrivateKey(flags=ALL_FLAGS) priv_key.set_raw_privkey(private_key) # sanit check the extract_ecdsa_signer function works as expected. vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=sha3_256) vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig) vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id)) vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full)) assert vector_address == address # Now have geth sign some data. signature_hex = web3.eth.sign(address, data) signature_bytes = decode_hex(signature_hex) actual_signer = extract_ecdsa_signer(data_hash_bytes, signature_bytes) assert actual_signer == address # Verify the signature against the public key derived from the # original private key. It fails. rec_id = signature_bytes[64] if is_string(rec_id): rec_id = ord(rec_id) recoverable_signature = priv_key.ecdsa_recoverable_deserialize( signature_bytes[:64], rec_id, ) signature = priv_key.ecdsa_recoverable_convert(recoverable_signature) is_valid = priv_key.pubkey.ecdsa_verify( msg=data, raw_sig=signature, digest=sha3_256, ) assert is_valid
def from_dict(cls, data): assert data['type'] == cls.__name__ reveal_secret = cls( message_identifier=data['message_identifier'], secret=decode_hex(data['secret']), ) reveal_secret.signature = decode_hex(data['signature']) return reveal_secret
def test_pre_EIP155_transaction_sender_extraction(transaction_class, txn_fixture): if txn_fixture['chainId'] is not None: pytest.skip("Only testng non-EIP155 transactions") key = keys.PrivateKey(decode_hex(txn_fixture['key'])) transaction = rlp.decode(decode_hex(txn_fixture['signed']), sedes=transaction_class) sender = extract_transaction_sender(transaction) assert is_same_address(sender, transaction.sender) assert is_same_address(sender, key.public_key.to_canonical_address())
def normalize_env(env): return { 'currentCoinbase': decode_hex(env['currentCoinbase']), 'currentDifficulty': to_int(env['currentDifficulty']), 'currentNumber': to_int(env['currentNumber']), 'currentGasLimit': to_int(env['currentGasLimit']), 'currentTimestamp': to_int(env['currentTimestamp']), 'previousHash': decode_hex(env.get('previousHash', '00' * 32)), }
async def get_nodes_to_connect(self): nodekey = keys.PrivateKey(decode_hex( "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8")) remoteid = nodekey.public_key.to_hex() return [ kademlia.Node( keys.PublicKey(decode_hex(remoteid)), kademlia.Address('127.0.0.1', 30303, 30303)) ]
def test_decrypt_known_good_handshake(): # Data taken from https://gist.github.com/fjl/3a78780d17c755d22df2 privkey = keys.PrivateKey( decode_hex("c45f950382d542169ea207959ee0220ec1491755abe405cd7498d6b16adb6df8")) auth_ciphertext = decode_hex( "04a0274c5951e32132e7f088c9bdfdc76c9d91f0dc6078e848f8e3361193dbdc43b94351ea3d89e4ff33ddcefbc80070498824857f499656c4f79bbd97b6c51a514251d69fd1785ef8764bd1d262a883f780964cce6a14ff206daf1206aa073a2d35ce2697ebf3514225bef186631b2fd2316a4b7bcdefec8d75a1025ba2c5404a34e7795e1dd4bc01c6113ece07b0df13b69d3ba654a36e35e69ff9d482d88d2f0228e7d96fe11dccbb465a1831c7d4ad3a026924b182fc2bdfe016a6944312021da5cc459713b13b86a686cf34d6fe6615020e4acf26bf0d5b7579ba813e7723eb95b3cef9942f01a58bd61baee7c9bdd438956b426a4ffe238e61746a8c93d5e10680617c82e48d706ac4953f5e1c4c4f7d013c87d34a06626f498f34576dc017fdd3d581e83cfd26cf125b6d2bda1f1d56") # noqa: E501 auth_plaintext = decode_hex( "884c36f7ae6b406637c1f61b2f57e1d2cab813d24c6559aaf843c3f48962f32f46662c066d39669b7b2e3ba14781477417600e7728399278b1b5d801a519aa570034fdb5419558137e0d44cd13d319afe5629eeccb47fd9dfe55cc6089426e46cc762dd8a0636e07a54b31169eba0c7a20a1ac1ef68596f1f283b5c676bae4064abfcce24799d09f67e392632d3ffdc12e3d6430dcb0ea19c318343ffa7aae74d4cd26fecb93657d1cd9e9eaf4f8be720b56dd1d39f190c4e1c6b7ec66f077bb1100") # noqa: E501 decrypted = ecies.decrypt(auth_ciphertext, privkey) assert auth_plaintext == decrypted
def from_dict(cls, data): assert data['type'] == cls.__name__ secret_request = cls( message_identifier=data['message_identifier'], payment_identifier=data['payment_identifier'], secrethash=decode_hex(data['secrethash']), amount=data['amount'], ) secret_request.signature = decode_hex(data['signature']) return secret_request
def topup(self, deposit): """ Attempts to increase the deposit in an existing channel. Block until confirmation. """ if self.state != Channel.State.open: log.error('Channel must be open to be topped up.') return token_balance = self.core.token.call().balanceOf(self.core.address) if token_balance < deposit: log.error( 'Insufficient tokens available for the specified topup ({}/{})' .format(token_balance, deposit) ) return None log.info('Topping up channel to {} created at block #{} by {} tokens.'.format( self.receiver, self.block, deposit )) current_block = self.core.web3.eth.blockNumber data = (decode_hex(self.sender) + decode_hex(self.receiver) + self.block.to_bytes(4, byteorder='big')) tx = create_signed_contract_transaction( self.core.private_key, self.core.token, 'transfer', [ self.core.channel_manager.address, deposit, data ] ) self.core.web3.eth.sendRawTransaction(tx) log.debug('Waiting for topup confirmation event...') event = get_event_blocking( self.core.channel_manager, 'ChannelToppedUp', from_block=current_block + 1, argument_filters={ '_sender_address': self.sender, '_receiver_address': self.receiver, '_open_block_number': self.block } ) if event: log.debug('Successfully topped up channel in block {}.'.format(event['blockNumber'])) self.deposit += deposit return event else: log.error('No event received.') return None
def normalize_account_state(account_state): return { to_canonical_address(address): { 'balance': to_int(state['balance']), 'code': decode_hex(state['code']), 'nonce': to_int(state['nonce']), 'storage': { to_int(slot): big_endian_to_int(decode_hex(value)) for slot, value in state['storage'].items() }, } for address, state in account_state.items() }
def test_class_construction_sets_class_vars(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME): MathContract = web3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) assert MathContract.web3 == web3 assert MathContract.bytecode == decode_hex(MATH_CODE) assert MathContract.bytecode_runtime == decode_hex(MATH_RUNTIME)
def normalize_blockchain_fixtures(fixture): normalized_fixture = { 'blocks': [normalize_block(block_fixture) for block_fixture in fixture['blocks']], 'genesisBlockHeader': normalize_block_header(fixture['genesisBlockHeader']), 'lastblockhash': decode_hex(fixture['lastblockhash']), 'pre': normalize_account_state(fixture['pre']), 'postState': normalize_account_state(fixture['postState']), 'network': fixture['network'], } if 'genesisRLP' in fixture: normalized_fixture['genesisRLP'] = decode_hex(fixture['genesisRLP']) return normalized_fixture
def test_apply_transaction( chain, funded_address, funded_address_private_key, funded_address_initial_balance): vm = chain.get_vm() tx_idx = len(vm.block.transactions) recipient = decode_hex('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0c') amount = 100 from_ = funded_address tx = new_transaction(vm, from_, recipient, amount, funded_address_private_key) computation, _ = vm.apply_transaction(tx) access_logs = computation.vm_state.access_logs assert not computation.is_error tx_gas = tx.gas_price * constants.GAS_TX with vm.state.state_db(read_only=True) as state_db: assert state_db.get_balance(from_) == ( funded_address_initial_balance - amount - tx_gas) assert state_db.get_balance(recipient) == amount block = vm.block assert block.transactions[tx_idx] == tx assert block.header.gas_used == constants.GAS_TX assert len(access_logs.reads) > 0 assert len(access_logs.writes) > 0
def configure_homestead_header(vm, **header_params): validate_header_params_for_configuration(header_params) for field_name, value in header_params.items(): setattr(vm.block.header, field_name, value) if 'timestamp' in header_params and vm.block.header.block_number > 0: parent_header = get_parent_header(vm.block.header, vm.chaindb) vm.block.header.difficulty = compute_homestead_difficulty( parent_header, header_params['timestamp'], ) # In geth the modification of the state in the DAO fork block is performed # before any transactions are applied, so doing it here is the closest we # get to that. Another alternative would be to do it in Block.mine(), but # there we'd need to manually instantiate the State and update # header.state_root after we're done. if vm.support_dao_fork and vm.block.header.block_number == vm.dao_fork_block_number: vm_state = vm.state with vm_state.state_db() as state_db: for account in dao_drain_list: account = decode_hex(account) balance = state_db.get_balance(account) state_db.delta_balance(dao_refund_contract, balance) state_db.set_balance(account, 0) # Update state_root manually vm.block.header.state_root = vm_state.state_root return vm.block.header
def verify_balance_proof(self, sender, open_block_number, balance, signature): """Verify that a balance proof is valid and return the sender. This method just verifies if the balance proof is valid - no state update is performed. :returns: Channel, if it exists """ assert is_checksum_address(sender) if (sender, open_block_number) in self.unconfirmed_channels: raise InsufficientConfirmations( 'Insufficient confirmations for the channel ' '(sender=%s, open_block_number=%d)' % (sender, open_block_number)) try: c = self.channels[sender, open_block_number] except KeyError: raise NoOpenChannel('Channel does not exist or has been closed' '(sender=%s, open_block_number=%s)' % (sender, open_block_number)) if c.is_closed: raise NoOpenChannel('Channel closing has been requested already.') if not is_same_address( verify_balance_proof( self.receiver, open_block_number, balance, decode_hex(signature), self.channel_manager_contract.address ), sender ): raise InvalidBalanceProof('Recovered signer does not match the sender') return c
def test_get_cumulative_gas_used(chain, funded_address, funded_address_private_key): vm = chain.get_vm() # Empty block. block = vm.mine_block() chain.import_block(block) block1 = chain.get_canonical_block_by_number(1) blockgas = vm.get_cumulative_gas_used(block1) assert blockgas == 0 # Only one transaction in the block. recipient = decode_hex('0xa94f5374fce5edbc8e2a8697c15331677e6ebf0c') amount = 100 vm = chain.get_vm() from_ = funded_address tx = new_transaction(vm, from_, recipient, amount, funded_address_private_key) vm.apply_transaction(tx) block = vm.mine_block() chain.import_block(block) block2 = chain.get_canonical_block_by_number(2) blockgas = vm.get_cumulative_gas_used(block2) assert blockgas == constants.GAS_TX
def wait_for_contract(self, contract_address_hex, timeout=None): """ Wait until a contract is mined Args: contract_address_hex (string): hex encoded address of the contract timeout (int): time to wait for the contract to get mined Returns: True if the contract got mined, false otherwise """ contract_address = decode_hex(contract_address_hex) start_time = time.time() result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) current_time = time.time() while not result: if timeout and start_time + timeout > current_time: return False result = self._raiden.chain.client.web3.eth.getCode( to_checksum_address(contract_address), ) gevent.sleep(0.5) current_time = time.time() return len(result) > 0
def from_dict(cls, data): assert data['type'] == cls.__name__ message = cls( chain_id=data['chain_id'], message_identifier=data['message_identifier'], payment_identifier=data['payment_identifier'], secret=decode_hex(data['secret']), nonce=data['nonce'], token_network_address=to_canonical_address(data['token_network_address']), channel_identifier=decode_hex(data['channel']), transferred_amount=data['transferred_amount'], locked_amount=data['locked_amount'], locksroot=decode_hex(data['locksroot']), ) message.signature = decode_hex(data['signature']) return message
def from_dict(cls, data): assert data['type'] == cls.__name__ return cls( amount=data['amount'], expiration=data['expiration'], secrethash=decode_hex(data['secrethash']), )
def transact(self, function_name: str, *args, **kargs): data = ContractProxy.get_transaction_data(self.contract.abi, function_name, args) try: txhash = self.jsonrpc_client.send_transaction( to=self.contract.address, value=kargs.pop('value', 0), data=decode_hex(data), **kargs, ) except ValueError as e: action = inspect_client_error(e, self.jsonrpc_client.eth_node) if action == ClientErrorInspectResult.INSUFFICIENT_FUNDS: raise InsufficientFunds('Insufficient ETH for transaction') elif action == ClientErrorInspectResult.TRANSACTION_UNDERPRICED: raise ReplacementTransactionUnderpriced( 'Transaction was rejected. This is potentially ' 'caused by the reuse of the previous transaction ' 'nonce as well as paying an amount of gas less than or ' 'equal to the previous transaction\'s gas amount', ) raise e return txhash
def from_dict(cls, data): assert data['type'] == cls.__name__ delivered = cls( delivered_message_identifier=data['delivered_message_identifier'], ) delivered.signature = decode_hex(data['signature']) return delivered
def from_dict(cls, data): assert data['type'] == cls.__name__ expired_lock = cls( chain_id=data['chain_id'], nonce=data['nonce'], message_identifier=data['message_identifier'], token_network_address=to_canonical_address(data['token_network_address']), channel_identifier=data['channel_identifier'], transferred_amount=data['transferred_amount'], secrethash=decode_hex(data['secrethash']), recipient=to_canonical_address(data['recipient']), locked_amount=data['locked_amount'], locksroot=decode_hex(data['locksroot']), ) expired_lock.signature = decode_hex(data['signature']) return expired_lock
def from_dict(cls, data): assert data['type'] == cls.__name__ processed = cls( message_identifier=data['message_identifier'], ) processed.signature = decode_hex(data['signature']) return processed
def test_class_construction_sets_class_vars(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, some_address, ): MathContract = web3.eth.contract( abi=MATH_ABI, bytecode=MATH_CODE, bytecode_runtime=MATH_RUNTIME, ) classic = MathContract(some_address) assert classic.web3 == web3 assert classic.bytecode == decode_hex(MATH_CODE) assert classic.bytecode_runtime == decode_hex(MATH_RUNTIME)
def sign(self, key): """Sign this transaction with a private key. A potentially already existing signature would be overridden. """ if not is_bitcoin_available() or not is_secp256k1_available(): raise ImportError( "In order to sign transactions the " "`bitcoin` and `secp256k1` packages must be installed." ) from bitcoin import privtopub from secp256k1 import PrivateKey if key in (0, b'', b'\x00' * 32, b'0' * 64): raise ValueError("Zero privkey cannot sign") rawhash = keccak(rlp.encode(self, UnsignedTransaction)) if len(key) in {64, 66}: # we need a binary key key = decode_hex(key) pk = PrivateKey(key, raw=True) sig_bytes, rec_id = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(rawhash, raw=True) ) signature = sig_bytes + force_bytes(chr(rec_id)) self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27 self.r = decode_big_endian_int(signature[0:32]) self.s = decode_big_endian_int(signature[32:64]) self.sender = to_normalized_address(keccak(privtopub(key)[1:])[-20:]) return self
def test_private_key_signing_manager(web3_pk_signer, account_private_key, account_public_key, wait_for_transaction): web3 = web3_pk_signer assert account_public_key not in web3_pk_signer.eth.accounts with pytest.raises(ValueError): web3.eth.sendTransaction({ 'from': account_public_key, 'to': web3.eth.coinbase, 'value': 1, }) from ethereum import tester tester.keys.append(account_private_key) tester.accounts.append(decode_hex(account_public_key)) txn_hash = web3.eth.sendTransaction({ 'from': account_public_key, 'to': web3.eth.coinbase, 'value': 1, }) txn_receipt = wait_for_transaction(web3, txn_hash) txn = web3.eth.getTransaction(txn_hash) assert txn['from'] == account_public_key
def scrypt_hash(val, params): return scrypt.hash(str(val), decode_hex(params["salt"]), params["n"], params["r"], params["p"], params["dklen"])
async def test_lightchain_integration(request, event_loop, caplog): """Test LightChainSyncer/LightPeerChain against a running geth instance. In order to run this you need to pass the following to pytest: pytest --integration --capture=no --enode=... If you don't have any geth testnet data ready, it is very quick to generate some with: geth --testnet --syncmode full You only need the first 11 blocks for this test to succeed. Then you can restart geth with: geth --testnet --lightserv 90 --nodiscover """ # TODO: Implement a pytest fixture that runs geth as above, so that we don't need to run it # manually. if not pytest.config.getoption("--integration"): pytest.skip("Not asked to run integration tests") # will almost certainly want verbose logging in a failure caplog.set_level(logging.DEBUG) remote = Node.from_uri(pytest.config.getoption("--enode")) base_db = MemoryDB() chaindb = FakeAsyncChainDB(base_db) chaindb.persist_header(ROPSTEN_GENESIS_HEADER) headerdb = FakeAsyncHeaderDB(base_db) peer_pool = PeerPool( LESPeer, FakeAsyncHeaderDB(base_db), ROPSTEN_NETWORK_ID, ecies.generate_privkey(), ROPSTEN_VM_CONFIGURATION, ) chain = FakeAsyncRopstenChain(base_db) syncer = LightChainSyncer(chain, chaindb, peer_pool) syncer.min_peers_to_sync = 1 peer_chain = LightPeerChain(headerdb, peer_pool) asyncio.ensure_future(peer_pool.run()) asyncio.ensure_future(connect_to_peers_loop(peer_pool, tuple([remote]))) asyncio.ensure_future(peer_chain.run()) asyncio.ensure_future(syncer.run()) await asyncio.sleep( 0) # Yield control to give the LightChainSyncer a chance to start def finalizer(): event_loop.run_until_complete(peer_pool.cancel()) event_loop.run_until_complete(peer_chain.cancel()) event_loop.run_until_complete(syncer.cancel()) request.addfinalizer(finalizer) n = 11 # Wait for the chain to sync a few headers. async def wait_for_header_sync(block_number): while headerdb.get_canonical_head().block_number < block_number: await asyncio.sleep(0.1) await asyncio.wait_for(wait_for_header_sync(n), 5) # https://ropsten.etherscan.io/block/11 header = headerdb.get_canonical_block_header_by_number(n) body = await peer_chain.get_block_body_by_hash(header.hash) assert len(body['transactions']) == 15 receipts = await peer_chain.get_receipts(header.hash) assert len(receipts) == 15 assert encode_hex(keccak(rlp.encode(receipts[0]))) == ( '0xf709ed2c57efc18a1675e8c740f3294c9e2cb36ba7bb3b89d3ab4c8fef9d8860') assert len(peer_pool) == 1 head_info = peer_pool.peers[0].head_info head = await peer_chain.get_block_header_by_hash(head_info.block_hash) assert head.block_number == head_info.block_number # In order to answer queries for contract code, geth needs the state trie entry for the block # we specify in the query, but because of fast sync we can only assume it has that for recent # blocks, so we use the current head to lookup the code for the contract below. # https://ropsten.etherscan.io/address/0x95a48dca999c89e4e284930d9b9af973a7481287 contract_addr = decode_hex('0x8B09D9ac6A4F7778fCb22852e879C7F3B2bEeF81') contract_code = await peer_chain.get_contract_code(head.hash, contract_addr) assert encode_hex(contract_code) == '0x600060006000600060006000356000f1' account = await peer_chain.get_account(head.hash, contract_addr) assert account.code_hash == keccak(contract_code) assert account.balance == 0
def create_transaction_data(contract: Contract, func_name: str, args: List[Any]) -> bytes: data = contract._prepare_transaction(func_name, args)['data'] return decode_hex(data)
def encode_int(s): a = "%x" % s return b'' if s == 0 else decode_hex('0' * (len(a) % 2) + a)[::-1]
from . import trie from eth_utils import decode_hex DEFAULT_PY_TEST_CHAIN_ID = 10 default_config = dict( GENESIS_DIFFICULTY=0, GENESIS_PREVHASH=decode_hex( "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" ), # KECCAK EMPTY, hash of the empty bytes string. GENESIS_COINBASE=b'\x10' * 20, GENESIS_PRI_KEY=decode_hex( "46b9e861b63d3509c88b7817275a30d22d62c8cd8fa6486ddee35ef0d8e0495f"), TOTAL_COIN=5 * 10**9 * 10**18 * 10**6, GENESIS_STATE_ROOT=decode_hex( "0xd8b87cc5cf36cd3f2b655446bbaec331a63b80dfabececc379bf197e56949e39"), GENESIS_RECEIPTS_ROOT=decode_hex( "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" ), # KECCAK_EMPTY_LIST_RLP ~ keccak(rlp([])) GENESIS_LOGS_BLOOM_HASH=decode_hex( "0xd397b3b043d87fcd6fad1291ff0bfd16401c274896d8c63a923727f077b8e0b5" ), # KECCAK_EMPTY_BLOOM ~ keccak(b'\0' * 256) GENESIS_AUTHOR=decode_hex("0x0000000000000000000000000000000000000020"), GENESIS_GAS_LIMIT=30_000_000, MAX_BLOCK_SIZE_IN_BYTES=200 * 1024, ) default_conflux_conf = dict( chain_id=DEFAULT_PY_TEST_CHAIN_ID, db_cache_size=128, ledger_cache_size=1024,
def _fill_address(self) -> None: if "address" in self.keystore: self._address = Address(decode_hex(self.keystore["address"])) elif not self.locked: assert self.privkey self._address = privatekey_to_address(self.privkey)
def nodekey_bytes(): _nodekey_bytes = decode_hex(NODEKEY) return _nodekey_bytes
async def get_nodes_to_connect(self) -> List[Node]: # TODO: This should use the Discovery service to lookup nodes to connect to, but our # current implementation only supports v4 and with that it takes an insane amount of time # to find any LES nodes with the same network ID as us, so for now we hard-code some nodes # that seem to have a good uptime. from evm.chains.ropsten import RopstenChain from evm.chains.mainnet import MainnetChain if self.network_id == MainnetChain.network_id: return [ Node( keys.PublicKey( decode_hex( "1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082" )), # noqa: E501 Address("52.74.57.123", 30303, 30303)), Node( keys.PublicKey( decode_hex( "78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d" )), # noqa: E501 Address("191.235.84.50", 30303, 30303)), Node( keys.PublicKey( decode_hex( "ddd81193df80128880232fc1deb45f72746019839589eeb642d3d44efbb8b2dda2c1a46a348349964a6066f8afb016eb2a8c0f3c66f32fadf4370a236a4b5286" )), # noqa: E501 Address("52.231.202.145", 30303, 30303)), Node( keys.PublicKey( decode_hex( "3f1d12044546b76342d59d4a05532c14b85aa669704bfe1f864fe079415aa2c02d743e03218e57a33fb94523adb54032871a6c51b2cc5514cb7c7e35b3ed0a99" )), # noqa: E501 Address("13.93.211.84", 30303, 30303)), ] elif self.network_id == RopstenChain.network_id: return [ Node( keys.PublicKey( decode_hex( "88c2b24429a6f7683fbfd06874ae3f1e7c8b4a5ffb846e77c705ba02e2543789d66fc032b6606a8d8888eb6239a2abe5897ce83f78dcdcfcb027d6ea69aa6fe9" )), # noqa: E501 Address("163.172.157.61", 30303, 30303)), Node( keys.PublicKey( decode_hex( "a1ef9ba5550d5fac27f7cbd4e8d20a643ad75596f307c91cd6e7f85b548b8a6bf215cca436d6ee436d6135f9fe51398f8dd4c0bd6c6a0c332ccb41880f33ec12" )), # noqa: E501 Address("51.15.218.125", 30303, 30303)), Node( keys.PublicKey( decode_hex( "e80276aabb7682a4a659f4341c1199de79d91a2e500a6ee9bed16ed4ce927ba8d32ba5dea357739ffdf2c5bcc848d3064bb6f149f0b4249c1f7e53f8bf02bfc8" )), # noqa: E501 Address("51.15.39.57", 30303, 30303)), Node( keys.PublicKey( decode_hex( "584c0db89b00719e9e7b1b5c32a4a8942f379f4d5d66bb69f9c7fa97fa42f64974e7b057b35eb5a63fd7973af063f9a1d32d8c60dbb4854c64cb8ab385470258" )), # noqa: E501 Address("51.15.35.2", 30303, 30303)), Node( keys.PublicKey( decode_hex( "d40871fc3e11b2649700978e06acd68a24af54e603d4333faecb70926ca7df93baa0b7bf4e927fcad9a7c1c07f9b325b22f6d1730e728314d0e4e6523e5cebc2" )), # noqa: E501 Address("51.15.132.235", 30303, 30303)), Node( keys.PublicKey( decode_hex( "482484b9198530ee2e00db89791823244ca41dcd372242e2e1297dd06f6d8dd357603960c5ad9cc8dc15fcdf0e4edd06b7ad7db590e67a0b54f798c26581ebd7" )), # noqa: E501 Address("51.15.75.138", 30303, 30303)), ] else: raise ValueError("Unknown network_id: %s", self.network_id)
Use the following command line to run geth: ./build/bin/geth -vmodule p2p=4,p2p/discv5=0,eth/*=0 \ -nodekeyhex 45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8 \ -testnet -lightserv 90 """ import argparse from evm.chains.ropsten import RopstenChain, ROPSTEN_GENESIS_HEADER from evm.db.backends.memory import MemoryDB logging.basicConfig(level=logging.DEBUG, format='%(levelname)s: %(message)s') # The default remoteid can be used if you pass nodekeyhex as above to geth. nodekey = keys.PrivateKey( decode_hex( "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8") ) remoteid = nodekey.public_key.to_hex() parser = argparse.ArgumentParser() parser.add_argument('-remoteid', type=str, default=remoteid) parser.add_argument('-light', action='store_true', help="Connect as a light node") args = parser.parse_args() peer_class = ETHPeer # type: ignore if args.light: peer_class = LESPeer # type: ignore remote = Node(keys.PublicKey(decode_hex(args.remoteid)), Address('127.0.0.1', 30303, 30303)) chaindb = BaseChainDB(MemoryDB())
) chain.apply_transaction(tx.as_signed_transaction(SENDER)) chain.mine_block() return chain.chaindb @pytest.fixture def chaindb_fresh(): chain = PoWMiningChain.from_genesis(FakeAsyncAtomicDB(), GENESIS_PARAMS, GENESIS_STATE) assert chain.chaindb.get_canonical_head().block_number == 0 return chain.chaindb SENDER = keys.PrivateKey( decode_hex( "49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")) RECEIVER = keys.PrivateKey( decode_hex( "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")) GENESIS_PARAMS = { 'parent_hash': constants.GENESIS_PARENT_HASH, 'uncles_hash': constants.EMPTY_UNCLE_HASH, 'coinbase': constants.ZERO_ADDRESS, 'transaction_root': constants.BLANK_ROOT_HASH, 'receipt_root': constants.BLANK_ROOT_HASH, 'bloom': 0, 'difficulty': 5, 'block_number': constants.GENESIS_BLOCK_NUMBER, 'gas_limit': 3141592, 'gas_used': 0, 'timestamp': 1514764800,
def test_container_of_static_sized_fields(value, serialized): sedes = Container(tuple(itertools.repeat(uint8, len(value)))) assert encode_hex(ssz.encode(value, sedes)) == serialized assert ssz.decode(decode_hex(serialized), sedes) == value
def _handle_message(self, room, event) -> bool: """ Handle text messages sent to listening rooms """ if (event['type'] != 'm.room.message' or event['content']['msgtype'] != 'm.text' or self._stop_event.ready()): # Ignore non-messages and non-text messages return False sender_id = event['sender'] if sender_id == self._user_id: # Ignore our own messages return False user = self._get_user(sender_id) peer_address = self._validate_userid_signature(user) if not peer_address: self.log.debug( 'message from invalid user displayName signature', peer_user=user.user_id, room=room, ) return False # don't proceed if user isn't healthchecked (yet) if peer_address not in self._address_to_userids: # user not start_health_check'ed self.log.debug( 'message from non-healthchecked peer - ignoring', sender=user, sender_address=pex(peer_address), room=room, ) return False # rooms we created and invited user, or were invited specifically by them room_ids = self._get_room_ids_for_address(peer_address) if room.room_id not in room_ids: # this should not happen, but is not fatal, as we may not know user yet if bool(room.invite_only) < self._private_rooms: reason = 'required private room, but received message in a public' else: reason = 'unknown room for user' self.log.debug( 'received peer message in an invalid room - ignoring', peer_user=user.user_id, peer_address=pex(peer_address), room=room, reason=reason, ) return False if not room_ids or room.room_id != room_ids[0]: self.log.debug( 'received message triggered new comms room for peer', peer_user=user.user_id, peer_address=pex(peer_address), known_user_rooms=room_ids, room=room, ) self._set_room_id_for_address(peer_address, room.room_id) data = event['content']['body'] if not isinstance(data, str): self.log.warning( 'Received message body not a string', peer_user=user.user_id, peer_address=to_checksum_address(peer_address), room=room, ) return False if data.startswith('0x'): try: message = message_from_bytes(decode_hex(data)) if not message: raise InvalidProtocolMessage except (DecodeError, AssertionError) as ex: self.log.warning( "Can't parse message binary data", message_data=data, peer_address=pex(peer_address), _exc=ex, ) return False except InvalidProtocolMessage as ex: self.log.warning( "Received message binary data is not a valid message", message_data=data, peer_address=pex(peer_address), _exc=ex, ) return False else: try: message_dict = json.loads(data) message = message_from_dict(message_dict) except (UnicodeDecodeError, json.JSONDecodeError) as ex: self.log.warning( "Can't parse message data JSON", message_data=data, peer_address=pex(peer_address), _exc=ex, ) return False except InvalidProtocolMessage as ex: self.log.warning( "Message data JSON are not a valid message", message_data=data, peer_address=pex(peer_address), _exc=ex, ) return False self.log.debug( 'MESSAGE_DATA', data=data, sender=pex(peer_address), sender_user=user, room=room, ) if isinstance(message, Ping): self.log.warning( 'Not required Ping received', message=data, ) return False elif isinstance(message, SignedMessage): if message.sender != peer_address: self.log.warning( 'Message not signed by sender!', message=message, signer=message.sender, peer_address=peer_address, ) return False if isinstance(message, Delivered): self._receive_delivered(message) else: self._receive_message(message) else: self.log.warning( 'Received Invalid message', message=data, ) return False return True
inbound_peers, (len(self.connected_nodes) - inbound_peers)) try: await wait_with_token(asyncio.sleep(self._report_interval), self.finished.wait(), token=self.cancel_token) except OperationCancelled: break DEFAULT_PREFERRED_NODES: Dict[int, Tuple[Node, ...]] = { MAINNET_NETWORK_ID: ( Node( keys.PublicKey( decode_hex( "1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082" )), # noqa: E501 Address("52.74.57.123", 30303, 30303)), Node( keys.PublicKey( decode_hex( "78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d" )), # noqa: E501 Address("191.235.84.50", 30303, 30303)), Node( keys.PublicKey( decode_hex( "ddd81193df80128880232fc1deb45f72746019839589eeb642d3d44efbb8b2dda2c1a46a348349964a6066f8afb016eb2a8c0f3c66f32fadf4370a236a4b5286" )), # noqa: E501 Address("52.231.202.145", 30303, 30303)), Node(
les2_topic = discovery.get_v5_topic(LESProtocolV2, ROPSTEN_GENESIS_HEADER.hash) assert les2_topic == b'LES2@41941023680923e0' def remove_whitespace(s): return re.sub(r"\s+", "", s) eip8_packets = { discovery.CMD_PING: dict( # ping packet with version 4, additional list elements ping1=decode_hex( remove_whitespace(''' e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663a aa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a 4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000 000000000000000000018208ae820d058443b9a3550102''')), # ping packet with version 555, additional list elements and additional random data ping2=decode_hex( remove_whitespace(''' 577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e 7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3 d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef 12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203 040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba7602 3fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee191 7084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c7 6d922dc3''')), ),
# before any transactions are applied, so doing it here is the closest we # get to that. Another alternative would be to do it in Block.mine(), but # there we'd need to manually instantiate the State and update # header.state_root after we're done. if vm.support_dao_fork and vm.block.header.block_number == vm.dao_fork_block_number: with vm.state_db() as state_db: for account in dao_drain_list: account = decode_hex(account) balance = state_db.get_balance(account) state_db.delta_balance(dao_refund_contract, balance) state_db.set_balance(account, 0) return vm.block.header dao_refund_contract = decode_hex('0xbf4ed7b27f1d666546e30d74d50d173d20bca754') dao_drain_list = [ "0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", "0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", "0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", "0xecd135fa4f61a655311e86238c92adcd779555d2", "0x1975bd06d486162d5dc297798dfc41edd5d160a7", "0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6", "0x319f70bab6845585f412ec7724b744fec6095c85", "0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936", "0x5c8536898fbb74fc7445814902fd08422eac56d0", "0x6966ab0d485353095148a2155858910e0965b6f9", "0x779543a0491a837ca36ce8c635d6154e3c4911a6", "0x2a5ed960395e2a49b1c758cef4aa15213cfd874c", "0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5", "0x9c50426be05db97f5d64fc54bf89eff947f0a321",
def _test(): """ Create a Peer instance connected to a local geth instance and log messages exchanged with it. Use the following command line to run geth: ./build/bin/geth -vmodule p2p=4,p2p/discv5=0,eth/*=0 \ -nodekeyhex 45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8 \ -testnet -lightserv 90 """ import argparse import signal from evm.chains.ropsten import RopstenChain, ROPSTEN_GENESIS_HEADER from evm.db.backends.memory import MemoryDB from tests.p2p.integration_test_helpers import FakeAsyncHeaderDB logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s: %(message)s') # The default remoteid can be used if you pass nodekeyhex as above to geth. nodekey = keys.PrivateKey( decode_hex( "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8") ) remoteid = nodekey.public_key.to_hex() parser = argparse.ArgumentParser() parser.add_argument('-remoteid', type=str, default=remoteid) parser.add_argument('-light', action='store_true', help="Connect as a light node") args = parser.parse_args() peer_class = ETHPeer # type: ignore if args.light: peer_class = LESPeer # type: ignore remote = Node(keys.PublicKey(decode_hex(args.remoteid)), Address('127.0.0.1', 30303, 30303)) headerdb = FakeAsyncHeaderDB(MemoryDB()) headerdb.persist_header(ROPSTEN_GENESIS_HEADER) network_id = RopstenChain.network_id loop = asyncio.get_event_loop() peer = loop.run_until_complete( handshake(remote, ecies.generate_privkey(), peer_class, headerdb, network_id, CancelToken("Peer test"))) async def request_stuff(): # Request some stuff from ropsten's block 2440319 # (https://ropsten.etherscan.io/block/2440319), just as a basic test. nonlocal peer block_hash = decode_hex( '0x59af08ab31822c992bb3dad92ddb68d820aa4c69e9560f07081fa53f1009b152' ) if peer_class == ETHPeer: peer = cast(ETHPeer, peer) peer.sub_proto.send_get_block_headers(block_hash, 1) peer.sub_proto.send_get_block_bodies([block_hash]) peer.sub_proto.send_get_receipts([block_hash]) else: peer = cast(LESPeer, peer) request_id = 1 peer.sub_proto.send_get_block_headers(block_hash, 1, request_id) peer.sub_proto.send_get_block_bodies([block_hash], request_id + 1) peer.sub_proto.send_get_receipts(block_hash, request_id + 2) sigint_received = asyncio.Event() for sig in [signal.SIGINT, signal.SIGTERM]: loop.add_signal_handler(sig, sigint_received.set) async def exit_on_sigint(): await sigint_received.wait() await peer.cancel() loop.stop() asyncio.ensure_future(exit_on_sigint()) asyncio.ensure_future(request_stuff()) asyncio.ensure_future(peer.run()) loop.run_forever() loop.close()
from eth_utils import decode_hex default_config = dict( GENESIS_DIFFICULTY=0, GENESIS_PREVHASH=b'\x00' * 32, GENESIS_COINBASE=b'\x00' * 20, GENESIS_PRI_KEY=decode_hex( "46b9e861b63d3509c88b7817275a30d22d62c8cd8fa6486ddee35ef0d8e0495f"), TOTAL_COIN=5 * 10**9 * 10**18, GENESIS_STATE_ROOT=decode_hex( "0x8d9fa8e7b2d2033a7acd4581a899b9b4ee9b81ff6c0edb15e831d4ff615fe483"), GENESIS_RECEIPTS_ROOT=decode_hex( "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"), )
def _chain_with_block_validation(VM, base_db, genesis_state, chain_cls=Chain): """ Return a Chain object containing just the genesis block. The Chain's state includes one funded account, which can be found in the funded_address in the chain itself. This Chain will perform all validations when importing new blocks, so only valid and finalized blocks can be used with it. If you want to test importing arbitrarily constructe, not finalized blocks, use the chain_without_block_validation fixture instead. """ genesis_params = { "bloom": 0, "coinbase": to_canonical_address("8888f1f195afa192cfee860698584c030f4c9db1"), "difficulty": 131072, "extra_data": b"B", "gas_limit": 3141592, "gas_used": 0, "mix_hash": decode_hex( "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" ), # noqa: E501 "nonce": decode_hex("0102030405060708"), "block_number": 0, "parent_hash": decode_hex( "0000000000000000000000000000000000000000000000000000000000000000" ), # noqa: E501 "receipt_root": decode_hex( "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" ), # noqa: E501 "timestamp": 1422494849, "transaction_root": decode_hex( "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421" ), # noqa: E501 "uncles_hash": decode_hex( "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347" ) # noqa: E501 } klass = chain_cls.configure( __name__='TestChain', vm_configuration=((constants.GENESIS_BLOCK_NUMBER, VM.configure(consensus_class=PowConsensus)), ), chain_id=1337, ) chain = klass.from_genesis(base_db, genesis_params, genesis_state) return chain
MAINNET_VM_CONFIGURATION = tuple(zip(MAINNET_FORK_BLOCKS, MAINNET_VMS)) class BaseMainnetChain: chain_id = MAINNET_CHAIN_ID vm_configuration: Tuple[Tuple[BlockNumber, Type[VirtualMachineAPI]], ...] = MAINNET_VM_CONFIGURATION class MainnetChain(BaseMainnetChain, Chain): pass MAINNET_GENESIS_HEADER = BlockHeader( difficulty=eth_constants.GENESIS_DIFFICULTY, extra_data=decode_hex( "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"), gas_limit=eth_constants.GENESIS_GAS_LIMIT, gas_used=0, bloom=0, mix_hash=eth_constants.ZERO_HASH32, nonce=eth_constants.GENESIS_NONCE, block_number=0, parent_hash=eth_constants.ZERO_HASH32, receipt_root=eth_constants.BLANK_ROOT_HASH, uncles_hash=eth_constants.EMPTY_UNCLE_HASH, state_root=decode_hex( "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"), timestamp=0, transaction_root=eth_constants.BLANK_ROOT_HASH, )
from eth_utils import decode_hex default_config = dict( GENESIS_DIFFICULTY=0, GENESIS_PREVHASH=b'\x00' * 32, GENESIS_COINBASE=b'\x00' * 20, GENESIS_PRI_KEY=decode_hex( "46b9e861b63d3509c88b7817275a30d22d62c8cd8fa6486ddee35ef0d8e0495f"), TOTAL_COIN=5 * 10**9 * 10**18 * 10**6, GENESIS_STATE_ROOT=decode_hex( "0xb11554381a6ee59a94e33efcd7288e09f332cf4bff51e9b6ce8a5b194ba55b92"), GENESIS_RECEIPTS_ROOT=decode_hex( "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"), GENESIS_AUTHOR=decode_hex("0x0000000000000000000000000000000000000005"), )
def funded_address_private_key(): return keys.PrivateKey( decode_hex( '0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8' ))
wrap_in_list, ) # # Defaults # DEFAULT_MAIN_ENVIRONMENT = { "currentCoinbase": to_canonical_address("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba"), "currentDifficulty": 131072, "currentGasLimit": 1000000, "currentNumber": 1, "currentTimestamp": 1000, "previousHash": decode_hex( "0x5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6" ), } DEFAULT_MAIN_TRANSACTION = { "data": b"", "gasLimit": 100000, "gasPrice": 0, "nonce": 0, "secretKey": decode_hex("0x45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8"), "to": to_canonical_address("0x0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6"), "value": 0 } # type: TransactionDict
def _deserialize(self, value: str, attr: Any, data: Any) -> bytes: return decode_hex(value)
def test_payment_channel_proxy_basics( token_network_proxy, private_keys, token_proxy, chain_id, web3, ): token_network_address = to_canonical_address( token_network_proxy.proxy.contract.address) c1_client = JSONRPCClient(web3, private_keys[1]) c2_client = JSONRPCClient(web3, private_keys[2]) c1_token_network_proxy = TokenNetwork( c1_client, token_network_address, ) c2_token_network_proxy = TokenNetwork( c2_client, token_network_address, ) # create a channel channel_identifier = c1_token_network_proxy.new_netting_channel( c2_client.sender, TEST_SETTLE_TIMEOUT_MIN, ) assert channel_identifier is not None # create channel proxies channel_proxy_1 = PaymentChannel(c1_token_network_proxy, channel_identifier) channel_proxy_2 = PaymentChannel(c2_token_network_proxy, channel_identifier) channel_filter = channel_proxy_1.all_events_filter( from_block=web3.eth.blockNumber, to_block='latest', ) assert channel_proxy_1.channel_identifier == channel_identifier assert channel_proxy_2.channel_identifier == channel_identifier assert channel_proxy_1.opened() is True assert channel_proxy_2.opened() is True # check the settlement timeouts assert channel_proxy_1.settle_timeout() == channel_proxy_2.settle_timeout() assert channel_proxy_1.settle_timeout() == TEST_SETTLE_TIMEOUT_MIN events = channel_filter.get_all_entries() assert len(events) == 1 # ChannelOpened # test deposits initial_token_balance = 100 token_proxy.transfer(c1_client.sender, initial_token_balance) initial_balance_c1 = token_proxy.balance_of(c1_client.sender) assert initial_balance_c1 == initial_token_balance initial_balance_c2 = token_proxy.balance_of(c2_client.sender) assert initial_balance_c2 == 0 # actual deposit channel_proxy_1.set_total_deposit(10) events = channel_filter.get_all_entries() assert len(events) == 2 # ChannelOpened, ChannelNewDeposit # balance proof by c2 transferred_amount = 3 balance_proof = BalanceProof( channel_identifier=channel_identifier, token_network_address=to_checksum_address(token_network_address), nonce=1, chain_id=chain_id, transferred_amount=transferred_amount, ) balance_proof.signature = encode_hex( eth_sign( privkey=encode_hex(private_keys[1]), data=balance_proof.serialize_bin(), )) # correct close c2_token_network_proxy.close( channel_identifier=channel_identifier, partner=c1_client.sender, balance_hash=decode_hex(balance_proof.balance_hash), nonce=balance_proof.nonce, additional_hash=decode_hex(balance_proof.additional_hash), signature=decode_hex(balance_proof.signature), ) assert channel_proxy_1.closed() is True assert channel_proxy_2.closed() is True events = channel_filter.get_all_entries() assert len(events) == 3 # ChannelOpened, ChannelNewDeposit, ChannelClosed # check the settlement timeouts again assert channel_proxy_1.settle_timeout() == channel_proxy_2.settle_timeout() assert channel_proxy_1.settle_timeout() == TEST_SETTLE_TIMEOUT_MIN # update transfer wait_blocks(c1_client.web3, TEST_SETTLE_TIMEOUT_MIN) c2_token_network_proxy.settle( channel_identifier=channel_identifier, transferred_amount=0, locked_amount=0, locksroot=EMPTY_HASH, partner=c1_client.sender, partner_transferred_amount=transferred_amount, partner_locked_amount=0, partner_locksroot=EMPTY_HASH, ) assert channel_proxy_1.settled() is True assert channel_proxy_2.settled() is True events = channel_filter.get_all_entries() assert len( events ) == 4 # ChannelOpened, ChannelNewDeposit, ChannelClosed, ChannelSettled
local_private_key=recipient_private_key, remote_public_key=initiator_public_key, local_node_id=recipient_node_id, remote_node_id=initiator_node_id, id_nonce=id_nonce, is_locally_initiated=False, ) assert initiator_session_keys.auth_response_key == recipient_session_keys.auth_response_key assert initiator_session_keys.encryption_key == recipient_session_keys.decryption_key assert initiator_session_keys.decryption_key == recipient_session_keys.encryption_key @pytest.mark.parametrize(["local_secret_key", "remote_public_key", "shared_secret_key"], [ [ decode_hex("0xfb757dc581730490a1d7a00deea65e9b1936924caaea8f44d476014856b68736"), decode_hex( "0x9961e4c2356d61bedb83052c115d311acb3a96f5777296dcf297351130266231503061ac4aaee666073d" "7e5bc2c80c3f5c5b500c1cb5fd0a76abbb6b675ad157" ), decode_hex("0x033b11a2a1f214567e1537ce5e509ffd9b21373247f2a3ff6841f4976f53165e7e"), ] ]) def test_official_key_agreement(local_secret_key, remote_public_key, shared_secret_key): assert ecdh_agree(local_secret_key, remote_public_key) == shared_secret_key @pytest.mark.parametrize( [ "secret", "initiator_node_id",
def pad32_dict_values(some_dict): return { key: encode_hex(pad32(decode_hex(value))) for key, value in some_dict.items() }
def get_name_node(name): name = name.lower() if not name.endswith('eth'): name = name + '.eth' name = decode_hex(name_hash2(name)) return name
from eth_keys import keys from eth_utils import decode_hex from tests.trinity.core.integration_test_helpers import FUNDED_ACCT, load_mining_chain RECEIVER = keys.PrivateKey( decode_hex( "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")) def build_pow_fixture(write_db, num_blocks=20): chain = load_mining_chain(write_db) for i in range(num_blocks): tx = chain.create_unsigned_transaction( nonce=i, gas_price=1234, gas=123400, to=RECEIVER.public_key.to_canonical_address(), value=i, data=b'', ) chain.apply_transaction(tx.as_signed_transaction(FUNDED_ACCT)) chain.mine_block() return chain.chaindb
UnsignedENR, ) from p2p.discv5.identity_schemes import ( IdentityScheme, V4IdentityScheme, IdentitySchemeRegistry, ) # Source: https://github.com/fjl/EIPs/blob/0acb5939555cbd0efcdd04da0d3acb0cc81d049a/EIPS/eip-778.md OFFICIAL_TEST_DATA = { "repr": ("enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkT" "fj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHY" "pMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8"), "private_key": decode_hex( "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291"), "node_id": decode_hex( "a448f24c6d18e575453db13171562b71999873db5b286df957af199ec94617f7"), "identity_scheme": V4IdentityScheme, "sequence_number": 1, "kv_pairs": { b"id": b"v4", b"ip": decode_hex("7f000001"), b"secp256k1": decode_hex( "03ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd3138",
def set_fork_point(self, fork_hash, height): self.parent_hash = decode_hex(fork_hash) self.height = height + 1