def ecmul(computation): computation.gas_meter.consume_gas(constants.GAS_ECMUL, reason='ECMUL Precompile') try: result = _ecmull(computation.msg.data) except ValidationError: raise VMError("Invalid ECMUL parameters") result_x, result_y = result result_bytes = b''.join(( pad32(int_to_big_endian(result_x.n)), pad32(int_to_big_endian(result_y.n)), )) computation.output = result_bytes return computation
def ecmul(computation): computation.consume_gas(constants.GAS_ECMUL, reason='ECMUL Precompile') try: result = _ecmull(computation.msg.data) except ValidationError: raise VMError("Invalid ECMUL parameters") result_x, result_y = result result_bytes = b''.join(( pad32(int_to_big_endian(result_x.n)), pad32(int_to_big_endian(result_y.n)), )) computation.output = result_bytes return computation
def _block_to_dict(self, block): logs_bloom = encode_hex(int_to_big_endian(block.header.bloom))[2:] logs_bloom = '0x' + logs_bloom.rjust(512, '0') return { "difficulty": hex(block.header.difficulty), "extraData": encode_hex(block.header.extra_data), "gasLimit": hex(block.header.gas_limit), "gasUsed": hex(block.header.gas_used), "hash": encode_hex(block.header.hash), "logsBloom": logs_bloom, "mixHash": encode_hex(block.header.mix_hash), "nonce": encode_hex(block.header.nonce), "number": hex(block.header.block_number), "parentHash": encode_hex(block.header.parent_hash), "receiptsRoot": encode_hex(block.header.receipt_root), "sha3Uncles": encode_hex(block.header.uncles_hash), "stateRoot": encode_hex(block.header.state_root), "timestamp": hex(block.header.timestamp), "totalDifficulty": hex(self.chain.chaindb.get_score(block.hash)), "transactions": [encode_hex(tx.hash) for tx in block.transactions], "transactionsRoot": encode_hex(block.header.transaction_root), "uncles": [encode_hex(uncle.hash) for uncle in block.uncles], "size": hex(len(rlp.encode(block))), "miner": encode_hex(block.header.coinbase), }
def test_chunk_iteration(): chunk_number = COLLATION_SIZE // CHUNK_SIZE test_chunks = [ zpad_left(int_to_big_endian(i), CHUNK_SIZE) for i in range(chunk_number) ] chunks = test_chunks body = b"".join(chunks) for recovered, original in zip_longest(chunk_iterator(body), chunks, fillvalue=None): assert recovered is not None and original is not None assert recovered == original chunks = test_chunks[:-2] body = b"".join(chunks) for recovered, original in zip_longest(chunk_iterator(body), chunks, fillvalue=None): assert recovered is not None and original is not None assert recovered == original body = b"".join(test_chunks)[:-2] with pytest.raises(ValueError): next(chunk_iterator(body))
def random_pubkey(): """ Generate a random public key. """ pk = int_to_big_endian(random.getrandbits(kademlia.k_pubkey_size)) return keys.PublicKey(b'\x00' * (kademlia.k_pubkey_size // 8 - len(pk)) + pk)
def set_balance(self, address, balance): validate_canonical_address(address, title="Storage Address") validate_uint256(balance, title="Account Balance") key = get_balance_key(address) self._check_accessibility(key) self._trie[key] = int_to_big_endian(balance)
def set_storage(self, address, slot, value): validate_uint256(value, title="Storage Value") validate_uint256(slot, title="Storage Slot") validate_canonical_address(address, title="Storage Address") key = get_storage_key(address, slot) self._check_accessibility(key) if value: self._trie[key] = int_to_big_endian(value) else: del self._trie[key]
def modexp(computation): """ https://github.com/ethereum/EIPs/pull/198 """ gas_fee = _compute_modexp_gas_fee(computation.msg.data) computation.gas_meter.consume_gas(gas_fee, reason='MODEXP Precompile') result = _modexp(computation.msg.data) _, _, modulus_length = _extract_lengths(computation.msg.data) result_bytes = zpad_left(int_to_big_endian(result), to_size=modulus_length) computation.output = result_bytes return computation
def get_storage(self, address, slot): validate_canonical_address(address) validate_uint256(slot) account = self._get_account(address) storage = StateTrie(Trie(self.db, account.storage_root)) slot_as_key = pad32(int_to_big_endian(slot)) if slot_as_key in storage: encoded_value = storage[slot_as_key] return rlp.decode(encoded_value, sedes=rlp.sedes.big_endian_int) else: return 0
def get_storage(self, address, slot): validate_canonical_address(address, title="Storage Address") validate_uint256(slot, title="Storage Slot") account = self._get_account(address) storage = HashTrie(HexaryTrie(self._journaldb, account.storage_root)) slot_as_key = pad32(int_to_big_endian(slot)) if slot_as_key in storage: encoded_value = storage[slot_as_key] return rlp.decode(encoded_value, sedes=rlp.sedes.big_endian_int) else: return 0
def modexp(computation): """ https://github.com/ethereum/EIPs/pull/198 """ gas_fee = _compute_modexp_gas_fee(computation.msg.data) computation.gas_meter.consume_gas(gas_fee, reason='MODEXP Precompile') result = _modexp(computation.msg.data) _, _, modulus_length = _extract_lengths(computation.msg.data) result_bytes = zpad_left(int_to_big_endian(result), to_size=modulus_length) computation.output = result_bytes return computation
def get_message_for_signing(self): if is_eip_155_signed_transaction(self): chain_id = extract_chain_id(self.v) txn_parts = rlp.decode(rlp.encode(self)) txn_parts_for_signing = txn_parts[:-3] + [int_to_big_endian(chain_id), b'', b''] return rlp.encode(txn_parts_for_signing) else: return rlp.encode(SpuriousDragonUnsignedTransaction( nonce=self.nonce, gas_price=self.gas_price, gas=self.gas, to=self.to, value=self.value, data=self.data, ))
def print_var(value, var_typ): if isinstance(value, int): v = int_to_big_endian(value) else: v = value if isinstance(v, bytes): if var_typ == 'uint256': print(big_endian_to_int(v)) elif var_typ == 'int128': print('TODO!') elif var_typ == 'address': print(to_hex(v[12:])) else: print(v)
def set_storage(self, address, slot, value): validate_uint256(value, title="Storage Value") validate_uint256(slot, title="Storage Slot") validate_canonical_address(address, title="Storage Address") account = self._get_account(address) storage = HashTrie(HexaryTrie(self._journaldb, account.storage_root)) slot_as_key = pad32(int_to_big_endian(slot)) if value: encoded_value = rlp.encode(value) storage[slot_as_key] = encoded_value else: del storage[slot_as_key] self._set_account(address, account.copy(storage_root=storage.root_hash))
def set_storage(self, address, slot, value): validate_uint256(value) validate_uint256(slot) validate_canonical_address(address) account = self._get_account(address) storage = StateTrie(Trie(self.db, account.storage_root)) slot_as_key = pad32(int_to_big_endian(slot)) if value: encoded_value = rlp.encode(value) storage[slot_as_key] = encoded_value else: del storage[slot_as_key] account.storage_root = storage.root_hash self._set_account(address, account)
def assemble_data_field(user_account_transaction, include_signature=True): if include_signature: signature = b"".join([ pad32(int_to_big_endian(user_account_transaction.v)), pad32(int_to_big_endian(user_account_transaction.r)), pad32(int_to_big_endian(user_account_transaction.s)), ]) else: signature = b"" return b''.join([ signature, pad32(int_to_big_endian(user_account_transaction.nonce)), pad32(int_to_big_endian(user_account_transaction.int_gas_price)), pad32(int_to_big_endian(user_account_transaction.value)), pad32(int_to_big_endian(user_account_transaction.min_block)), pad32(int_to_big_endian(user_account_transaction.max_block)), pad32(user_account_transaction.destination), user_account_transaction.msg_data, ])
def create_transaction_signature(unsigned_txn, private_key, chain_id=None): transaction_parts = rlp.decode(rlp.encode(unsigned_txn)) if chain_id: transaction_parts_for_signature = ( transaction_parts + [int_to_big_endian(chain_id), b'', b'']) else: transaction_parts_for_signature = transaction_parts message = rlp.encode(transaction_parts_for_signature) signature = private_key.sign_msg(message) canonical_v, r, s = signature.vrs if chain_id: v = canonical_v + chain_id * 2 + EIP155_CHAIN_ID_OFFSET else: v = canonical_v + V_OFFSET return v, r, s
def create_transaction_signature(unsigned_txn, private_key, chain_id=None): transaction_parts = rlp.decode(rlp.encode(unsigned_txn)) if chain_id: transaction_parts_for_signature = ( transaction_parts + [int_to_big_endian(chain_id), b'', b''] ) else: transaction_parts_for_signature = transaction_parts message = rlp.encode(transaction_parts_for_signature) signature = private_key.sign_msg(message) canonical_v, r, s = signature.vrs if chain_id: v = canonical_v + chain_id * 2 + EIP155_CHAIN_ID_OFFSET else: v = canonical_v + V_OFFSET return v, r, s
def _pop(self, num_items, type_hint): for _ in range(num_items): if type_hint == constants.UINT256: value = self.values.pop() if isinstance(value, int): yield value else: yield big_endian_to_int(value) elif type_hint == constants.BYTES: value = self.values.pop() if isinstance(value, bytes): yield value else: yield int_to_big_endian(value) elif type_hint == constants.ANY: yield self.values.pop() else: raise TypeError( "Unknown type_hint: {0}. Must be one of {1}".format( type_hint, ", ".join((constants.UINT256, constants.BYTES)), ))
def _pop(self, num_items, type_hint): for _ in range(num_items): if type_hint == constants.UINT256: value = self.values.pop() if isinstance(value, int): yield value else: yield big_endian_to_int(value) elif type_hint == constants.BYTES: value = self.values.pop() if isinstance(value, bytes): yield value else: yield int_to_big_endian(value) elif type_hint == constants.ANY: yield self.values.pop() else: raise TypeError( "Unknown type_hint: {0}. Must be one of {1}".format( type_hint, ", ".join((constants.UINT256, constants.BYTES)), ) )
def get_storage_key(address, slot): return keccak(address) + STORAGE_TRIE_PREFIX + pad32(int_to_big_endian(slot))
def send_find_node(self, node, target_node_id): target_node_id = int_to_big_endian(target_node_id).rjust( kademlia.k_pubkey_size // 8, b'\0') self.logger.debug('>>> find_node to {}'.format(node)) message = _pack(CMD_FIND_NODE.id, [target_node_id], self.privkey) self.send(node, message)
def send_find_node(self, node: kademlia.Node, target_node_id: int) -> None: node_id = int_to_big_endian( target_node_id).rjust(kademlia.k_pubkey_size // 8, b'\0') self.logger.debug('>>> find_node to %s', node) message = _pack(CMD_FIND_NODE.id, [node_id], self.privkey) self.send(node, message)
def generate_privkey(): """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)))