本文整理汇总了Python中rlp.decode方法的典型用法代码示例。如果您正苦于以下问题:Python rlp.decode方法的具体用法?Python rlp.decode怎么用?Python rlp.decode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rlp
的用法示例。
在下文中一共展示了rlp.decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _unpack_v4
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def _unpack_v4(
message: bytes
) -> Tuple[datatypes.PublicKey, int, Tuple[Any, ...], Hash32]:
"""Unpack a discovery v4 UDP message received from a remote node.
Returns the public key used to sign the message, the cmd ID, payload and hash.
"""
message_hash = message[:MAC_SIZE]
if message_hash != keccak(message[MAC_SIZE:]):
raise WrongMAC("Wrong msg mac")
signature = keys.Signature(message[MAC_SIZE:HEAD_SIZE])
signed_data = message[HEAD_SIZE:]
remote_pubkey = signature.recover_public_key_from_msg(signed_data)
cmd_id = message[HEAD_SIZE]
cmd = CMD_ID_MAP[cmd_id]
payload = tuple(rlp.decode(message[HEAD_SIZE + 1 :], strict=False))
# Ignore excessive list elements as required by EIP-8.
payload = payload[: cmd.elem_count]
return remote_pubkey, cmd_id, payload, message_hash
示例2: _unpack_v5
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def _unpack_v5(
message: bytes, V5_ID_STRING, HEAD_SIZE_V5
) -> Tuple[datatypes.PublicKey, int, Tuple[Any, ...], Hash32]:
"""Unpack a discovery v5 UDP message received from a remote node.
Returns the public key used to sign the message, the cmd ID, payload and msg hash.
"""
if not message.startswith(V5_ID_STRING):
raise DefectiveMessage("Missing v5 version prefix")
message_hash = keccak(message[len(V5_ID_STRING) :])
signature = keys.Signature(message[len(V5_ID_STRING) : HEAD_SIZE_V5])
body = message[HEAD_SIZE_V5:]
remote_pubkey = signature.recover_public_key_from_msg(body)
cmd_id = body[0]
cmd = CMD_ID_MAP_V5[cmd_id]
payload = tuple(rlp.decode(body[1:], strict=False))
# Ignore excessive list elements as required by EIP-8.
payload = payload[: cmd.elem_count]
return remote_pubkey, cmd_id, payload, message_hash
示例3: decode_payload
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def decode_payload(self, rlp_data: bytes) -> PayloadType:
if isinstance(self.structure, sedes.CountableList):
decoder = self.structure
else:
decoder = sedes.List(
[type_ for _, type_ in self.structure], strict=self.decode_strict
)
try:
data = rlp.decode(rlp_data, sedes=decoder, recursive_cache=True)
except rlp.DecodingError as err:
raise MalformedMessage(
"Malformed {} message: {}".format(type(self).__name__, repr(err))
) from err
if isinstance(self.structure, sedes.CountableList):
return data
return {
field_name: value
for ((field_name, _), value) in zip(self.structure, data)
}
示例4: to_dict
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def to_dict(self):
if not self.token_trie:
return self._balances
# Iterating trie is costly. It's only for JSONRPC querying account information, which
# can be improved later
trie_dict = self.token_trie.to_dict()
ret = {
utils.big_endian_to_int(k): utils.big_endian_to_int(rlp.decode(v))
for k, v in trie_dict.items()
}
# Get latest update
for k, v in self._balances.items():
if v == 0:
ret.pop(k, None)
else:
ret[k] = v
return ret
示例5: inc_refcount
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def inc_refcount(self, k, v):
# raise Exception("WHY AM I CHANGING A REFCOUNT?!:?")
try:
node_object = rlp.decode(self._keyValueStorage.get(b'r:' + k))
refcount = utils.decode_int(node_object[0])
self.journal.append([node_object[0], k])
if refcount >= DEATH_ROW_OFFSET:
refcount = 0
new_refcount = utils.encode_int(refcount + 1)
self._keyValueStorage.put(b'r:' + k, rlp.encode([new_refcount, v]))
if self.logging:
sys.stderr.write('increasing %s %r to: %d\n' % (
utils.encode_hex(k), v, refcount + 1))
except BaseException:
self._keyValueStorage.put(b'r:' + k, rlp.encode([ONE_ENCODED, v]))
self.journal.append([ZERO_ENCODED, k])
if self.logging:
sys.stderr.write('increasing %s %r to: %d\n' % (
utils.encode_hex(k), v, 1))
示例6: dec_refcount
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def dec_refcount(self, k):
# raise Exception("WHY AM I CHANGING A REFCOUNT?!:?")
node_object = rlp.decode(self._keyValueStorage.get(b'r:' + k))
refcount = utils.decode_int(node_object[0])
if self.logging:
sys.stderr.write('decreasing %s to: %d\n' % (
utils.encode_hex(k), refcount - 1))
if not refcount > 0:
raise ValueError(
"node object for key {} has {} number "
"of references, expected > 0"
.format(k, refcount)
)
self.journal.append([node_object[0], k])
new_refcount = utils.encode_int(refcount - 1)
self._keyValueStorage.put(
b'r:' + k, rlp.encode([new_refcount, node_object[1]]))
if new_refcount == ZERO_ENCODED:
self.death_row.append(k)
示例7: revert_refcount_changes
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def revert_refcount_changes(self, epoch):
timeout_epoch = epoch + self.ttl
# Delete death row additions
try:
self._keyValueStorage.remove('deathrow:' + str(timeout_epoch))
except BaseException:
pass
# Revert journal changes
try:
journal = rlp.decode(
self._keyValueStorage.get('journal:' + str(epoch)))
for new_refcount, hashkey in journal[::-1]:
node_object = rlp.decode(
self._keyValueStorage.get(b'r:' + hashkey))
k = b'r:' + hashkey
v = rlp.encode([new_refcount, node_object[1]])
self._keyValueStorage.put(k, v)
except BaseException:
pass
示例8: decode
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def decode(self, data=''):
if data:
self._decode_buffer.extend(data)
if not self._cached_decode_header:
if len(self._decode_buffer) < Frame.header_size + Frame.mac_size:
return []
else:
self._cached_decode_header = self.decode_header(memoryview(self._decode_buffer))
assert isinstance(self._cached_decode_header, str)
body_size = struct.unpack('>I', '\x00' + self._cached_decode_header[:3])[0]
required_len = Frame.header_size + Frame.mac_size + ceil16(body_size) + Frame.mac_size
if len(self._decode_buffer) >= required_len:
packet = self.decode_body(memoryview(self._decode_buffer), self._cached_decode_header)
self._cached_decode_header = None
self._decode_buffer = self._decode_buffer[required_len:]
if packet:
return [packet] + self.decode()
else:
return self.decode()
return []
示例9: unpack
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def unpack(self, message):
"""
macSize = 256 / 8 = 32
sigSize = 520 / 8 = 65
headSize = macSize + sigSize = 97
hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
shouldhash := crypto.Sha3(buf[macSize:])
"""
mdc = message[:32]
assert mdc == crypto.sha3(message[32:])
signature = message[32:97]
assert len(signature) == 65
signed_data = crypto.sha3(message[97:])
remote_pubkey = crypto.ecdsa_recover(signed_data, signature)
assert len(remote_pubkey) == 512 / 8
if not crypto.verify(remote_pubkey, signature, signed_data):
raise InvalidSignature()
cmd_id = self.decoders['cmd_id'](message[97])
assert cmd_id in self.cmd_id_map.values()
payload = rlp.decode(message[98:])
assert isinstance(payload, list)
expiration = self.decoders['expiration'](payload.pop())
if time.time() > expiration:
raise PacketExpired()
return remote_pubkey, cmd_id, payload, mdc
示例10: decode_payload
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def decode_payload(cls, rlp_data):
log.debug('decoding rlp', size=len(rlp_data))
if isinstance(cls.structure, sedes.CountableList):
decoder = cls.structure
else:
decoder = sedes.List([x[1] for x in cls.structure])
try:
data = rlp.decode(str(rlp_data), sedes=decoder)
except (AssertionError, rlp.RLPException, TypeError) as e:
print repr(rlp.decode(rlp_data))
raise e
if isinstance(cls.structure, sedes.CountableList):
return data
else: # convert to dict
return dict((cls.structure[i][0], v) for i, v in enumerate(data))
# end command base ###################################################
示例11: get_transaction_by_index
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def get_transaction_by_index(
self,
block_number: BlockNumber,
transaction_index: int,
transaction_class: Type[SignedTransactionAPI]) -> SignedTransactionAPI:
try:
block_header = self.get_canonical_block_header_by_number(block_number)
except HeaderNotFound:
raise TransactionNotFound(f"Block {block_number} is not in the canonical chain")
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
encoded_index = rlp.encode(transaction_index)
encoded_transaction = transaction_db[encoded_index]
if encoded_transaction != b'':
return rlp.decode(encoded_transaction, sedes=transaction_class)
else:
raise TransactionNotFound(
f"No transaction is at index {transaction_index} of block {block_number}"
)
示例12: apply_fixture_block_to_chain
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def apply_fixture_block_to_chain(
block_fixture: Dict[str, Any],
chain: ChainAPI,
perform_validation: bool=True) -> Tuple[BlockAPI, BlockAPI, BlockAPI]:
"""
:return: (premined_block, mined_block, rlp_encoded_mined_block)
"""
# The block to import may be in a different block-class-range than the
# chain's current one, so we use the block number specified in the
# fixture to look up the correct block class.
if 'blockHeader' in block_fixture:
block_number = block_fixture['blockHeader']['number']
block_class = chain.get_vm_class_for_block_number(block_number).get_block_class()
else:
block_class = chain.get_vm().get_block_class()
block = rlp.decode(block_fixture['rlp'], sedes=block_class)
import_result = chain.import_block(block, perform_validation=perform_validation)
mined_block = import_result.imported_block
rlp_encoded_mined_block = rlp.encode(mined_block, sedes=block_class)
return (block, mined_block, rlp_encoded_mined_block)
示例13: create_transaction_signature
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def create_transaction_signature(unsigned_txn: BaseTransaction,
private_key: datatypes.PrivateKey,
chain_id: int=None) -> VRS:
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 VRS((v, r, s))
示例14: test_chaindb_get_score
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def test_chaindb_get_score(chaindb):
genesis = BlockHeader(difficulty=1, block_number=0, gas_limit=0)
chaindb.persist_header(genesis)
genesis_score_key = SchemaV1.make_block_hash_to_score_lookup_key(genesis.hash)
genesis_score = rlp.decode(chaindb.db.get(genesis_score_key), sedes=rlp.sedes.big_endian_int)
assert genesis_score == 1
assert chaindb.get_score(genesis.hash) == 1
block1 = BlockHeader(difficulty=10, block_number=1, gas_limit=0, parent_hash=genesis.hash)
chaindb.persist_header(block1)
block1_score_key = SchemaV1.make_block_hash_to_score_lookup_key(block1.hash)
block1_score = rlp.decode(chaindb.db.get(block1_score_key), sedes=rlp.sedes.big_endian_int)
assert block1_score == 11
assert chaindb.get_score(block1.hash) == 11
示例15: _check_transaction
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import decode [as 别名]
def _check_transaction(self, transaction, unsigned):
"""
Checks a single (external) transaction against its expected unsigned (local) counterpart
"""
decoded = rlp.decode(self.web3.toAscii(transaction['signedRaw']), Transaction)
decoded_tx = dict(
nonce=self.web3.toHex(decoded.nonce),
gasPrice=self.web3.toHex(decoded.gasprice),
gas=self.web3.toHex(decoded.startgas),
to=self.web3.toHex(decoded.to),
value=self.web3.toHex(decoded.value),
data=self.web3.toHex(decoded.data)
)
unsigned['tx'].pop('from')
if unsigned['tx'] != decoded_tx:
logging.error("mismatch! signed tx: {}, local tx: {}".format(decoded_tx, unsigned['tx']))
raise AirdropException("transaction mismatch for {}".format(unsigned['tx']['nonce']))