本文整理汇总了Python中utils.sha3函数的典型用法代码示例。如果您正苦于以下问题:Python sha3函数的具体用法?Python sha3怎么用?Python sha3使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sha3函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate_uncles
def validate_uncles(self):
if utils.sha3(rlp.encode(self.uncles)) != self.uncles_hash:
return False
# Check uncle validity
ancestor_chain = [self]
# Uncle can have a block from 2-7 blocks ago as its parent
for i in [1, 2, 3, 4, 5, 6, 7]:
if ancestor_chain[-1].number > 0:
ancestor_chain.append(ancestor_chain[-1].get_parent())
ineligible = []
# Uncles of this block cannot be direct ancestors and cannot also
# be uncles included 1-6 blocks ago
for ancestor in ancestor_chain[1:]:
ineligible.extend(ancestor.uncles)
ineligible.extend([b.list_header() for b in ancestor_chain])
eligible_ancestor_hashes = [x.hash for x in ancestor_chain[2:]]
for uncle in self.uncles:
if not check_header_pow(uncle):
return False
# uncle's parent cannot be the block's own parent
prevhash = uncle[block_structure_rev['prevhash'][0]]
if prevhash not in eligible_ancestor_hashes:
logger.debug("%r: Uncle does not have a valid ancestor", self)
return False
if uncle in ineligible:
logger.debug("%r: Duplicate uncle %r", self, utils.sha3(rlp.encode(uncle)).encode('hex'))
return False
ineligible.append(uncle)
return True
示例2: to_dict
def to_dict(self, with_state=False, full_transactions=False,
with_storage_roots=False, with_uncles=False):
"""
serializes the block
with_state: include state for all accounts
full_transactions: include serialized tx (hashes otherwise)
with_uncles: include uncle hashes
"""
b = {}
for name, typ, default in block_structure:
b[name] = utils.printers[typ](getattr(self, name))
txlist = []
for i in range(self.transaction_count):
tx_rlp = self.transactions.get(rlp.encode(utils.encode_int(i)))
tx, msr, gas = rlp.decode(tx_rlp)
if full_transactions:
txjson = transactions.Transaction.create(tx).to_dict()
else:
txjson = utils.sha3(rlp.descend(tx_rlp, 0)).encode('hex') # tx hash
txlist.append({
"tx": txjson,
"medstate": msr.encode('hex'),
"gas": str(utils.decode_int(gas))
})
b["transactions"] = txlist
if with_state:
state_dump = {}
for address, v in self.state.to_dict().iteritems():
state_dump[address.encode('hex')] = \
self.account_to_dict(address, with_storage_roots)
b['state'] = state_dump
if with_uncles:
b['uncles'] = [utils.sha3(rlp.encode(u)).encode('hex') for u in self.uncles]
return b
示例3: check_header_pow
def check_header_pow(header):
assert len(header[-1]) == 32
rlp_Hn = rlp.encode(header[:-1])
nonce = header[-1]
diff = utils.decoders['int'](header[block_structure_rev['difficulty'][0]])
h = utils.sha3(utils.sha3(rlp_Hn) + nonce)
return utils.big_endian_to_int(h) < 2 ** 256 / diff
示例4: mine
def mine(self, steps=1000):
"""
It is formally defined as PoW: PoW(H, n) = BE(SHA3(SHA3(RLP(Hn)) o n))
where:
RLP(Hn) is the RLP encoding of the block header H, not including the
final nonce component;
SHA3 is the SHA3 hash function accepting an arbitrary length series of
bytes and evaluating to a series of 32 bytes (i.e. 256-bit);
n is the nonce, a series of 32 bytes;
o is the series concatenation operator;
BE(X) evaluates to the value equal to X when interpreted as a
big-endian-encoded integer.
"""
nonce_bin_prefix = '\x00' * (32 - len(struct.pack('>q', 0)))
target = 2 ** 256 / self.block.difficulty
rlp_Hn = self.block.serialize_header_without_nonce()
for nonce in range(self.nonce, self.nonce + steps):
nonce_bin = nonce_bin_prefix + struct.pack('>q', nonce)
# BE(SHA3(SHA3(RLP(Hn)) o n))
h = utils.sha3(utils.sha3(rlp_Hn) + nonce_bin)
l256 = utils.big_endian_to_int(h)
if l256 < target:
self.block.nonce = nonce_bin
assert self.block.check_proof_of_work(self.block.nonce) is True
assert self.block.get_parent()
logger.debug(
'Nonce found %d %r', nonce, self.block)
return self.block
self.nonce = nonce
return False
示例5: check_proof_of_work
def check_proof_of_work(self, nonce):
assert len(nonce) == 32
rlp_Hn = self.serialize_header_without_nonce()
# BE(SHA3(SHA3(RLP(Hn)) o n))
h = utils.sha3(utils.sha3(rlp_Hn) + nonce)
l256 = utils.big_endian_to_int(h)
return l256 < 2 ** 256 / self.difficulty
示例6: create_contract
def create_contract(block,tx,msg):
oldroot = block.state.root
senderstate = block.state.get(msg.sender) or ['','','','']
recvstate = ['','',sha3(msg.data),'']
recvaddr = sha3(rlp.encode([msg.sender,senderstate[NONCE_INDEX]]))[12:]
code = msg.data
statedb.put(sha3(msg.data),msg.data)
compustate = Compustate(gas=msg.gas)
# Not enough vaue to send, instaquit
if decode_int(senderstate[BALANCE_INDEX]) < msg.value:
recvstate[2] = []
block.state.update(recvaddr,recvstate)
return recvaddr, compustate.gas
# Transfer value and update nonce
senderstate[BALANCE_INDEX] = encode_int(decode_int(senderstate[BALANCE_INDEX])-msg.value)
senderstate[NONCE_INDEX] = encode_int(decode_int(senderstate[NONCE_INDEX])+1)
recvstate[BALANCE_INDEX] = encode_int(decode_int(senderstate[BALANCE_INDEX])+msg.value)
block.state.update(msg.sender.decode('hex'),senderstate)
block.state.update(recvaddr,recvstate)
# Temporary pre-POC5: don't do the code/init thing
return recvaddr, compustate.gas
# Main loop
while 1:
o = apply_op(block,tx,msg,msg.data,compustate.op)
if o is not None:
if o == OUT_OF_GAS:
block.state.root = oldroot
return 0, 0
else:
recvstate = block.state.get(recvaddr)
recvstate[CODE_INDEX] = sha3(map(chr,o))
statedb.put(sha3(map(chr,o)),map(chr,o))
block.state.update(recvaddr,recvstate)
return recvaddr, recvstate
示例7: mk_blank_acct
def mk_blank_acct(self):
if not hasattr(self, '_blank_acct'):
codehash = utils.sha3('')
self.state.db.put(utils.sha3(''), '')
self._blank_acct = [utils.encode_int(0),
utils.encode_int(0),
trie.BLANK_ROOT,
codehash]
return self._blank_acct[:]
示例8: serialize
def serialize(self):
txlist = [x.serialize() for x in self.transactions]
header = [encode_int(self.number),
self.prevhash,
sha3(rlp.encode(self.uncles)),
self.coinbase.decode('hex'),
self.state.root,
sha3(rlp.encode(txlist)),
encode_int(self.difficulty),
encode_int(self.timestamp),
self.extradata,
encode_int(self.nonce)]
return rlp.encode([header, txlist, self.uncles])
示例9: remote_blocks_received_handler
def remote_blocks_received_handler(sender, block_lst, peer, **kwargs):
logger.debug("received %d remote blocks", len(block_lst))
old_head = chain_manager.head
# assuming chain order w/ newest block first
for block_data in reversed(block_lst):
try:
block = blocks.Block.deserialize(rlp.encode(block_data))
except blocks.UnknownParentException:
# no way to ask peers for older parts of chain
bhash = utils.sha3(rlp.encode(block_data)).encode('hex')[:4]
phash = block_data[0][0].encode('hex')[:4]
number = utils.decode_int(block_data[0][6])
logger.debug('Block(#%d %s %s) with unknown parent, requesting ...',
number, bhash, phash.encode('hex')[:4])
chain_manager.synchronize_blockchain()
break
if block.hash in chain_manager:
logger.debug('Known %r', block)
else:
if block.has_parent():
# add block & set HEAD if it's longest chain
success = chain_manager.add_block(block)
if success:
logger.debug('Added %r', block)
else:
logger.debug('Orphant %r', block)
if chain_manager.head != old_head:
chain_manager.synchronize_blockchain()
示例10: create_contract
def create_contract(block, tx, msg):
snapshot = block.snapshot()
sender = msg.sender.decode('hex') if len(msg.sender) == 40 else msg.sender
nonce = utils.encode_int(block.get_nonce(msg.sender))
recvaddr = utils.sha3(rlp.encode([sender, nonce]))[12:]
assert not block.get_code(recvaddr)
msg.to = recvaddr
block.increment_nonce(msg.sender)
# Transfer value, instaquit if not enough
o = block.transfer_value(msg.sender, msg.to, msg.value)
if not o:
return 0, msg.gas
compustate = Compustate(gas=msg.gas)
# Main loop
while 1:
o = apply_op(block, tx, msg, msg.data, compustate)
if o is not None:
if o == OUT_OF_GAS:
block.revert(snapshot)
return 0, 0, []
else:
for s in block.suicides:
block.state.delete(utils.encode_addr(s))
block.set_code(recvaddr, ''.join(map(chr, o)))
return recvaddr, compustate.gas, o
示例11: create_contract
def create_contract(block,tx,msg):
snapshot = block.snapshot()
sender = msg.sender.decode('hex') if len(msg.sender) == 40 else msg.sender
nonce = encode_int(block.get_nonce(msg.sender))
recvaddr = sha3(rlp.encode([sender,nonce]))[12:]
code = msg.data
# Transfer value, instaquit if not enough
block.delta_balance(recvaddr,msg.value)
o = block.delta_balance(msg.sender,msg.value)
if not o:
return 0, msg.gas
block.set_code(recvaddr,msg.data)
compustate = Compustate(gas=msg.gas)
# Temporary pre-POC5: don't do the code/init thing
return recvaddr, compustate.gas
# Main loop
while 1:
o = apply_op(block,tx,msg,msg.data,compustate.op)
if o is not None:
if o == OUT_OF_GAS:
block.state.root = oldroot
return 0, 0
else:
block.set_code(''.join(map(chr,o)))
return recvaddr, compustate.gas
示例12: sign
def sign(self, privkey):
assert not self.signature
assert isinstance(privkey, bytes) and len(privkey) == 32
h = sha3(_encode_optimized(self.serialize()))
self.signature = c_ecdsa_sign_compact(h, privkey)
assert len(self.signature) == 65
return self
示例13: send
def send(self, sender, host_port, data):
print 'in send unreliable', self.network.counter, self.network.counter % self.droprate
if self.network.counter % self.droprate:
self.network.send(sender, host_port, data)
else:
self.network.track_send(sender, host_port, data)
print('dropped data {}'.format(pex(sha3(data))))
示例14: send
def send(self, receiver_address, msg):
assert isaddress(receiver_address)
assert not isinstance(msg, (Ack, BaseError)), msg
log.info("SENDING {} > {} : {}".format(pex(self.raiden.address),
pex(receiver_address), msg))
host_port = self.discovery.get(receiver_address)
data = msg.encode()
msghash = sha3(data)
self.tries[msghash] = self.max_tries
log.debug("MSGHASH SENT", msghash=pex(msghash))
assert len(data) < self.max_message_size
def repeater():
while self.tries.get(msghash, 0) > 0:
if not self.repeat_messages and self.tries[msghash] < self.max_tries:
raise Exception(
"DEACTIVATED MSG resents {} {}".format(pex(receiver_address), msg))
self.tries[msghash] -= 1
self.transport.send(self.raiden, host_port, data)
gevent.sleep(self.try_interval)
# Each sent msg must be acked. When msg is acked its hash is removed from self.tries
if msghash in self.tries:
assert False, "Node does not reply, fixme suspend node"
gevent.spawn(repeater)
示例15: validate_uncles
def validate_uncles(self):
if utils.sha3rlp(self.uncles) != self.uncles_hash:
return False
# Check uncle validity
ancestor_chain = [a for a in self.get_ancestor_list(MAX_UNCLE_DEPTH + 1) if a]
ineligible = []
# Uncles of this block cannot be direct ancestors and cannot also
# be uncles included 1-6 blocks ago
for ancestor in ancestor_chain[1:]:
ineligible.extend(ancestor.uncles)
ineligible.extend([b.list_header() for b in ancestor_chain])
eligible_ancestor_hashes = [x.hash for x in ancestor_chain[2:]]
for uncle in self.uncles:
if not check_header_pow(uncle):
return False
prevhash = uncle[block_structure_rev['prevhash'][0]]
if prevhash not in eligible_ancestor_hashes:
log.error("Uncle does not have a valid ancestor", block=self)
return False
if uncle in ineligible:
log.error("Duplicate uncle", block=self, uncle=utils.sha3(
rlp.encode(uncle)).encode('hex'))
return False
ineligible.append(uncle)
return True