本文整理汇总了Python中pyethereum.utils.sha3函数的典型用法代码示例。如果您正苦于以下问题:Python sha3函数的具体用法?Python sha3怎么用?Python sha3使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sha3函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_genesis_hash
def test_genesis_hash(genesis_fixture):
set_db()
genesis = blocks.genesis()
"""
YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (),
SHA3(42), (), ()
Where 0256 refers to the parent and state and transaction root hashes,
a 256-bit hash which is all zeroes;
0160 refers to the coinbase address,
a 160-bit hash which is all zeroes;
2**22 refers to the difficulty;
0 refers to the timestamp (the Unix epoch);
() refers to the extradata and the sequences of both uncles and
transactions, all empty.
SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
and only byte is of value 42.
SHA3RLP() values refer to the hashes of the transaction and uncle lists
in RLP
both empty.
The proof-of-concept series include a development premine, making the state
root hash some value stateRoot. The latest documentation should be
consulted for the value of the state root.
"""
h256 = '\00' * 32
sr = genesis_fixture['genesis_state_root'].decode('hex')
genesis_block_defaults = [
["prevhash", "bin", h256], # h256()
["uncles_hash", "bin", utils.sha3(rlp.encode([]))], # sha3EmptyList
["coinbase", "addr", "0" * 40], # h160()
["state_root", "trie_root", sr], # stateRoot
["tx_list_root", "trie_root", trie.BLANK_ROOT], # h256()
["difficulty", "int", 2 ** 22], # c_genesisDifficulty
["number", "int", 0], # 0
["min_gas_price", "int", 0], # 0
["gas_limit", "int", 10 ** 6], # 10**6 for genesis
["gas_used", "int", 0], # 0
["timestamp", "int", 0], # 0
["extra_data", "bin", ""], # ""
["nonce", "bin", utils.sha3(chr(42))], # sha3(bytes(1, 42));
]
cpp_genesis_block = rlp.decode(
genesis_fixture['genesis_rlp_hex'].decode('hex'))
cpp_genesis_header = cpp_genesis_block[0]
for i, (name, typ, genesis_default) in enumerate(genesis_block_defaults):
assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
assert getattr(genesis, name) == genesis_default
assert genesis.hex_hash() == genesis_fixture['genesis_hash']
assert genesis.hex_hash() == utils.sha3(
genesis_fixture['genesis_rlp_hex'].decode('hex')
).encode('hex')
示例2: test_genesis_hash
def test_genesis_hash():
set_db()
genesis = blocks.genesis()
"""
cpp: https://github.com/ethereum/cpp-ethereum/libethereum/BlockInfo.cpp#L64
h256() << sha3EmptyList << h160() << stateRoot << h256() << c_genesisDifficulty << 0 << 0 << 1000000 << 0 << (uint)0 << string() << sha3(bytes(1, 42));
PoC5 etherpad: https://ethereum.etherpad.mozilla.org/11
Genesis block is: ( B32(0, 0, ...), B32(sha3(B())), B20(0, 0, ...), B32(stateRoot), B32(0, 0, ...), P(2^22), P(0), P(0), P(1000000), P(0), P(0) << B() << B32(sha3(B(42))) )
Genesis hash: 69a7356a245f9dc5b865475ada5ee4e89b18f93c06503a9db3b3630e88e9fb4e
YP: https://raw.githubusercontent.com/ethereum/latexpaper/master/Paper.tex
0256 , SHA3RLP(), 0160 , stateRoot, 0256 , 2**22 , 0, 0, 1000000, 0, 0, (), SHA3(42), (), ()
Where 0256 refers to the parent and state and transaction root hashes,
a 256-bit hash which is all zeroes;
0160 refers to the coinbase address,
a 160-bit hash which is all zeroes;
2**22 refers to the difficulty;
0 refers to the timestamp (the Unix epoch);
() refers to the extradata and the sequences of both uncles and transactions, all empty.
SHA3(42) refers to the SHA3 hash of a byte array of length one whose first
and only byte is of value 42.
SHA3RLP() values refer to the hashes of the transaction and uncle lists in RLP,
both empty.
The proof-of-concept series include a development premine, making the state root
hash some value stateRoot. The latest documentation should be consulted for
the value of the state root.
"""
h256 = "\x00" * 32
sr = CPP_PoC5_GENESIS_STATE_ROOT_HEX_HASH.decode('hex')
genisi_block_defaults = [
["prevhash", "bin", h256], # h256()
["uncles_hash", "bin", utils.sha3(rlp.encode([]))], # sha3EmptyList
["coinbase", "addr", "0" * 40], # h160()
["state_root", "trie_root", sr], # stateRoot
["tx_list_root", "trie_root", h256], # h256()
["difficulty", "int", 2 ** 22], # c_genesisDifficulty
["number", "int", 0], # 0
["min_gas_price", "int", 0], # 0
["gas_limit", "int", 1000000], # 1000000
["gas_used", "int", 0], # 0
["timestamp", "int", 0], # 0
["extra_data", "bin", ""], # ""
["nonce", "bin", utils.sha3(chr(42))], # sha3(bytes(1, 42));
]
cpp_genesis_block = rlp.decode(CPP_PoC5_GENESIS_HEX.decode('hex'))
cpp_genesis_header = cpp_genesis_block[0]
for i, (name, typ, genesis_default) in enumerate(genisi_block_defaults):
# print name, repr(getattr(genesis, name)), repr(genesis_default)
assert utils.decoders[typ](cpp_genesis_header[i]) == genesis_default
assert getattr(genesis, name) == genesis_default
assert genesis.hex_hash() == CPP_PoC5_GENESIS_HEX_HASH
示例3: bad
def bad(n=21):
# Build n levels
t = trie.Trie(s.db)
accum = ''
for i in range(n):
for j in range(1,16):
k = accum + '%X'%j
if len(k) % 2 != 0: k += '0'
k = zpadr(k.decode('hex'))
print k.encode('hex')
t.update(k,utils.sha3('cow'))
accum += '%X'%0
k = zpadr(accum.decode('hex'))
t.update(k,utils.sha3('cow'))
return t
示例4: create_default_config
def create_default_config():
config = ConfigParser.ConfigParser()
# set some defaults, which may be overwritten
config.add_section('network')
config.set('network', 'listen_host', '0.0.0.0')
config.set('network', 'listen_port', '30303')
config.set('network', 'num_peers', '5')
config.set('network', 'remote_port', '30303')
config.set('network', 'remote_host', '')
config.set('network', 'client_id', Packeter.CLIENT_ID)
config.set('network', 'node_id', sha3(str(uuid.uuid1())).encode('hex'))
config.add_section('api')
config.set('api', 'listen_host', '127.0.0.1')
config.set('api', 'listen_port', '30203')
config.add_section('misc')
config.set('misc', 'verbosity', '1')
config.set('misc', 'config_file', None)
config.set('misc', 'logging', None)
config.set('misc', 'data_dir', data_dir.path)
config.set('misc', 'mining', '10')
config.add_section('wallet')
config.set('wallet', 'coinbase', '0' * 40)
return config
示例5: test_status
def test_status():
p = get_packeter()
total_difficulty = 1000
head_hash = utils.sha3('head')
genesis_hash = utils.sha3('genesis')
msg = p.dump_Status(total_difficulty, head_hash, genesis_hash)
success, res = p.load_packet(msg)
assert success
_, _, cmd, data, remain = res
assert cmd == 'Status'
assert idec(data[0]) == packeter.Packeter.ETHEREUM_PROTOCOL_VERSION
assert idec(data[1]) == packeter.Packeter.NETWORK_ID
assert idec(data[2]) == total_difficulty
assert data[3] == head_hash
assert data[4] == genesis_hash
return
示例6: create_wrapper
def create_wrapper(msg):
ext.set_balance(msg.sender, ext.get_balance(msg.sender) - msg.value)
sender = msg.sender.decode('hex') if len(msg.sender) == 40 else msg.sender
nonce = u.encode_int(ext._block.get_nonce(msg.sender))
addr = u.sha3(rlp.encode([sender, nonce]))[12:].encode('hex')
hexdata = msg.data.extract_all().encode('hex')
apply_message_calls.append(dict(gasLimit=msg.gas, value=msg.value,
destination='', data=hexdata))
return 1, msg.gas, addr
示例7: _recv_Blocks
def _recv_Blocks(self, data):
print("RECEIVED", len(data))
for x in reversed(data):
enc = rlp.encode(x)
#tb = blocks.TransientBlock(enc)
#print tb
self.blk_counter += 1
fh.write(enc.encode('hex') + '\n') # LOG line
h = utils.sha3(enc)
print('received block %s %d' % (h.encode('hex'), self.blk_counter))
request(self,h)
示例8: push_content
def push_content(content, title, genesis, root_contract, usr):
key, addr = usr
nonce = get_nonce(genesis, addr)
content_hash = utils.sha3(content)
# push a transaction with a title. recover title from blockchain
tx_push = transactions.Transaction(nonce, 0, 10**12, 10000, root_contract, serpent.encode_datalist([1, content_hash, title])).sign(key)
ans = processblock.apply_tx(genesis, tx_push)
f = open('data/%s'%content_hash.encode('hex'), 'w')
f.write(content)
f.close()
return content_hash
示例9: genesis_fixture
def genesis_fixture():
"""
Read genesis block from fixtures.
"""
genesis_fixture = None
with open('fixtures/genesishashestest.json', 'r') as f:
genesis_fixture = json.load(f)
assert genesis_fixture is not None, "Could not read genesishashtest.json from fixtures. Make sure you did 'git submodule init'!"
# FIXME: assert that link is uptodate
for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash', 'initial_alloc'):
assert k in genesis_fixture
assert utils.sha3(genesis_fixture['genesis_rlp_hex'].decode('hex')).encode('hex') ==\
genesis_fixture['genesis_hash']
return genesis_fixture
示例10: deserialize_child
def deserialize_child(parent, rlpdata):
"""
deserialization w/ replaying transactions
"""
header_args, transaction_list, uncles = rlp.decode(rlpdata)
assert len(header_args) == len(blocks.block_structure)
kargs = dict(transaction_list=transaction_list, uncles=uncles)
# Deserialize all properties
for i, (name, typ, default) in enumerate(blocks.block_structure):
kargs[name] = utils.decoders[typ](header_args[i])
block = blocks.Block.init_from_parent(parent, kargs['coinbase'],
extra_data=kargs['extra_data'],
timestamp=kargs['timestamp'])
block.finalize() # this is the first potential state change
# replay transactions
for tx_lst_serialized, _state_root, _gas_used_encoded in transaction_list:
tx = transactions.Transaction.create(tx_lst_serialized)
logger.debug("data %r", tx.data)
logger.debug('applying %r', tx)
logger.debug('applying %r', tx.to_dict())
logger.debug('block.gas_used before: %r', block.gas_used)
success, output = processblock.apply_transaction(block, tx)
logger.debug('block.gas_used after: %r', block.gas_used)
logger.debug('success: %r', success)
diff = utils.decode_int(_gas_used_encoded) - block.gas_used
logger.debug("GAS_USED DIFF %r", diff)
assert utils.decode_int(_gas_used_encoded) == block.gas_used
assert _state_root.encode('hex') == block.state.root_hash.encode('hex')
# checks
assert block.prevhash == parent.hash
assert block.tx_list_root == kargs['tx_list_root']
assert block.gas_used == kargs['gas_used']
assert block.gas_limit == kargs['gas_limit']
assert block.timestamp == kargs['timestamp']
assert block.difficulty == kargs['difficulty']
assert block.number == kargs['number']
assert block.extra_data == kargs['extra_data']
assert utils.sha3(rlp.encode(block.uncles)) == kargs['uncles_hash']
assert block.state.root_hash.encode(
'hex') == kargs['state_root'].encode('hex')
block.uncles_hash = kargs['uncles_hash']
block.nonce = kargs['nonce']
block.min_gas_price = kargs['min_gas_price']
return block
示例11: _get_block_before_tx
def _get_block_before_tx(txhash):
tx, blk = chain_manager.index.get_transaction(txhash.decode('hex'))
# get the state we had before this transaction
test_blk = 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 utils.sha3(rlp.encode(tx_lst_serialized)) == tx.hash:
break
else:
pre_state = sr
test_blk.state.root_hash = pre_state
return test_blk, tx
示例12: before_feature
def before_feature(self, context, feature):
'''
.. note::
`context.conf` is used instead of `context.config` because `config`
is used internally in `context` by *behave*
'''
context.conf = conf = mock.MagicMock()
node_id = sha3(str(uuid.uuid1())).encode('hex')
tempdir = tempfile.mkdtemp()
def get_side_effect(section, option):
if section == 'network' and option == 'client_id':
return 'client id'
if section == 'network' and option == 'listen_host':
return '0.0.0.0'
if section == 'network' and option == 'node_id':
return node_id
if section == 'wallet' and option == 'coinbase':
return '0'*40
if section == 'misc' and option == 'data_dir':
return tempdir
def getint_side_effect(section, option):
if section == 'network' and option == 'listen_port':
return 1234
if section == 'network' and option == 'num_peers':
return 10
conf.get.side_effect = get_side_effect
conf.getint.side_effect = getint_side_effect
示例13: range
import serpent, json, random
from pyethereum import transactions, blocks, processblock,utils
NUM_ACCOUNTS=4
root_code = serpent.compile(open('zeroid.se').read())
root_key = utils.sha3('cow')
root_addr = utils.privtoaddr(root_key)
keys = {}
for x in range(NUM_ACCOUNTS):
key = utils.sha3(str(x+4))
addr = utils.privtoaddr(key)
keys[addr] = key
endowment = {root_addr: 10**18}
for x in keys:
endowment[x] = 10**18
genesis = blocks.genesis(endowment)
tx1 = transactions.contract(0, 10**12, 100000, 0, root_code).sign(root_key)
result, contract = processblock.apply_transaction(genesis, tx1)
nonce=1
for address in keys:
示例14: default_node_id
def default_node_id():
return sha3(str(uuid.uuid1())).encode('hex')
示例15: create_config
def create_config():
config = ConfigParser.ConfigParser()
# set some defaults, which may be overwritten
config.add_section('network')
config.set('network', 'listen_host', '0.0.0.0')
config.set('network', 'listen_port', '30303')
config.set('network', 'num_peers', '5')
config.set('network', 'remote_port', '30303')
config.set('network', 'remote_host', '')
config.set('network', 'client_id', Packeter.CLIENT_ID)
config.set('network', 'node_id', sha3(str(uuid.uuid1())).encode('hex'))
config.add_section('api')
config.set('api', 'listen_host', '127.0.0.1')
config.set('api', 'listen_port', '30203')
config.add_section('misc')
config.set('misc', 'verbosity', '1')
config.set('misc', 'config_file', None)
config.set('misc', 'logging', None)
config.set('misc', 'data_dir', data_dir.path)
config.set('misc', 'mining', '10')
config.add_section('wallet')
config.set('wallet', 'coinbase', '0' * 40)
usage = "usage: %prog [options]"
parser = OptionParser(usage=usage, version=Packeter.CLIENT_ID)
parser.add_option(
"-l", "--listen",
dest="listen_port",
default=config.get('network', 'listen_port'),
help="<port> Listen on the given port for incoming"
" connected (default: 30303).")
parser.add_option(
"-a", "--address",
dest="coinbase",
help="Set the coinbase (mining payout) address",
default=config.get('wallet', 'coinbase'))
parser.add_option(
"-d", "--data_dir",
dest="data_dir",
help="<path> Load database from path (default: %s)" % config.get(
'misc', 'data_dir'),
default=config.get('misc', 'data_dir'))
parser.add_option(
"-r", "--remote",
dest="remote_host",
help="<host> Connect to remote host"
" (try: 54.201.28.117 or 54.204.10.41)")
parser.add_option(
"-p", "--port",
dest="remote_port",
default=config.get('network', 'remote_port'),
help="<port> Connect to remote port (default: 30303)"
)
parser.add_option(
"-v", "--verbose",
dest="verbosity",
default=config.get('misc', 'verbosity'),
help="<0 - 3> Set the log verbosity from 0 to 3 (default: 1)")
parser.add_option(
"-m", "--mining",
dest="mining",
default=config.get('misc', 'mining'),
help="<0 - 100> Percent CPU used for mining 0==off (default: 10)")
parser.add_option(
"-L", "--logging",
dest="logging",
default=config.get('misc', 'logging'),
help="<logger1:LEVEL,logger2:LEVEL> set the console log level for"
" logger1, logger2, etc. Empty loggername means root-logger,"
" e.g. 'pyethereum.wire:DEBUG,:INFO'. Overrides '-v'")
parser.add_option(
"-x", "--peers",
dest="num_peers",
default=config.get('network', 'num_peers'),
help="<number> Attempt to connect to given number of peers"
"(default: 5)")
parser.add_option("-C", "--config",
dest="config_file",
help="read coniguration")
(options, args) = parser.parse_args()
# set network options
for attr in ('listen_port', 'remote_host', 'remote_port', 'num_peers'):
config.set('network', attr, getattr(
options, attr) or config.get('network', attr))
# set misc options
for attr in ('verbosity', 'config_file', 'logging', 'data_dir', 'mining'):
config.set(
'misc', attr, getattr(options, attr) or config.get('misc', attr))
# set wallet options
for attr in ('coinbase',):
config.set(
'wallet', attr, getattr(options, attr) or config.get('wallet', attr))
#.........这里部分代码省略.........