Ejemplo n.º 1
0
    async def getBlockCreationParams(self, chain_address):
        #create new chain for all requests
        chain = self.get_new_chain(chain_address)

        to_return = {}

        to_return['block_number'] = hex(chain.header.block_number)
        to_return['parent_hash'] = encode_hex(chain.header.parent_hash)

        vm = chain.get_vm(timestamp=int(time.time()))

        to_return['nonce'] = hex(vm.state.account_db.get_nonce(chain_address))

        receivable_transactions = chain.create_receivable_transactions()
        encoded_receivable_transactions = []

        for re_tx in receivable_transactions:
            encoded_receivable_transactions.append(
                encode_hex(rlp.encode(re_tx)))

        to_return['receive_transactions'] = encoded_receivable_transactions

        reward_bundle = chain.get_consensus_db(
        ).create_reward_bundle_for_block(chain_address)
        amount = reward_bundle.reward_type_1.amount + reward_bundle.reward_type_2.amount
        to_return['reward_bundle'] = encode_hex(
            rlp.encode(reward_bundle, sedes=StakeRewardBundle))

        return to_return
Ejemplo n.º 2
0
def test_peek():
    assert rlp.peek(rlp.encode(b''), []) == b''
    nested = rlp.encode([0, 1, [2, 3]])
    assert rlp.peek(nested, [2, 0], big_endian_int) == 2
    for index in [3, [3], [0, 0], [2, 2], [2, 1, 0]]:
        with pytest.raises(IndexError):
            rlp.peek(nested, index)
    assert rlp.peek(nested, 2, CountableList(big_endian_int)) == (2, 3)
Ejemplo n.º 3
0
 def micro_header_hash(self) -> Hash32:
     if self._micro_header_hash is None:
         header_parts = rlp.decode(rlp.encode(self), use_list=True)
         header_parts_for_hash = (
                 header_parts[:4] + [header_parts[6]] + header_parts[9:12] + header_parts[-3:]
         )
         self._micro_header_hash = keccak(rlp.encode(header_parts_for_hash))
     return self._micro_header_hash
Ejemplo n.º 4
0
    def get_message_for_signing(self, chain_id: int = None) -> bytes:
        if chain_id is None:
            chain_id = self.chain_id

        transaction_parts = rlp.decode(rlp.encode(self), use_list=True)

        transaction_parts_for_signature = transaction_parts[:-3] + [int_to_big_endian(chain_id), b'', b'']

        message = rlp.encode(transaction_parts_for_signature)
        return message
def test_list_of_serializable_decoding_rlp_caching(rlp_obj):
    rlp_obj_code = encode(rlp_obj, cache=False)
    L = [rlp_obj, rlp_obj]
    list_code = encode(L, cache=False)

    L2 = decode(list_code,
                sedes=List((type(rlp_obj), type(rlp_obj))),
                recursive_cache=True)
    assert L2[0]._cached_rlp == rlp_obj_code
    assert L2[1]._cached_rlp == rlp_obj_code
Ejemplo n.º 6
0
def test_compare_length():
    data = encode([1, 2, 3, 4, 5])
    assert compare_length(data, 100) == -1
    assert compare_length(data, 5) == 0
    assert compare_length(data, 1) == 1

    data = encode([])
    assert compare_length(data, 100) == -1
    assert compare_length(data, 0) == 0
    assert compare_length(data, -1) == 1
Ejemplo n.º 7
0
 def set_availability(self, chunk_root: Hash32,
                      availability: Availability) -> None:
     key = make_collation_availability_lookup_key(chunk_root)
     if availability is Availability.AVAILABLE:
         self.db.set(key, rlp.encode(1))
     elif availability is Availability.UNAVAILABLE:
         self.db.set(key, rlp.encode(0))
     elif availability is Availability.UNKNOWN:
         if self.db.exists(key):
             self.db.delete(key)
