本文整理汇总了Python中rlp.encode方法的典型用法代码示例。如果您正苦于以下问题:Python rlp.encode方法的具体用法?Python rlp.encode怎么用?Python rlp.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rlp
的用法示例。
在下文中一共展示了rlp.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_auth_message
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def create_auth_message(self, nonce: bytes) -> bytes:
ecdh_shared_secret = ecies.ecdh_agree(self.privkey, self.remote.pubkey)
secret_xor_nonce = sxor(ecdh_shared_secret, nonce)
S = self.ephemeral_privkey.sign_msg_hash(secret_xor_nonce).to_bytes()
if self.use_eip8:
data = rlp.encode(
[S, self.pubkey.to_bytes(), nonce, SUPPORTED_RLPX_VERSION],
sedes=eip8_auth_sedes,
)
return _pad_eip8_data(data)
else:
# S || H(ephemeral-pubk) || pubk || nonce || 0x0
return (
S
+ keccak(self.ephemeral_pubkey.to_bytes())
+ self.pubkey.to_bytes()
+ nonce
+ b"\x00"
)
示例2: test_ping_pong_v5
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def test_ping_pong_v5():
alice = get_discovery_protocol(b"alice")
bob = get_discovery_protocol(b"bob")
# Connect alice's and bob's transports directly so we don't need to deal with the complexities
# of going over the wire.
link_transports(alice, bob)
# Collect all pongs received by alice in a list for later inspection.
received_pongs = []
alice.recv_pong_v5 = lambda node, payload, hash_, _: received_pongs.append(
(node, payload)
)
topics = [b"foo", b"bar"]
token = alice.send_ping_v5(bob.this_node, topics)
assert len(received_pongs) == 1
node, payload = received_pongs[0]
_, reply_token, _, topic_hash, _, _ = payload
assert node.id == bob.this_node.id
assert token == reply_token
assert topic_hash == keccak(rlp.encode(topics))
示例3: recv_ping_v5
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def recv_ping_v5(
self,
node: kademlia.Node,
payload: Tuple[Any, ...],
message_hash: Hash32,
_: bytes,
) -> None:
# version, from, to, expiration, topics
_, _, _, _, topics = payload
self.logger.trace("<<< ping(v5) from %s, topics: %s", node, topics)
self.process_ping(node, message_hash)
topic_hash = keccak(rlp.encode(topics))
ticket_serial = self.topic_table.issue_ticket(node)
# TODO: Generate wait_periods list according to spec.
wait_periods = [60] * len(topics) # : List[int]
self.send_pong_v5(node, message_hash, topic_hash, ticket_serial, wait_periods)
示例4: _get_max_neighbours_per_packet
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def _get_max_neighbours_per_packet() -> int:
# As defined in https://github.com/ethereum/devp2p/blob/master/rlpx.md, the max size of a
# datagram must be 1280 bytes, so when sending neighbours packets we must include up to
# _max_neighbours_per_packet and if there's more than that split them across multiple
# packets.
# Use an IPv6 address here as we're interested in the size of the biggest possible node
# representation.
addr = kademlia.Address("::1", 30303, 30303)
node_data = addr.to_endpoint() + [b"\x00" * (kademlia.k_pubkey_size // 8)]
neighbours = [node_data]
expiration = rlp.sedes.big_endian_int.serialize(_get_msg_expiration())
payload = rlp.encode([neighbours] + [expiration])
while HEAD_SIZE + len(payload) <= 1280:
neighbours.append(node_data)
payload = rlp.encode([neighbours] + [expiration])
return len(neighbours) - 1
示例5: encode_payload
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def encode_payload(self, data: Union[PayloadType, sedes.CountableList]) -> bytes:
if isinstance(data, dict): # convert dict to ordered list
if not isinstance(self.structure, list):
raise ValueError("Command.structure must be a list when data is a dict")
expected_keys = sorted(name for name, _ in self.structure)
data_keys = sorted(data.keys())
if data_keys != expected_keys:
raise ValueError(
"Keys in data dict ({}) do not match expected keys ({})".format(data_keys, expected_keys)
)
data = [data[name] for name, _ in self.structure]
if isinstance(self.structure, sedes.CountableList):
encoder = self.structure
else:
encoder = sedes.List([type_ for _, type_ in self.structure])
return rlp.encode(data, sedes=encoder)
示例6: encode
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def encode(self, data: PayloadType) -> Tuple[bytes, bytes]:
payload = self.encode_payload(data)
enc_cmd_id = rlp.encode(self.cmd_id, sedes=rlp.sedes.big_endian_int)
frame_size = len(enc_cmd_id) + len(payload)
if frame_size.bit_length() > 24:
raise ValueError("Frame size has to fit in a 3-byte integer")
# Drop the first byte as, per the spec, frame_size must be a 3-byte int.
header = struct.pack(">I", frame_size)[1:]
# All clients seem to ignore frame header data, so we do the same, although I'm not sure
# why geth uses the following value:
# https://github.com/ethereum/go-ethereum/blob/master/p2p/rlpx.go#L556
zero_header = b"\xc2\x80\x80"
header += zero_header
header = _pad_to_16_byte_boundary(header)
body = _pad_to_16_byte_boundary(enc_cmd_id + payload)
return header, body
示例7: serialize
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def serialize(self):
# Make sure is committed
check(self._not_using_trie or (self.token_trie and self._balances == {}))
# Return trie hash if possible
if self.token_trie:
return b"\x01" + self.token_trie.root_hash
# Serialize in-memory balance representation as an array
if len(self._balances) == 0:
return b""
# Don't serialize 0 balance
ls = [TokenBalancePair(k, v) for k, v in self._balances.items() if v > 0]
# Sort by token id to make token balances serialization deterministic
ls.sort(key=lambda b: b.token_id)
return b"\x00" + rlp.encode(ls)
示例8: to_dict
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def to_dict(self):
odict = self.storage_trie.to_dict()
for k, v in self.storage_cache.items():
odict[utils.encode_int(k)] = rlp.encode(utils.encode_int(v))
return {
"token_balances": self.token_balances.to_dict(),
"nonce": str(self.nonce),
"code": "0x" + encode_hex(self.code),
"storage": {
"0x"
+ encode_hex(key.lstrip(b"\x00") or b"\x00"): "0x"
+ encode_hex(rlp.decode(val))
for key, val in odict.items()
},
}
# from ethereum.state import State
示例9: inc_refcount
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [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))
示例10: dec_refcount
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [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)
示例11: revert_refcount_changes
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [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
示例12: main
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def main():
import time
import state.trie.pruning_trie as trie
def run():
st = time.time()
x = trie.Trie(KeyValueStorageInMemory())
for i in range(10000):
x.update(str(i), str(i**3))
print('elapsed', time.time() - st)
return x.root_hash
trie.rlp_encode = _encode_optimized
print('trie.rlp_encode = encode_optimized')
r3 = run()
trie.rlp_encode = rlp.codec.encode_raw
print('trie.rlp_encode = rlp.codec.encode_raw')
r2 = run()
assert r2 == r3
trie.rlp_encode = rlp.encode
print('trie.rlp_encode = rlp.encode')
r = run()
assert r == r2
示例13: submitWork
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def submitWork(self, nonce, mining_hash, mix_digest):
print 'submitting work'
h = self.chain.chain.head_candidate
print 'header: %s' % encode_hex(rlp.encode(h))
if h.header.mining_hash != mining_hash:
return False
print 'mining hash: %s' % encode_hex(mining_hash)
print 'nonce: %s' % encode_hex(nonce)
print 'mixhash: %s' % encode_hex(mix_digest)
print 'seed: %s' % encode_hex(h.header.seed)
h.header.nonce = nonce
h.header.mixhash = mix_digest
if not h.header.check_pow():
print 'PoW check false'
return False
print 'PoW check true'
self.chain.chain.add_block(h)
self.chain.broadcast_newblock(h)
print 'Added: %d' % h.header.number
return True
示例14: _get_block_before_tx
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def _get_block_before_tx(self, txhash):
tx, blk, i = self.app.services.chain.chain.index.get_transaction(txhash)
# get the state we had before this transaction
test_blk = ethereum.blocks.Block.init_from_parent(blk.get_parent(),
blk.coinbase,
extra_data=blk.extra_data,
timestamp=blk.timestamp,
uncles=blk.uncles)
pre_state = test_blk.state_root
for i in range(blk.transaction_count):
tx_lst_serialized, sr, _ = blk.get_transaction(i)
if sha3(rlp.encode(tx_lst_serialized)) == tx.hash:
break
else:
pre_state = sr
test_blk.state.root_hash = pre_state
return test_blk, tx, i
示例15: on_receive_status
# 需要导入模块: import rlp [as 别名]
# 或者: from rlp import encode [as 别名]
def on_receive_status(self, proto, eth_version, network_id, chain_difficulty, chain_head_hash,
genesis_hash):
log.debug('status received', proto=proto, eth_version=eth_version)
assert eth_version == proto.version, (eth_version, proto.version)
if network_id != self.config['eth'].get('network_id', proto.network_id):
log.warn("invalid network id", remote_network_id=network_id,
expected_network_id=self.config['eth'].get('network_id', proto.network_id))
raise eth_protocol.ETHProtocolError('wrong network_id')
# check genesis
if genesis_hash != self.chain.genesis.hash:
log.warn("invalid genesis hash", remote_id=proto, genesis=genesis_hash.encode('hex'))
raise eth_protocol.ETHProtocolError('wrong genesis block')
# request chain
self.synchronizer.receive_status(proto, chain_head_hash, chain_difficulty)
# send transactions
transactions = self.chain.get_transactions()
if transactions:
log.debug("sending transactions", remote_id=proto)
proto.send_transactions(*transactions)
# transactions