def normalize_block_header(header: Dict[str, Any]) -> Dict[str, Any]: 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 normalize_blockchain_fixtures(fixture: Dict[str, Any]) -> Dict[str, Any]: 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_post_state(fixture.get('postState')), 'network': fixture['network'], } if 'sealEngine' in fixture: normalized_fixture['sealEngine'] = fixture['sealEngine'] if 'genesisRLP' in fixture: normalized_fixture['genesisRLP'] = decode_hex(fixture['genesisRLP']) return normalized_fixture
def normalize_account_state(account_state: FixtureAccountState) -> AccountState: 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 normalize_bytes(value: Union[bytes, str]) -> bytes: if is_bytes(value): return cast(bytes, value) elif is_text(value) and is_hex(value): return decode_hex(cast(str, value)) elif is_text(value): return b'' else: raise TypeError("Value must be either a string or bytes object")
def normalize_exec(exec_params: Dict[str, Any]) -> Dict[str, Any]: return { 'origin': to_canonical_address(exec_params['origin']), 'address': to_canonical_address(exec_params['address']), 'caller': to_canonical_address(exec_params['caller']), 'value': to_int(exec_params['value']), 'data': decode_hex(exec_params['data']), 'gas': to_int(exec_params['gas']), 'gasPrice': to_int(exec_params['gasPrice']), }
def normalize_vmtest_fixture(fixture: Dict[str, Any]) -> Iterable[Tuple[str, Any]]: yield 'env', normalize_environment(fixture['env']) yield 'exec', normalize_exec(fixture['exec']) yield 'pre', normalize_account_state(fixture['pre']) if 'post' in fixture: yield 'post', normalize_account_state(fixture['post']) if 'callcreates' in fixture: yield 'callcreates', normalize_callcreates(fixture['callcreates']) if 'gas' in fixture: yield 'gas', to_int(fixture['gas']) if 'out' in fixture: yield 'out', decode_hex(fixture['out']) if 'logs' in fixture: yield 'logs', decode_hex(fixture['logs'])
def normalize_signed_transaction(transaction: Dict[str, Any]) -> Dict[str, Any]: return { 'data': robust_decode_hex(transaction['data']), 'gasLimit': to_int(transaction['gasLimit']), 'gasPrice': to_int(transaction['gasPrice']), 'nonce': to_int(transaction['nonce']), 'r': to_int(transaction['r']), 's': to_int(transaction['s']), 'v': to_int(transaction['v']), 'to': decode_hex(transaction['to']), 'value': to_int(transaction['value']), }
def normalize_callcreates(callcreates: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: return [ { 'data': decode_hex(created_call['data']), 'destination': ( to_canonical_address(created_call['destination']) if created_call['destination'] else CREATE_CONTRACT_ADDRESS ), 'gasLimit': to_int(created_call['gasLimit']), 'value': to_int(created_call['value']), } for created_call in callcreates ]
def normalize_block(block: Dict[str, Any]) -> Dict[str, Any]: normalized_block: Dict[str, Any] = {} try: normalized_block['rlp'] = decode_hex(block['rlp']) except ValueError as err: normalized_block['rlp_error'] = err if 'blockHeader' in block: normalized_block['blockHeader'] = normalize_block_header(block['blockHeader']) if 'transactions' in block: normalized_block['transactions'] = [ normalize_signed_transaction(transaction) for transaction in block['transactions'] ] return normalized_block
def normalize_transactiontest_fixture(fixture: Dict[str, Any], fork: str) -> Dict[str, Any]: normalized_fixture = {} fork_data = fixture[fork] try: normalized_fixture['rlp'] = decode_hex(fixture['rlp']) except binascii.Error: normalized_fixture['rlpHex'] = fixture['rlp'] if "sender" in fork_data: normalized_fixture['sender'] = fork_data['sender'] if "hash" in fork_data: normalized_fixture['hash'] = fork_data['hash'] return normalized_fixture
def normalize_signed_transaction( transaction: Dict[str, Any]) -> Dict[str, Any]: normalized_universal_transaction = { 'data': robust_decode_hex(transaction['data']), 'gasLimit': to_int(transaction['gasLimit']), 'nonce': to_int(transaction['nonce']), 'r': to_int(transaction['r']), 's': to_int(transaction['s']), 'v': to_int(transaction['v']), 'to': decode_hex(transaction['to']), 'value': to_int(transaction['value']), } if 'type' in transaction: type_id = to_int(transaction['type']) if type_id == 1: custom_fields = { 'type': type_id, 'gasPrice': to_int(transaction['gasPrice']), 'chainId': to_int(transaction['chainId']), } elif type_id == 2: custom_fields = { 'type': type_id, 'chainId': to_int(transaction['chainId']), 'maxFeePerGas': to_int(transaction['maxFeePerGas']), 'maxPriorityFeePerGas': to_int(transaction['maxPriorityFeePerGas']), } else: raise ValidationError( f"Did not recognize transaction type {type_id}") else: custom_fields = { 'gasPrice': to_int(transaction['gasPrice']), } return merge(normalized_universal_transaction, custom_fields)
def normalize_raw_transaction(raw_transaction_hex): return decode_hex(raw_transaction_hex)
def normalize_post_state_hash(post_state: Dict[str, Any]) -> Iterable[Tuple[str, bytes]]: yield 'hash', decode_hex(post_state['hash']) if 'logs' in post_state: yield 'logs', decode_hex(post_state['logs'])
def signBlock(self, header_dict: dict, private_key: str, send_transaction_dicts: List[dict] = [], receive_transaction_dicts: List[dict] = []) -> AttributeDict: ''' transaction = { # Note that the address must be in checksum format: 'to': '0xF0109fC8DF283027b6285cc889F5aA624EaC1F55', 'value': 1000000000, 'gas': 2000000, 'gasPrice': 234567897654321, 'nonce': 0, 'chainId': 1 } receive_transaction = { 'senderBlockHash', 'sendTransactionHash', 'isRefund', 'remainingRefund' } header = { 'parentHash', 'blockNumber', 'extraData', } :param send_transaction_dicts: :param receive_transaction_dicts: :param reward_bundle: :param private_key: :return: ''' timestamp = int(time.time()) if not is_bytes(header_dict['parentHash']): header_dict['parentHash'] = to_bytes( hexstr=header_dict['parentHash']) if "extraData" in header_dict: if not is_bytes(header_dict['extraData']): extra_data = to_bytes(hexstr=header_dict['extraData']) else: extra_data = header_dict['extraData'] else: extra_data = b'' if "chainId" in header_dict: chain_id = header_dict['chainId'] else: if len(send_transaction_dicts) > 0: if 'chainId' in send_transaction_dicts[0]: chain_id = send_transaction_dicts[0]['chainId'] else: chain_id = 1 else: chain_id = 1 photon_timestamp = get_photon_timestamp(chain_id) if timestamp < photon_timestamp: fork_id = 0 else: fork_id = 1 account = self.privateKeyToAccount(private_key) send_transactions = [] for transaction_dict in send_transaction_dicts: if 'data' in transaction_dict: if not is_bytes(transaction_dict['data']): data = to_bytes(hexstr=transaction_dict['data']) else: data = transaction_dict['data'] else: data = b'' if not is_bytes(transaction_dict['to']): to = to_bytes(hexstr=transaction_dict['to']) else: to = transaction_dict['to'] if fork_id == 0: tx = BosonTransaction(nonce=transaction_dict['nonce'], gas_price=transaction_dict['gasPrice'], gas=transaction_dict['gas'], to=to, value=transaction_dict['value'], data=data, v=0, r=0, s=0) signed_tx = tx.get_signed(account._key_obj, chain_id) elif fork_id == 1: if 'codeAddress' in transaction_dict: if not is_bytes(transaction_dict['codeAddress']): code_address = to_bytes( hexstr=transaction_dict['codeAddress']) else: code_address = transaction_dict['codeAddress'] else: code_address = b'' if 'executeOnSend' in transaction_dict: execute_on_send = bool(transaction_dict['executeOnSend']) else: execute_on_send = False tx = PhotonTransaction(nonce=transaction_dict['nonce'], gas_price=transaction_dict['gasPrice'], gas=transaction_dict['gas'], to=to, value=transaction_dict['value'], data=data, code_address=code_address, execute_on_send=execute_on_send, v=0, r=0, s=0) signed_tx = tx.get_signed(account._key_obj, chain_id) else: raise Exception("Unknown fork id") send_transactions.append(signed_tx) receive_transactions = [] for receive_transaction_dict in receive_transaction_dicts: if not is_bytes(receive_transaction_dict['senderBlockHash']): receive_transaction_dict['senderBlockHash'] = to_bytes( hexstr=receive_transaction_dict['senderBlockHash']) if not is_bytes(receive_transaction_dict['sendTransactionHash']): receive_transaction_dict['sendTransactionHash'] = to_bytes( hexstr=receive_transaction_dict['sendTransactionHash']) if not is_boolean(receive_transaction_dict['isRefund']): receive_transaction_dict['isRefund'] = False if to_int( hexstr=receive_transaction_dict['isRefund']) == 0 else True # We renamed the fourth parameter in the new photon fork fourth_parameter = 0 if 'remainingRefund' in receive_transaction_dict: if not is_integer(receive_transaction_dict['remainingRefund']): fourth_parameter = to_int( hexstr=receive_transaction_dict['remainingRefund']) else: fourth_parameter = receive_transaction_dict[ 'remainingRefund'] elif 'refundAmount' in receive_transaction_dict: if not is_integer(receive_transaction_dict['refundAmount']): fourth_parameter = to_int( hexstr=receive_transaction_dict['refundAmount']) else: fourth_parameter = receive_transaction_dict['refundAmount'] if fork_id == 0: receive_transaction_class = BosonReceiveTransaction elif fork_id == 1: receive_transaction_class = PhotonReceiveTransaction else: raise Exception("Unknown fork id") tx = receive_transaction_class( receive_transaction_dict['senderBlockHash'], receive_transaction_dict['sendTransactionHash'], receive_transaction_dict['isRefund'], fourth_parameter) receive_transactions.append(tx) send_tx_root_hash, _ = make_trie_root_and_nodes(send_transactions) receive_tx_root_hash, _ = make_trie_root_and_nodes( receive_transactions) chain_address = account.address reward_bundle = StakeRewardBundle() header = BlockHeader(chain_address=decode_hex(chain_address), parent_hash=header_dict['parentHash'], transaction_root=send_tx_root_hash, receive_transaction_root=receive_tx_root_hash, block_number=header_dict['blockNumber'], timestamp=timestamp, extra_data=extra_data, reward_hash=reward_bundle.hash) signed_header = header.get_signed(account._key_obj, chain_id) signed_micro_header = signed_header.to_micro_header() if fork_id == 0: micro_block = BosonMicroBlock( header=signed_micro_header, transactions=send_transactions, receive_transactions=receive_transactions, reward_bundle=reward_bundle) rlp_encoded_micro_block = rlp.encode(micro_block, sedes=BosonMicroBlock) elif fork_id == 1: micro_block = PhotonMicroBlock( header=signed_micro_header, transactions=send_transactions, receive_transactions=receive_transactions, reward_bundle=reward_bundle) rlp_encoded_micro_block = rlp.encode(micro_block, sedes=PhotonMicroBlock) else: raise Exception("Unknown fork id") return AttributeDict({ 'rawBlock': encode_hex(rlp_encoded_micro_block), 'send_tx_hashes': [tx.hash for tx in send_transactions], 'receive_tx_hashes': [tx.hash for tx in receive_transactions], 'r': signed_header.r, 's': signed_header.s, 'v': signed_header.v, })
def normalize_topic(topic): if topic is None: return None else: return decode_hex(topic)
def normalize_private_key(value): return decode_hex(value)
def normalize_topic_list(topics): for topic in topics: if topic is None: yield None else: yield decode_hex(topic)