Ejemplo n.º 8
0
def test_string(value):
    def dec():
        return rlp.decode_lazy(rlp.encode(value))

    assert isinstance(dec(), bytes)
    assert len(dec()) == len(value)
    assert dec() == value
    assert rlp.peek(rlp.encode(value), []) == value
    with pytest.raises(IndexError):
        rlp.peek(rlp.encode(value), 0)
    with pytest.raises(IndexError):
        rlp.peek(rlp.encode(value), [0])
Ejemplo n.º 9
0
    def get_message_for_signing(self, chain_id: int = None) -> bytes:
        if chain_id is None:
            chain_id = self.chain_id

        header_parts = rlp.decode(rlp.encode(self, sedes=self.__class__), use_list=True)
        header_parts_for_signature = (
                header_parts[:4] + [header_parts[6]] + header_parts[9:12] + [
            int_to_big_endian(chain_id), b'', b'']
        )
        # header_parts_for_signature = (
        #         header_parts[:3] + [header_parts[5]] + header_parts[8:11] + [header_parts[12]] + [header_parts[13]] + [
        #     int_to_big_endian(chain_id), b'', b'']
        # )
        message = rlp.encode(header_parts_for_signature)
        return message
Ejemplo n.º 10
0
 def set_current_syncing_info(self, timestamp: Timestamp,
                              head_root_hash: Hash32) -> None:
     validate_is_bytes(head_root_hash, title='Head Root Hash')
     validate_uint256(timestamp, title='timestamp')
     encoded = rlp.encode([timestamp, head_root_hash],
                          sedes=CurrentSyncingInfo)
     self.db[SchemaV1.make_current_syncing_info_lookup_key()] = encoded
Ejemplo n.º 11
0
def block_to_dict(block: BaseBlock, include_transactions: bool,
                  chain: AsyncChain) -> Dict[str, Union[str, List[str]]]:

    header_dict = header_to_dict(block.header)

    block_dict: Dict[str, Union[str, List[str]]] = dict(
        header_dict,
        size=hex(len(rlp.encode(block))),
    )

    if include_transactions:
        block_dict['transactions'] = transactions_to_dict(
            block.transactions, chain)
        block_dict['receiveTransactions'] = receive_transactions_to_dict(
            block.receive_transactions, chain)
        block_dict['rewardBundle'] = reward_bundle_to_dict(block.reward_bundle)
    else:
        block_dict['transactions'] = [
            encode_hex(tx.hash) for tx in block.transactions
        ]
        block_dict['receiveTransactions'] = [
            encode_hex(tx.hash) for tx in block.receive_transactions
        ]
        block_dict['rewardBundle'] = reward_bundle_to_dict(block.reward_bundle)
    return block_dict
Ejemplo n.º 12
0
def test_encode(name, in_out):
    msg_format = 'Test {} failed (encoded {} to {} instead of {})'
    data = in_out['in']
    result = encode_hex(encode(data)).lower()
    expected = in_out['out'].lower()
    if result != expected:
        pytest.fail(msg_format.format(name, data, result, expected))
Ejemplo n.º 13
0
def test_evaluation_of_lazy_decode_with_list_sedes_and_invalid_value():
    sedes = CountableList(big_endian_int)
    value = [(), (1, 2), b'asdf', (3)]
    invalid_lazy = rlp.decode_lazy(rlp.encode(value), sedes)
    assert invalid_lazy[0] == value[0]
    assert invalid_lazy[1] == value[1]
    with pytest.raises(DeserializationError):
        invalid_lazy[2]
Ejemplo n.º 14
0
def _make_trie_root_and_nodes(
        items: Tuple[bytes, ...]) -> Tuple[bytes, Dict[bytes, bytes]]:
    kv_store = {}  # type: Dict[bytes, bytes]
    trie = HexaryTrie(kv_store, BLANK_ROOT_HASH)
    for index, item in enumerate(items):
        index_key = rlp.encode(index, sedes=rlp.sedes.big_endian_int)
        trie[index_key] = item
    return trie.root_hash, kv_store
Ejemplo n.º 15
0
 def get_message_for_signing(self):
     if is_eip_155_signed_transaction(self):
         txn_parts = rlp.decode(rlp.encode(self))
         txn_parts_for_signing = txn_parts[:-3] + [
             int_to_big_endian(self.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,
             ))
Ejemplo n.º 16
0
    def _remove_address_from_smart_contracts_with_pending_transactions(self, address: Address) -> None:
        key = SchemaV1.make_smart_contracts_with_pending_transactions_lookup_key()

        address_set = set(self.get_smart_contracts_with_pending_transactions())

        address_set.remove(address)

        self.db[key] = rlp.encode(list(address_set), sedes=rlp.sedes.FCountableList(address))
Ejemplo n.º 17
0
 def get_account_hash(self, address: Address) -> Hash32:
     account = self._get_account(address)
     account_hashable = account.copy(
         receivable_transactions = (),
         block_conflicts = (),
     )
     account_hashable_encoded = rlp.encode(account_hashable, sedes=Account)
     return keccak(account_hashable_encoded)
Ejemplo n.º 18
0
 def save_now_as_last_min_gas_price_PID_update(self) -> None:
     now = int(time.time())
     lookup_key = SchemaV1.make_min_gas_system_last_pid_time_key()
     encoded_data = rlp.encode(now, sedes=rlp.sedes.f_big_endian_int)
     self.db.set(
         lookup_key,
         encoded_data,
     )
Ejemplo n.º 19
0
 def save_current_account_with_hash_lookup(self, wallet_address):
     validate_canonical_address(wallet_address, title="Address")
     account_hash = self.get_account_hash(wallet_address)
     account = self._get_account(wallet_address)
     rlp_account = rlp.encode(account, sedes=Account)
     
     lookup_key = SchemaV1.make_account_by_hash_lookup_key(account_hash)
     self.db[lookup_key] = rlp_account
Ejemplo n.º 20
0
def hash_log_entries(log_entries):
    """
    Helper function for computing the RLP hash of the logs from transaction
    execution.
    """
    logs = [Log(*entry) for entry in log_entries]
    encoded_logs = rlp.encode(logs)
    logs_hash = keccak(encoded_logs)
    return logs_hash
Ejemplo n.º 21
0
def make_binary_trie_root(items: Tuple[bytes, ...]) -> bytes:
    kv_store = {}  # type: Dict[bytes, bytes]
    trie = BinaryTrie(kv_store, BLANK_HASH)

    for index, item in enumerate(items):
        index_key = rlp.encode(index, sedes=rlp.sedes.big_endian_int)
        trie[index_key] = item

    return trie.root_hash
Ejemplo n.º 22
0
    def _set_peer_node_health(self, peer_wallet_address: Address,
                              after_block_number: BlockNumber,
                              peer_node_health: PeerNodeHealth) -> None:
        encoded_peer_node_health = rlp.encode(peer_node_health,
                                              sedes=PeerNodeHealth)
        key = SchemaV1.make_peer_node_health_lookup(peer_wallet_address,
                                                    after_block_number)

        self.db[key] = encoded_peer_node_health
def test_serializable_encoding_rlp_caching(rlp_obj):
    assert rlp_obj._cached_rlp is None

    # obj should start out without a cache
    rlp_code = encode(rlp_obj, cache=False)
    assert rlp_obj._cached_rlp is None

    # cache should be populated now.
    assert encode(rlp_obj, cache=True) == rlp_code
    assert rlp_obj._cached_rlp == rlp_code

    # cache should still be populated and encoding should used cached_rlp value
    rlp_obj._cached_rlp = b'test-uses-cache'
    assert encode(rlp_obj, cache=True) == b'test-uses-cache'

    obj_decoded = decode(rlp_code, sedes=rlp_obj.__class__)
    assert obj_decoded == rlp_obj
    assert obj_decoded._cached_rlp == rlp_code
Ejemplo n.º 24
0
 def get_message_for_signing(self):
     return rlp.encode(
         HomesteadUnsignedTransaction(
             nonce=self.nonce,
             gas_price=self.gas_price,
             gas=self.gas,
             to=self.to,
             value=self.value,
             data=self.data,
         ))
Ejemplo n.º 25
0
def extract_wallet_verification_sender(salt, v, r, s) -> bytes:
    vrs = (v, r, s)
    signature = keys.Signature(vrs=vrs)

    parts_for_sig = salt
    message = rlp.encode(parts_for_sig)

    public_key = signature.recover_public_key_from_msg(message)
    sender = public_key.to_canonical_address()
    return sender
Ejemplo n.º 26
0
 def create_auth_ack_message(self, nonce: bytes) -> bytes:
     if self.use_eip8:
         data = rlp.encode((self.ephemeral_pubkey.to_bytes(), nonce,
                            SUPPORTED_RLPX_VERSION),
                           sedes=eip8_ack_sedes)
         msg = _pad_eip8_data(data)
     else:
         # Unused, according to EIP-8, but must be included nevertheless.
         token_flag = b'\x00'
         msg = self.ephemeral_pubkey.to_bytes() + nonce + token_flag
     return msg
Ejemplo n.º 27
0
 def _add_block_number_to_hash_lookup(self, header: BlockHeader) -> None:
     """
     Sets a record in the database to allow looking up this header by its
     block number.
     """
     block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(
         header.block_number)
     self.db.set(
         block_number_to_hash_key,
         rlp.encode(header.hash, sedes=rlp.sedes.binary),
     )
Ejemplo n.º 28
0
 def save_chronological_block_window(self, data, timestamp):
     validate_uint256(timestamp, title='timestamp')
     if timestamp % TIME_BETWEEN_HEAD_HASH_SAVE != 0:
         raise InvalidHeadRootTimestamp("Can only save or load chronological block for timestamps in increments of {} seconds.".format(TIME_BETWEEN_HEAD_HASH_SAVE))
     
     chronological_window_lookup_key = SchemaV1.make_chronological_window_lookup_key(timestamp)
     encoded_data = rlp.encode(data,sedes=rlp.sedes.FCountableList(rlp.sedes.FList([f_big_endian_int, hash32])))
     self.db.set(
         chronological_window_lookup_key,
         encoded_data,
     )
def test_deserialization_for_custom_init_method():
    type_3 = RLPType3(2, 1, 3)
    assert type_3.field1 == 1
    assert type_3.field2 == 2
    assert type_3.field3 == 3

    result = decode(encode(type_3), sedes=RLPType3)

    assert result.field1 == 1
    assert result.field2 == 2
    assert result.field3 == 3
Ejemplo n.º 30
0
    def persist_header(self, header: BlockHeader) -> Tuple[BlockHeader, ...]:
        """
        :returns: iterable of headers newly on the canonical chain
        """
        if header.parent_hash != GENESIS_PARENT_HASH:
            try:
                self.get_block_header_by_hash(header.parent_hash)
            except HeaderNotFound:
                raise ParentNotFound(
                    "Cannot persist block header ({}) with unknown parent ({})"
                    .format(encode_hex(header.hash),
                            encode_hex(header.parent_hash)))

        self.db.set(
            header.hash,
            rlp.encode(header),
        )

        if header.parent_hash == GENESIS_PARENT_HASH:
            score = header.difficulty
        else:
            score = self.get_score(header.parent_hash) + header.difficulty

        self.db.set(
            SchemaV1.make_block_hash_to_score_lookup_key(header.hash),
            rlp.encode(score, sedes=rlp.sedes.big_endian_int),
        )

        try:
            head_score = self.get_score(self.get_canonical_head().hash)
        except CanonicalHeadNotFound:
            new_canonical_headers = self._set_as_canonical_chain_head(
                header.hash)
        else:
            if score > head_score:
                new_canonical_headers = self._set_as_canonical_chain_head(
                    header.hash)
            else:
                new_canonical_headers = tuple()

        return new_canonical_headers