def test_ecrecover(): s = tester.state() c = s.abi_contract(ecrecover_code) priv = utils.sha3('some big long brainwallet password') pub = bitcoin.privtopub(priv) msghash = utils.sha3('the quick brown fox jumps over the lazy dog') pk = PrivateKey(priv, raw=True) signature = pk.ecdsa_recoverable_serialize( pk.ecdsa_sign_recoverable(msghash, raw=True) ) signature = signature[0] + utils.bytearray_to_bytestr([signature[1]]) V = utils.safe_ord(signature[64]) + 27 R = big_endian_to_int(signature[0:32]) S = big_endian_to_int(signature[32:64]) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr result = c.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S) assert result == addr
def sender(self): if not self._sender: # Determine sender if self.v: if self.r >= N or self.s >= N or self.v < 27 or self.v > 28 \ or self.r == 0 or self.s == 0: raise InvalidTransaction("Invalid signature values!") log.debug('recovering sender') rlpdata = rlp.encode(self, UnsignedTransaction) rawhash = utils.sha3(rlpdata) pk = PublicKey(flags=ALL_FLAGS) try: pk.public_key = pk.ecdsa_recover( rawhash, pk.ecdsa_recoverable_deserialize( zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.r)), 32) + zpad(utils.bytearray_to_bytestr(int_to_32bytearray(self.s)), 32), self.v - 27 ), raw=True ) pub = pk.serialize(compressed=False) except Exception: raise InvalidTransaction("Invalid signature values (x^3+7 is non-residue)") if pub[1:] == b"\x00" * 32: raise InvalidTransaction("Invalid signature (zero privkey cannot sign)") pub = encode_pubkey(pub, 'bin') self._sender = utils.sha3(pub[1:])[-20:] assert self.sender == self._sender else: self._sender = 0 return self._sender
def __init__(self, app): log.info("Casper service init") self.db = app.services.db self.bcast = app.services.peermanager.broadcast cfg = app.config['casper'] self.account = app.services.accounts.get_by_address(app.services.accounts.coinbase) self.privkey = self.account.privkey if 'network_id' in self.db: db_network_id = self.db.get('network_id') if db_network_id != str(cfg['network_id']): raise RuntimeError( "The database in '{}' was initialized with network id {} and can not be used " "when connecting to network id {}. Please choose a different data directory.".format( app.config['db']['data_dir'], db_network_id, cfg['network_id'] ) ) else: self.db.put('network_id', str(cfg['network_id'])) self.db.commit() self.epoch_length = cfg['epoch_length'] self.epoch_source = -1 self.epoch = 0 self.ancestry_hash = sha3('') self.source_ancestry_hash = sha3('') self.chain = app.services.chain self.genesis = self.chain.block(cfg['genesis_hash']) assert self.genesis assert self.genesis['number'] % self.epoch_length == 0 self.store = LevelDBStore(self.db, self.epoch_length, self.genesis) self.validator = self.store.validator(cfg['validator_id']) super(CasperService, self).__init__(app)
def sender(self): if not self._sender: # Determine sender if self.r == 0 and self.s == 0: self._sender = null_address else: if self.v in (27, 28): vee = self.v sighash = utils.sha3(rlp.encode(self, UnsignedTransaction)) elif self.v >= 37: vee = self.v - self.network_id * 2 - 8 assert vee in (27, 28) rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[ :-3] + [self.network_id, '', '']) sighash = utils.sha3(rlpdata) else: raise InvalidTransaction("Invalid V value") if self.r >= secpk1n or self.s >= secpk1n or self.r == 0 or self.s == 0: raise InvalidTransaction("Invalid signature values!") pub = ecrecover_to_pub(sighash, vee, self.r, self.s) if pub == b'\x00' * 64: raise InvalidTransaction( "Invalid signature (zero privkey cannot sign)") self._sender = utils.sha3(pub)[-20:] return self._sender
def generate_accounts(seeds): """Create private keys and addresses for all seeds. """ return { seed: dict( privatekey=encode_hex(sha3(seed)), address=encode_hex(privatekey_to_address(sha3(seed))) ) for seed in seeds}
def test_webui(): # pylint: disable=too-many-locals num_assets = 3 num_nodes = 10 assets_addresses = [ sha3('webui:asset:{}'.format(number))[:20] for number in range(num_assets) ] private_keys = [ sha3('webui:{}'.format(position)) for position in range(num_nodes) ] BlockChainServiceMock._instance = True blockchain_service= BlockChainServiceMock(None, MOCK_REGISTRY_ADDRESS) # overwrite the instance BlockChainServiceMock._instance = blockchain_service # pylint: disable=redefined-variable-type registry = blockchain_service.registry(MOCK_REGISTRY_ADDRESS) for asset in assets_addresses: registry.add_asset(asset) channels_per_node = 2 deposit = 100 app_list = create_network( private_keys, assets_addresses, MOCK_REGISTRY_ADDRESS, channels_per_node, deposit, DEFAULT_SETTLE_TIMEOUT, UDPTransport, BlockChainServiceMock ) app0 = app_list[0] addresses = [ app.raiden.address.encode('hex') for app in app_list if app != app_list[0] ] print '\nCreated nodes: \n', for node in addresses: print node setup_messages_cb() app0_assets = getattr(app0.raiden.api, 'assets') print '\nAvailable assets:' for asset in app0_assets: print asset.encode('hex') print '\n' wamp = WAMPRouter(app0.raiden, 8080, ['channel', 'test']) wamp.run()
def run_ethash_test(params, mode): if 'header' not in params: b = blocks.genesis(db) b.nonce = decode_hex(params['nonce']) b.number = params.get('number', 0) header = b.header params['header'] = encode_hex(rlp.encode(b.header)) else: header = blocks.BlockHeader(decode_hex(params['header'])) header_hash = header.mining_hash cache_size = ethash.get_cache_size(header.number) full_size = ethash.get_full_size(header.number) seed = b'\x00' * 32 for i in range(header.number // ethash_utils.EPOCH_LENGTH): seed = utils.sha3(seed) nonce = header.nonce assert len(nonce) == 8 assert len(seed) == 32 t1 = time.time() cache = ethash.mkcache(cache_size, seed) t2 = time.time() cache_hash = encode_hex(utils.sha3(ethash.serialize_cache(cache))) t6 = time.time() light_verify = ethash.hashimoto_light(full_size, cache, header_hash, nonce) t7 = time.time() # assert full_mine == light_mine out = { "seed": encode_hex(seed), "header_hash": encode_hex(header_hash), "nonce": encode_hex(nonce), "cache_size": cache_size, "full_size": full_size, "cache_hash": cache_hash, "mixhash": encode_hex(light_verify["mix digest"]), "result": encode_hex(light_verify["result"]), } if mode == FILL: header.mixhash = light_verify["mixhash"] params["header"] = encode_hex(rlp.encode(header)) for k, v in list(out.items()): params[k] = v return params elif mode == VERIFY: should, actual = header.mixhash, light_verify['mixhash'] assert should == actual, "Mismatch: mixhash %r %r" % (should, actual) for k, v in list(out.items()): assert params[k] == v, "Mismatch: " + k + ' %r %r' % (params[k], v) elif mode == TIME: return { "cache_gen": t2 - t1, "verification_time": t7 - t6 }
def sender(self): if not self._sender: # Determine sender if self.v: if self.r >= N or self.s >= P or self.v < 27 or self.v > 28: raise InvalidTransaction("Invalid signature values!") log.debug('recovering sender') rlpdata = rlp.encode(self, UnsignedTransaction) rawhash = utils.sha3(rlpdata) pub = encode_pubkey(ecdsa_raw_recover(rawhash, (self.v, self.r, self.s)), 'bin') self._sender = utils.sha3(pub[1:])[-20:] assert self.sender == self._sender else: self._sender = 0 return self._sender
def test_string_logging(): s = tester.state() c = s.abi_contract(string_logging_code) o = [] s.block.log_listeners.append(lambda x: o.append(c.translator.listen(x))) c.moo() assert o == [{ "_event_type": b"foo", "x": b"bob", "__hash_x": utils.sha3(b"bob"), "y": b"cow", "__hash_y": utils.sha3(b"cow"), "z": b"dog", "__hash_z": utils.sha3(b"dog"), }]
def test_eth_call(rpc_client, accounts): txn_hash = rpc_client( method="eth_sendTransaction", params=[{ "from": accounts[0], "data": CONTRACT_BIN, "value": 1234, }], ) txn_receipt = rpc_client( method="eth_getTransactionReceipt", params=[txn_hash], ) contract_address = txn_receipt['contractAddress'] assert contract_address function_sig = encode_data(sha3("return13()")[:4]) should_be_13 = rpc_client( method="eth_call", params=[{ "from": accounts[0], "to": contract_address, "data": function_sig, }], ) result = big_endian_to_int(decode_hex(should_be_13[2:])) assert result == 13
def test(): t.gas_price = 0 s = t.state() c = s.abi_contract('gamble.se') rseed = os.urandom(32) seed1 = utils.sha3(rseed) c.set_curseed(seed1) s.block.set_balance(c.address, 27000) totbal = sum([s.block.get_balance(x) for x in t.accounts]) # 90 bets succeed (bet with 25% winning probability) for i in range(90): assert c.bet(utils.zpad(str(i), 32), 250, sender=t.keys[i % 10], value=100) >= 0 # 10 bets fail due to not enough collateral for i in range(90, 100): assert c.bet(utils.zpad(str(i), 32), 250, sender=t.keys[i % 10], value=100) == -2 # Add more collateral s.block.delta_balance(c.address, 3000) # 10 bets succeed for i in range(90, 100): assert c.bet(utils.zpad(str(i), 32), 250, sender=t.keys[i % 10], value=100) >= 0 # 10 bets fail due to limit of 100 for i in range(100, 110): assert c.bet(utils.zpad(str(i), 32), 250, sender=t.keys[i % 10], value=100) == -1 mid_totbal = sum([s.block.get_balance(x) for x in t.accounts]) assert c.set_curseed(rseed, os.urandom(32)) # Check that a reasonable number of bets succeeded new_totbal = sum([s.block.get_balance(x) for x in t.accounts]) print 'Profit: ', totbal - new_totbal assert -4000 < (new_totbal - totbal) < 7000 assert 26000 < s.block.get_balance(c.address) < 37000
def benchmark(size): t = trie.Trie(db.EphemDB()) for i in range(size): t.update(utils.sha3('k'+str(i)), utils.sha3('v'+str(i))) sz = sum([len(v) for k, v in t.db.db.items()]) nsz = [] ldb = db.ListeningDB(t.db.db) for i in range(min(size, 100)): ldb2 = db.ListeningDB(ldb) odb = t.db t.db = ldb2 t.get(utils.sha3('k'+str(i))) nsz.append(sum([len(v) for k, v in ldb2.kv.items()])) t.db = odb ldbsz = sum([len(v) for k, v in ldb.kv.items()]) print sz, sum(nsz) // len(nsz), ldbsz
def test_ssv(chain, accounts, storage_slots): # get log reader sj = chain.storage.db # state journal sj.commit() lr = statejournal.JournalReader(sj.db) # validate full chain if False: state = lr.validate_state(sj.update_counter) assert state == sj.state_digest assert state == lr.last_update()['state_digest'] # get ssv ################ # read first (oldest entry) counter = 1 k = accounts[0] v = int_to_big_endian(counter) k += v # get the proof val, update_counter = sj.get_raw(k) proof = lr.get_ssv(update_counter) assert proof['value'] == val, (big_endian_to_int(proof['value']), val) hash_chain = proof['hash_chain'] assert len(hash_chain) s = hash_chain[0] for h in hash_chain[1:]: s = sha3(s + h) assert s == sj.state_digest
def handle_secret(self, identifier, secret): """ Unlock locks, register the secret, and send Secret messages as necessary. This function will: - Unlock the locks created by this node and send a Secret message to the corresponding partner so that she can withdraw the asset. - Register the secret for the locks received and reveal the secret to the senders Note: The channel needs to be registered with `register_channel_for_hashlock`. """ # handling the secret needs to: # - unlock the asset for all `forward_channel` (the current one # and the ones that failed with a refund) # - send a message to each of the forward nodes allowing them # to withdraw the asset # - register the secret for the `originating_channel` so that a # proof can be made, if necessary # - reveal the secret to the `sender` node (otherwise we # cannot withdraw the asset) hashlock = sha3(secret) self._secret(identifier, secret, None, hashlock)
def __init__(self, chain, receiver, tx_num): assert isinstance(receiver, int) sender = config['num_accounts'] - receiver self.hash = sha3(str(tx_num)) # increase nonce Account(chain, sender).update_nonce() # receiving account account = Account(chain, receiver) reads = int(config['storage_reads'](tx_num)) reads = min(reads, account.storage_slots) updates = int(reads / config['storage_read_update_ratio']) deletes = int(updates / config['storage_read_delete_ratio']) # print reads, updates, deletes assert updates + deletes <= reads if not reads: # simple value transfer account.update_balance(tx_num) return # read, update, write for i in range(reads): i += tx_num v = account.read(i) if i < updates: account.store(i, v+i+tx_num) elif i < updates + deletes: account.delete(i)
def signing_hash(self): return sha3( 'commit%s%s' % ( encode_int32(self.epoch), self.hash ) )
def test_statejournal_read(chain): # validate chain sj = chain.storage.db # state journal sj.commit() lr = statejournal.JournalReader(sj.db) state = lr.validate_state(sj.update_counter) assert state == sj.state # get ssv ################ for i in range(config['num_accounts']): account = Account(chain, i) keys = account.keys() if keys: break assert len(keys) print 'keys found', account k = keys[0] val, update_counter = sj.get_raw(k) proof = lr.get_ssv(update_counter) assert proof['value'] == val hash_chain = proof['hash_chain'] assert len(hash_chain) s = hash_chain[0] for h in hash_chain[1:]: s = sha3(s + h) assert s == sj.state
def test(): t.gas_price = 0 s = t.state() c = s.abi_contract("randao.se") votes = [] ids = [] xor = 0 for i in range(5): r = random.randrange(2 ** 256) xor ^= r votes.append(utils.zpad(utils.encode_int(r), 32)) f = c.getFee() for i in range(5): ids.append(c.submitHash(utils.sha3(votes[i]), value=f)) while c.getPhase() == 0: s.mine(10) for i in range(5): c.submitValue(ids[i], votes[i]) while c.getPhase() == 1: s.mine(10) c.claimResults() assert c.getNextResultPos() == 1 assert c.getResult(0) == utils.zpad(utils.encode_int(xor), 32), ( c.getResult(0), utils.zpad(utils.encode_int(xor), 32), )
def test_ecrecover(): s = tester.state() c = s.abi_contract(ecrecover_code) priv = encode_hex(utils.sha3('some big long brainwallet password')) pub = bitcoin.privtopub(priv) msghash = encode_hex(utils.sha3('the quick brown fox jumps over the lazy dog')) V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv) assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub) addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:]) assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr result = c.test_ecrecover(utils.big_endian_to_int(decode_hex(msghash)), V, R, S) assert result == addr
def _check_pow(header): number = big_endian_to_int(header[8]) difficulty = big_endian_to_int(header[7]) mixhash = header[13] nonce = header[14] mining_hash = sha3(rlp.encode(header[:13])) assert check_pow(number, mining_hash, mixhash, nonce, difficulty)
def test_decode_transfer(): encoded_data = "0500000000000000000000010bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd823110747000000000000000000000000000000000000000000000000000000000000000160d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000000ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f00" bad_encoded_data = "0500000000000000000000010bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd823110747000000000000000000000000000000000000000000000000000000000000000160d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000000ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f0001" data = encoded_data.decode("hex") bad_data = bad_encoded_data.decode("hex") s = tester.state() c = s.abi_contract(decode_code, language="solidity") o1 = c.decodeTransfer(data) assert data[0] == "\x05" # make sure data has right cmdid assert len(data) == 213 nonce = o1[0] assert nonce == 1 asset = o1[1] assert asset == sha3("asset")[:20].encode("hex") recipient = o1[2] assert len(recipient) == 40 assert recipient == privtoaddr("y" * 32).encode("hex") balance = o1[3] assert balance == 1 optionalLocksroot = o1[4] assert optionalLocksroot == "60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51".decode("hex") optionalSecret = o1[5] assert optionalSecret == "0000000000000000000000000000000000000000000000000000000000000000".decode("hex") signature = "ff9636ccb66e73219fd166cd6ffbc9c6215f74ff31c1fd4131cf532b29ee096f65278c459253fba65bf019c723a68bb4a6153ea8378cd1b15d55825e1a291b6f00".decode( "hex" ) r = o1[6] s = o1[7] v = o1[8] assert r == signature[:32] assert s == signature[32:64] assert v == int(signature[64].encode("hex")) with pytest.raises(TransactionFailed): c.decodeSecret(bad_data)
def setup_apps(amount, assets, num_transfers, num_nodes, channels_per_node): assert len(assets) <= num_nodes deposit = amount * num_transfers private_keys = [ sha3('mediated_transfer:{}'.format(position)) for position in range(num_nodes) ] BlockChainServiceMock.reset() blockchain_services = list() for privkey in private_keys: blockchain = BlockChainServiceMock( privkey, MOCK_REGISTRY_ADDRESS, ) blockchain_services.append(blockchain) registry = blockchain_services[0].registry(MOCK_REGISTRY_ADDRESS) for asset in assets: registry.add_asset(asset) verbosity = 3 apps = create_network( blockchain_services, assets, channels_per_node, deposit, DEFAULT_SETTLE_TIMEOUT, UDPTransport, verbosity, ) return apps
def new_block(block, use_parent=True): """Create a new block based on a parent block. The block will not include any transactions and will not be finalized. """ parent = block.get_parent() header = BlockHeader(prevhash=parent.hash, uncles_hash=utils.sha3(rlp.encode([])), coinbase=block.coinbase, state_root=parent.state_root if use_parent else block.state_root, tx_list_root=trie.BLANK_ROOT, receipts_root=trie.BLANK_ROOT, bloom=0, difficulty=block.difficulty, mixhash='', number=parent.number + 1, gas_limit=block.gas_limit, gas_used=0, timestamp=block.timestamp, extra_data=block.extra_data, nonce=b'') block = Block(header, [], [], env=parent.env if use_parent else block.env, parent=parent, making=True) block.ancestor_hashes = [parent.hash] + parent.ancestor_hashes block.log_listeners = parent.log_listeners return block
def hash_array(arr): o = '' for x in arr: if isinstance(x, (int, long)): x = utils.zpad(utils.encode_int(x), 32) o += x return utils.big_endian_to_int(utils.sha3(o))
def register_secret(self, secret): """ Handle a secret that could be received from a Secret message or a ChannelSecretRevealed event. """ hashlock = sha3(secret) channels_reveal = self.hashlock_channel[hashlock] secret_message = Secret(secret) self.raiden.sign(secret_message) while channels_reveal: reveal_to = channels_reveal.pop() # send the secret to all channels registered, including the next # hop that might be the node that informed us about the secret self.raiden.send(reveal_to.partner_state.address, secret_message) # update the channel by claiming the locked transfers try: reveal_to.claim_locked(secret) except InvalidSecret: log.error('claiming lock failed') assert len(self.hashlock_channel[hashlock]) == 0 del self.hashlock_channel[hashlock]
def __init__(self, genesis, key, network, env, time_offset=5): # Create a chain object self.chain = Chain(genesis, env=env) # Use the validator's time as the chain's time self.chain.time = lambda: self.get_timestamp() # My private key self.key = key # My address self.address = privtoaddr(key) # My randao self.randao = RandaoManager(sha3(self.key)) # Pointer to the test p2p network self.network = network # Record of objects already received and processed self.received_objects = {} # The minimum eligible timestamp given a particular number of skips self.next_skip_count = 0 self.next_skip_timestamp = 0 # This validator's indices in the state self.indices = None # Code that verifies signatures from this validator self.validation_code = generate_validation_code(privtoaddr(key)) # Parents that this validator has already built a block on self.used_parents = {} # This validator's clock offset (for testing purposes) self.time_offset = random.randrange(time_offset) - (time_offset // 2) # Give this validator a unique ID self.id = len(ids) ids.append(self.id) self.find_my_indices() self.cached_head = self.chain.head_hash
def create_and_distribute_token(client, receivers, amount_per_receiver=1000, name=None, gasprice=denoms.shannon * 20, timeout=120): """Create a new ERC-20 token and distribute it among `receivers`. If `name` is None, the name will be derived from hashing all receivers. """ name = name or sha3(''.join(receivers)).encode('hex') token_proxy = client.deploy_solidity_contract( client.sender, 'HumanStandardToken', compile_file(get_contract_path('HumanStandardToken.sol')), dict() ( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper() # symbol ), gasprice=gasprice, timeout=timeout ) for receiver in receivers: token_proxy.transfer(receiver, amount_per_receiver) return token_proxy.address.encode('hex')
def _run(self): # pylint: disable=method-hidden transfer = self.originating_transfer assetmanager = self.transfermanager.assetmanager raiden = assetmanager.raiden transfer_details = '{} -> {} hash:{}'.format( pex(transfer.target), pex(transfer.initiator), pex(transfer.hash), ) log.debug('END MEDIATED TRANSFER {}'.format(transfer_details)) secret_request = SecretRequest(transfer.lock.hashlock) raiden.sign(secret_request) raiden.send(transfer.initiator, secret_request) self.event = AsyncResult() response = self.event.wait(raiden.config['msg_timeout']) if response is None: log.error('SECRETREQUEST TIMED OUT!') self.transfermanager.on_hashlock_result(transfer.hashlock, False) return if not isinstance(response, Secret): raise Exception('Invalid message received.') if sha3(response.secret) != transfer.lock.hashlock: raise Exception('Invalid secret received.') # update all channels and propagate the secret assetmanager.register_secret(response.secret) self.transfermanager.on_hashlock_result(transfer.lock.hashlock, True)
def create_node_configuration(miner=True, port=30301, rpcport=8101, host='127.0.0.1', node_key_seed=0): """ Create configuration (ports, keys, etc...) for one node. :param miner: if True, setup to be a mining node :param port: the p2p port to assign :param rpcport: the port to assign :param host: the host for the node to run on :return: node configuration dict """ node = dict() if miner: node['minerthreads'] = 1 # conservative node['unlock'] = 0 node['nodekey'] = sha3('node:{}'.format(node_key_seed)) node['nodekeyhex'] = encode_hex(node['nodekey']) node['pub'] = encode_hex(privtopub_enode(node['nodekey'])) node['address'] = privatekey_to_address(node['nodekey']) node['host'] = host node['port'] = port node['rpcport'] = rpcport node['enode'] = 'enode://{pub}@{host}:{port}'.format(**node) return node
def init_from_parent(cls, parent, coinbase, nonce=b'', extra_data=b'', timestamp=int(time.time()), uncles=[]): """Create a new block based on a parent block. The block will not include any transactions and will not be finalized. """ header = BlockHeader(prevhash=parent.hash, uncles_hash=utils.sha3(rlp.encode(uncles)), coinbase=coinbase, state_root=parent.state_root, tx_list_root=trie.BLANK_ROOT, receipts_root=trie.BLANK_ROOT, bloom=0, difficulty=calc_difficulty(parent, timestamp), mixhash='', number=parent.number + 1, gas_limit=calc_gaslimit(parent), gas_used=0, timestamp=timestamp, extra_data=extra_data, nonce=nonce) block = Block(header, [], uncles, db=parent.db, parent=parent, making=True) block.ancestor_hashes = [parent.hash] + parent.ancestor_hashes return block
import signal from subprocess import Popen, PIPE from ethereum.utils import denoms, sha3, privtoaddr, encode_hex from devp2p.crypto import privtopub as privtopub_enode # DEFAULTS NUM_GETH_NODES = 3 NUM_RAIDEN_ACCOUNTS = 10 CLUSTER_NAME = 'raiden' RAIDEN_PORT = 40001 DEFAULT_PW = 'notsosecret' # a list of `num_raiden_accounts` account addresses with a predictable privkey: # privkey = sha3('127.0.0.1:`raiden_port + i`') DEFAULTACCOUNTS = [ encode_hex(privtoaddr(sha3('127.0.0.1:{}'.format(RAIDEN_PORT + i)))) for i in range(NUM_RAIDEN_ACCOUNTS) ] # default args to pass to `geth` for all calls, e.g. verbosity, ... DEFAULT_ARGS = [ '--nodiscover', '--rpc', '--networkid {}'.format(sum(ord(c) for c in CLUSTER_NAME)), ] # the node specific arguments to pass to `geth` that will be extracted from a # 'node configuration' NODE_CONFIG = [ 'nodekeyhex', 'port',
def merkle_hash(self): return utils.sha3(self.hash + self.sig1 + self.sig2)
def get_empty_merkle_tree_hash(depth): zeroes_hash = NULL_HASH for _ in range(depth): zeroes_hash = u.sha3(zeroes_hash + zeroes_hash) return zeroes_hash
from ethereum.pow import chain from ethereum.transactions import Transaction from ethereum.consensus_strategy import get_consensus_strategy from ethereum.config import config_homestead, config_tangerine, config_spurious, config_metropolis, default_config, Env from ethereum.pow.ethpow import Miner from ethereum.messages import apply_transaction from ethereum.common import verify_execution_results, mk_block_from_prevstate, set_execution_results from ethereum.meta import make_head_candidate from ethereum.abi import ContractTranslator import rlp # Initialize accounts accounts = [] keys = [] for account_number in range(10): keys.append(sha3(to_string(account_number))) accounts.append(privtoaddr(keys[-1])) k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 = keys[:10] a0, a1, a2, a3, a4, a5, a6, a7, a8, a9 = accounts[:10] base_alloc = {} minimal_alloc = {} for a in accounts: base_alloc[a] = {'balance': 10**18} for i in range(1, 9): base_alloc[int_to_addr(i)] = {'balance': 1} minimal_alloc[int_to_addr(i)] = {'balance': 1} minimal_alloc[accounts[0]] = {'balance': 10**18} # Initialize languages
import random from toshi.log import configure_logger, log_unhandled_exceptions from toshi.ethereum.utils import data_decoder from ethereum.utils import sha3 from ethereum.abi import decode_abi, process_type, decode_single from toshi.utils import parse_int from toshieth.collectibles.base import CollectiblesTaskManager from urllib.parse import urlparse from tornado.httpclient import AsyncHTTPClient from tornado.escape import json_decode log = logging.getLogger("toshieth.fungible") ASSET_CREATED_TOPIC = "0xa34547120a941eab43859acf535a121237e5536fd476dccda8174fb1af6926ed" ASSET_TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" TOKEN_URI_CALL_DATA = "0x" + sha3("tokenURI()")[:4].hex() + "0" * 56 NAME_CALL_DATA = "0x" + sha3("name()")[:4].hex() + "0" * 56 CREATOR_CALL_DATA = "0x" + sha3("creator()")[:4].hex() + "0" * 56 TOTAL_SUPPLY_CALL_DATA = "0x" + sha3("totalSupply()")[:4].hex() + "0" * 56 class FungibleCollectibleTaskManager(CollectiblesTaskManager): def __init__(self): super().__init__() configure_logger(log) self._processing = {} self._queue = set() async def process_block(self, blocknumber=None): async with self.pool.acquire() as con:
def get_state_variable_from_storage(self, address, params=[]): (position, length, mappings) = (0, 1, []) try: if params[0] == "mapping": if len(params) < 3: raise CriticalError("Invalid number of parameters.") position = int(params[1]) position_formatted = utils.zpad( utils.int_to_big_endian(position), 32) for i in range(2, len(params)): key = bytes(params[i], 'utf8') key_formatted = utils.rzpad(key, 32) mappings.append( int.from_bytes(utils.sha3(key_formatted + position_formatted), byteorder='big')) length = len(mappings) if length == 1: position = mappings[0] else: if len(params) >= 4: raise CriticalError("Invalid number of parameters.") if len(params) >= 1: position = int(params[0]) if len(params) >= 2: length = int(params[1]) if len(params) == 3 and params[2] == "array": position_formatted = utils.zpad( utils.int_to_big_endian(position), 32) position = int.from_bytes(utils.sha3(position_formatted), byteorder='big') except ValueError: raise CriticalError( "Invalid storage index. Please provide a numeric value.") outtxt = [] try: if length == 1: outtxt.append("{}: {}".format( position, self.eth.eth_getStorageAt(address, position))) else: if len(mappings) > 0: for i in range(0, len(mappings)): position = mappings[i] outtxt.append("{}: {}".format( hex(position), self.eth.eth_getStorageAt(address, position))) else: for i in range(position, position + length): outtxt.append("{}: {}".format( hex(i), self.eth.eth_getStorageAt(address, i))) except FileNotFoundError as e: raise CriticalError("IPC error: " + str(e)) except ConnectionError as e: raise CriticalError( "Could not connect to RPC server. Make sure that your node is running and that RPC parameters are set correctly." ) return '\n'.join(outtxt)
def decodeABI(tinput, sig, returnVals): abi = tinput[2:] hash = utils.sha3(sig)[:4].encode('hex') if abi[:8] != hash: return None return decode_abi(returnVals, abi[8:].decode('hex'))
from devp2p.app import BaseApp from devp2p.discovery import NodeDiscovery from devp2p.peermanager import PeerManager from devp2p.service import BaseService from ethereum.utils import encode_hex, decode_hex, sha3, privtopub from casper import __version__ slogging.PRINT_FORMAT = '%(asctime)s %(name)s:%(levelname).1s\t%(message)s' log = slogging.get_logger('app') services = [ NodeDiscovery, PeerManager, DBService, AccountsService, ChainService, CasperService ] privkeys = [encode_hex(sha3(i)) for i in range(100, 200)] pubkeys = [encode_hex(privtopub(decode_hex(k))[1:]) for k in privkeys] class Casper(BaseApp): client_name = 'casper' client_version = '%s/%s/%s' % (__version__, sys.platform, 'py%d.%d.%d' % sys.version_info[:3]) client_version_string = '%s/v%s' % (client_name, client_version) start_console = False default_config = dict(BaseApp.default_config) default_config['client_version_string'] = client_version_string default_config['post_app_start_callback'] = None script_globals = {}
from ethereum.tools import tester from ethereum.utils import sha3, normalize_address c = tester.Chain() x = c.contract(open('rando.v.py').read(), l='viper') for i in range(10): x.deposit(sender=tester.keys[i], value=(i + 1) * 10**15) c.mine(1) o = [0] * 10 for i in range(550): addr = normalize_address(x.random_select(sha3(str(i)))) o[tester.accounts.index(addr)] += 1 for i, v in enumerate(o): ev = 10 * (i + 1) if not ev - 4 * ev**0.5 < v < ev + 4 * ev**0.5: raise Exception( "More than four standard deviations away; something is wrong: %.2f %d %.2f" % (ev - 4 * ev**0.5, v, ev + 4 * ev**0.5)) print(o)
# Author: Florian Tramer import glob import unittest from ethereum import utils from os.path import basename from utils.pyethereum_test_utils import PyEthereumTestCase, bytes_to_int, int_to_bytes # Base path to contracts from current directory PATH_TO_CONTRACTS = "" log_sigs = { 'Transfer': bytes_to_int(utils.sha3("Transfer(address,address,uint256)")), 'Approval': bytes_to_int(utils.sha3("Approval(address,address,uint256)")) } class TestERC20Flo(PyEthereumTestCase): def test_all(self): self.assertEqual(self.c.totalSupply(), 0, "Token not initially empty") orig_balance0 = self.s.head_state.get_balance(self.t.a0) orig_balance1 = self.s.head_state.get_balance(self.t.a1) self.c.deposit(sender=self.t.k0, value=1000) self.check_logs([log_sigs['Transfer'], 0, bytes_to_int(self.t.a0)], int_to_bytes(1000)) new_balance0 = self.s.head_state.get_balance(self.t.a0)
def get(self, k): return self.trie.get(utils.sha3(k))
def _run(self): # pylint: disable=method-hidden,too-many-locals tokenswap = self.tokenswap raiden = self.raiden identifier = tokenswap.identifier from_token = tokenswap.from_token from_amount = tokenswap.from_amount to_token = tokenswap.to_token to_amount = tokenswap.to_amount to_nodeaddress = tokenswap.to_nodeaddress from_graph = raiden.token_to_channelgraph[from_token] to_graph = raiden.token_to_channelgraph[to_token] from_routes = get_best_routes( from_graph, raiden.protocol.nodeaddresses_networkstatuses, raiden.address, to_nodeaddress, from_amount, previous_address=None, ) fee = 0 for route in from_routes: # for each new path a new secret must be used secret = sha3(hex(random.getrandbits(256))) hashlock = sha3(secret) from_channel = from_graph.get_channel_by_contract_address(route.channel_address) raiden.greenlet_task_dispatcher.register_task(self, hashlock) raiden.register_channel_for_hashlock(from_token, from_channel, hashlock) lock_expiration = ( raiden.get_block_number() + from_channel.settle_timeout - raiden.config['reveal_timeout'] ) from_mediated_transfer = from_channel.create_mediatedtransfer( raiden.address, to_nodeaddress, fee, from_amount, identifier, lock_expiration, hashlock, ) raiden.sign(from_mediated_transfer) from_channel.register_transfer( raiden.get_block_number(), from_mediated_transfer, ) # wait for the SecretRequest and MediatedTransfer to_mediated_transfer = self.send_and_wait_valid_state( raiden, route.node_address, to_nodeaddress, from_mediated_transfer, to_token, to_amount, ) if to_mediated_transfer is None: # the initiator can unregister right away since it knows the # secret wont be revealed raiden.greenlet_task_dispatcher.unregister_task(self, hashlock, False) elif isinstance(to_mediated_transfer, MediatedTransfer): to_hop = to_mediated_transfer.sender to_channel = to_graph.partneraddress_to_channel[to_hop] to_channel.register_transfer( raiden.get_block_number(), to_mediated_transfer, ) raiden.register_channel_for_hashlock(to_token, to_channel, hashlock) # A swap is composed of two mediated transfers, we need to # reveal the secret to both, since the maker is one of the ends # we just need to send the reveal secret directly to the taker. reveal_secret = RevealSecret(secret) raiden.sign(reveal_secret) raiden.send_async(to_nodeaddress, reveal_secret) from_channel.register_secret(secret) # Register the secret with the to_channel and send the # RevealSecret message to the node that is paying the to_token # (this node might, or might not be the same as the taker), # then wait for the withdraw. raiden.handle_secret( identifier, to_token, secret, None, hashlock, ) to_channel = to_graph.partneraddress_to_channel[to_mediated_transfer.sender] self._wait_for_unlock_or_close( raiden, to_graph, to_channel, to_mediated_transfer, ) # unlock the from_token and optimistically reveal the secret # forward raiden.handle_secret( identifier, from_token, secret, None, hashlock, ) raiden.greenlet_task_dispatcher.unregister_task(self, hashlock, True) self.async_result.set(True) return if log.isEnabledFor(logging.DEBUG): node_address = raiden.address log.debug( 'MAKER TOKEN SWAP FAILED initiator:%s to_nodeaddress:%s', pex(node_address), pex(to_nodeaddress), ) # all routes failed self.async_result.set(False)
def _store_account_address(self, address): """ get block transaction receipts by block header hash & number """ address_key = address_prefix + utils.sha3(address) self.wb.put(address_key, address)
def vm_execute(ext, msg, code): # precompute trace flag # if we trace vm, we're in slow mode anyway trace_vm = log_vm_op.is_active('trace') # Initialize stack, memory, program counter, etc compustate = Compustate(gas=msg.gas) stk = compustate.stack mem = compustate.memory # Compute jumpdest_mask, pushcache = preprocess_code(code) codelen = len(code) # For tracing purposes op = None steps = 0 _prevop = None # for trace only while compustate.pc < codelen: opcode = safe_ord(code[compustate.pc]) # Invalid operation if opcode not in opcodes.opcodes: return vm_exception('INVALID OP', opcode=opcode) op, in_args, out_args, fee = opcodes.opcodes[opcode] # out of gas error if fee > compustate.gas: return vm_exception('OUT OF GAS') # empty stack error if in_args > len(compustate.stack): return vm_exception('INSUFFICIENT STACK', op=op, needed=to_string(in_args), available=to_string(len(compustate.stack))) # overfull stack error if len(compustate.stack) - in_args + out_args > 1024: return vm_exception('STACK SIZE LIMIT EXCEEDED', op=op, pre_height=to_string(len(compustate.stack))) # Apply operation compustate.gas -= fee compustate.pc += 1 # Tracing if trace_vm: """ This diverges from normal logging, as we use the logging namespace only to decide which features get logged in 'eth.vm.op' i.e. tracing can not be activated by activating a sub like 'eth.vm.op.stack' """ trace_data = {} trace_data['stack'] = list(map(to_string, list(compustate.stack))) if _prevop in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL', 'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY', 'EXTCODECOPY'): if len(compustate.memory) < 1024: trace_data['memory'] = \ ''.join([encode_hex(ascii_chr(x)) for x in compustate.memory]) else: trace_data['sha3memory'] = \ encode_hex(utils.sha3(b''.join([ascii_chr(x) for x in compustate.memory]))) if _prevop in ('SSTORE', ) or steps == 0: trace_data['storage'] = ext.log_storage(msg.to) trace_data['gas'] = to_string(compustate.gas + fee) trace_data['inst'] = opcode trace_data['pc'] = to_string(compustate.pc - 1) if steps == 0: trace_data['depth'] = msg.depth trace_data['address'] = msg.to trace_data['steps'] = steps trace_data['depth'] = msg.depth if op[:4] == 'PUSH': trace_data['pushvalue'] = pushcache[compustate.pc - 1] log_vm_op.trace('vm', op=op, **trace_data) steps += 1 _prevop = op # Valid operations # Pushes first because they are very frequent if 0x60 <= opcode <= 0x7f: stk.append(pushcache[compustate.pc - 1]) compustate.pc += opcode - 0x5f # Move 1 byte forward for 0x60, up to 32 bytes for 0x7f # Arithmetic elif opcode < 0x10: if op == 'STOP': return peaceful_exit('STOP', compustate.gas, []) elif op == 'ADD': stk.append((stk.pop() + stk.pop()) & TT256M1) elif op == 'SUB': stk.append((stk.pop() - stk.pop()) & TT256M1) elif op == 'MUL': stk.append((stk.pop() * stk.pop()) & TT256M1) elif op == 'DIV': s0, s1 = stk.pop(), stk.pop() stk.append(0 if s1 == 0 else s0 // s1) elif op == 'MOD': s0, s1 = stk.pop(), stk.pop() stk.append(0 if s1 == 0 else s0 % s1) elif op == 'SDIV': s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop()) stk.append(0 if s1 == 0 else (abs(s0) // abs(s1) * (-1 if s0 * s1 < 0 else 1)) & TT256M1) elif op == 'SMOD': s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop()) stk.append(0 if s1 == 0 else (abs(s0) % abs(s1) * (-1 if s0 < 0 else 1)) & TT256M1) elif op == 'ADDMOD': s0, s1, s2 = stk.pop(), stk.pop(), stk.pop() stk.append((s0 + s1) % s2 if s2 else 0) elif op == 'MULMOD': s0, s1, s2 = stk.pop(), stk.pop(), stk.pop() stk.append((s0 * s1) % s2 if s2 else 0) elif op == 'EXP': base, exponent = stk.pop(), stk.pop() # fee for exponent is dependent on its bytes # calc n bytes to represent exponent nbytes = len(utils.encode_int(exponent)) expfee = nbytes * opcodes.GEXPONENTBYTE if ext.post_spurious_dragon_hardfork(): expfee += opcodes.EXP_SUPPLEMENTAL_GAS * nbytes if compustate.gas < expfee: compustate.gas = 0 return vm_exception('OOG EXPONENT') compustate.gas -= expfee stk.append(pow(base, exponent, TT256)) elif op == 'SIGNEXTEND': s0, s1 = stk.pop(), stk.pop() if s0 <= 31: testbit = s0 * 8 + 7 if s1 & (1 << testbit): stk.append(s1 | (TT256 - (1 << testbit))) else: stk.append(s1 & ((1 << testbit) - 1)) else: stk.append(s1) # Comparisons elif opcode < 0x20: if op == 'LT': stk.append(1 if stk.pop() < stk.pop() else 0) elif op == 'GT': stk.append(1 if stk.pop() > stk.pop() else 0) elif op == 'SLT': s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop()) stk.append(1 if s0 < s1 else 0) elif op == 'SGT': s0, s1 = utils.to_signed(stk.pop()), utils.to_signed(stk.pop()) stk.append(1 if s0 > s1 else 0) elif op == 'EQ': stk.append(1 if stk.pop() == stk.pop() else 0) elif op == 'ISZERO': stk.append(0 if stk.pop() else 1) elif op == 'AND': stk.append(stk.pop() & stk.pop()) elif op == 'OR': stk.append(stk.pop() | stk.pop()) elif op == 'XOR': stk.append(stk.pop() ^ stk.pop()) elif op == 'NOT': stk.append(TT256M1 - stk.pop()) elif op == 'BYTE': s0, s1 = stk.pop(), stk.pop() if s0 >= 32: stk.append(0) else: stk.append((s1 // 256**(31 - s0)) % 256) # SHA3 and environment info elif opcode < 0x40: if op == 'SHA3': s0, s1 = stk.pop(), stk.pop() compustate.gas -= opcodes.GSHA3WORD * (utils.ceil32(s1) // 32) if compustate.gas < 0: return vm_exception('OOG PAYING FOR SHA3') if not mem_extend(mem, compustate, op, s0, s1): return vm_exception('OOG EXTENDING MEMORY') data = bytearray_to_bytestr(mem[s0:s0 + s1]) stk.append(utils.big_endian_to_int(utils.sha3(data))) elif op == 'ADDRESS': stk.append(utils.coerce_to_int(msg.to)) elif op == 'BALANCE': if ext.post_anti_dos_hardfork(): if not eat_gas(compustate, opcodes.BALANCE_SUPPLEMENTAL_GAS): return vm_exception("OUT OF GAS") addr = utils.coerce_addr_to_hex(stk.pop() % 2**160) stk.append(ext.get_balance(addr)) elif op == 'ORIGIN': stk.append(utils.coerce_to_int(ext.tx_origin)) elif op == 'CALLER': stk.append(utils.coerce_to_int(msg.sender)) elif op == 'CALLVALUE': stk.append(msg.value) elif op == 'CALLDATALOAD': stk.append(msg.data.extract32(stk.pop())) elif op == 'CALLDATASIZE': stk.append(msg.data.size) elif op == 'CALLDATACOPY': mstart, dstart, size = stk.pop(), stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, mstart, size): return vm_exception('OOG EXTENDING MEMORY') if not data_copy(compustate, size): return vm_exception('OOG COPY DATA') msg.data.extract_copy(mem, mstart, dstart, size) elif op == 'CODESIZE': stk.append(codelen) elif op == 'CODECOPY': mstart, dstart, size = stk.pop(), stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, mstart, size): return vm_exception('OOG EXTENDING MEMORY') if not data_copy(compustate, size): return vm_exception('OOG COPY DATA') for i in range(size): if dstart + i < codelen: mem[mstart + i] = safe_ord(code[dstart + i]) else: mem[mstart + i] = 0 elif op == 'RETURNDATACOPY': mstart, dstart, size = stk.pop(), stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, mstart, size): return vm_exception('OOG EXTENDING MEMORY') if not data_copy(compustate, size): return vm_exception('OOG COPY DATA') if dstart + size > len(compustate.last_returned): return vm_exception('RETURNDATACOPY out of range') mem[mstart:mstart + size] = compustate.last_returned elif op == 'RETURNDATASIZE': stk.append(len(compustate.last_returned)) elif op == 'GASPRICE': stk.append(ext.tx_gasprice) elif op == 'EXTCODESIZE': if ext.post_anti_dos_hardfork(): if not eat_gas(compustate, opcodes.EXTCODELOAD_SUPPLEMENTAL_GAS): return vm_exception("OUT OF GAS") addr = utils.coerce_addr_to_hex(stk.pop() % 2**160) stk.append(len(ext.get_code(addr) or b'')) elif op == 'EXTCODECOPY': if ext.post_anti_dos_hardfork(): if not eat_gas(compustate, opcodes.EXTCODELOAD_SUPPLEMENTAL_GAS): return vm_exception("OUT OF GAS") addr = utils.coerce_addr_to_hex(stk.pop() % 2**160) start, s2, size = stk.pop(), stk.pop(), stk.pop() extcode = ext.get_code(addr) or b'' assert utils.is_string(extcode) if not mem_extend(mem, compustate, op, start, size): return vm_exception('OOG EXTENDING MEMORY') if not data_copy(compustate, size): return vm_exception('OOG COPY DATA') for i in range(size): if s2 + i < len(extcode): mem[start + i] = safe_ord(extcode[s2 + i]) else: mem[start + i] = 0 # Block info elif opcode < 0x50: if op == 'BLOCKHASH': if ext.post_metropolis_hardfork() and False: bh_addr = ext.blockhash_store stk.append(ext.get_storage_data(bh_addr, stk.pop())) else: stk.append( utils.big_endian_to_int(ext.block_hash(stk.pop()))) elif op == 'COINBASE': stk.append(utils.big_endian_to_int(ext.block_coinbase)) elif op == 'TIMESTAMP': stk.append(ext.block_timestamp) elif op == 'NUMBER': stk.append(ext.block_number) elif op == 'DIFFICULTY': stk.append(ext.block_difficulty) elif op == 'GASLIMIT': stk.append(ext.block_gas_limit) # VM state manipulations elif opcode < 0x60: if op == 'POP': stk.pop() elif op == 'MLOAD': s0 = stk.pop() if not mem_extend(mem, compustate, op, s0, 32): return vm_exception('OOG EXTENDING MEMORY') stk.append(utils.bytes_to_int(mem[s0:s0 + 32])) elif op == 'MSTORE': s0, s1 = stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, s0, 32): return vm_exception('OOG EXTENDING MEMORY') mem[s0:s0 + 32] = utils.encode_int32(s1) elif op == 'MSTORE8': s0, s1 = stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, s0, 1): return vm_exception('OOG EXTENDING MEMORY') mem[s0] = s1 % 256 elif op == 'SLOAD': if ext.post_anti_dos_hardfork(): if not eat_gas(compustate, opcodes.SLOAD_SUPPLEMENTAL_GAS): return vm_exception("OUT OF GAS") stk.append(ext.get_storage_data(msg.to, stk.pop())) elif op == 'SSTORE': s0, s1 = stk.pop(), stk.pop() if msg.static: return vm_exception( 'Cannot SSTORE inside a static context') if ext.get_storage_data(msg.to, s0): gascost = opcodes.GSTORAGEMOD if s1 else opcodes.GSTORAGEKILL refund = 0 if s1 else opcodes.GSTORAGEREFUND else: gascost = opcodes.GSTORAGEADD if s1 else opcodes.GSTORAGEMOD refund = 0 if compustate.gas < gascost: return vm_exception('OUT OF GAS') compustate.gas -= gascost ext.add_refund( refund) # adds neg gascost as a refund if below zero ext.set_storage_data(msg.to, s0, s1) elif op == 'JUMP': compustate.pc = stk.pop() if compustate.pc >= codelen or not ( (1 << compustate.pc) & jumpdest_mask): return vm_exception('BAD JUMPDEST') elif op == 'JUMPI': s0, s1 = stk.pop(), stk.pop() if s1: compustate.pc = s0 if compustate.pc >= codelen or not ( (1 << compustate.pc) & jumpdest_mask): return vm_exception('BAD JUMPDEST') elif op == 'PC': stk.append(compustate.pc - 1) elif op == 'MSIZE': stk.append(len(mem)) elif op == 'GAS': stk.append(compustate.gas) # AFTER subtracting cost 1 # DUPn (eg. DUP1: a b c -> a b c c, DUP3: a b c -> a b c a) elif op[:3] == 'DUP': stk.append( stk[0x7f - opcode] ) # 0x7f - opcode is a negative number, -1 for 0x80 ... -16 for 0x8f # SWAPn (eg. SWAP1: a b c d -> a b d c, SWAP3: a b c d -> d b c a) elif op[:4] == 'SWAP': temp = stk[ 0x8e - opcode] # 0x8e - opcode is a negative number, -2 for 0x90 ... -17 for 0x9f stk[0x8e - opcode] = stk[-1] stk[-1] = temp # Logs (aka "events") elif op[:3] == 'LOG': """ 0xa0 ... 0xa4, 32/64/96/128/160 + len(data) gas a. Opcodes LOG0...LOG4 are added, takes 2-6 stack arguments MEMSTART MEMSZ (TOPIC1) (TOPIC2) (TOPIC3) (TOPIC4) b. Logs are kept track of during tx execution exactly the same way as suicides (except as an ordered list, not a set). Each log is in the form [address, [topic1, ... ], data] where: * address is what the ADDRESS opcode would output * data is mem[MEMSTART: MEMSTART + MEMSZ] * topics are as provided by the opcode c. The ordered list of logs in the transaction are expressed as [log0, log1, ..., logN]. """ depth = int(op[3:]) mstart, msz = stk.pop(), stk.pop() topics = [stk.pop() for x in range(depth)] compustate.gas -= msz * opcodes.GLOGBYTE if msg.static: return vm_exception('Cannot LOG inside a static context') if not mem_extend(mem, compustate, op, mstart, msz): return vm_exception('OOG EXTENDING MEMORY') data = bytearray_to_bytestr(mem[mstart:mstart + msz]) ext.log(msg.to, topics, data) log_log.trace('LOG', to=msg.to, topics=topics, data=list(map(utils.safe_ord, data))) # print('LOG', msg.to, topics, list(map(ord, data))) # Create a new contract elif op == 'CREATE': value, mstart, msz = stk.pop(), stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, mstart, msz): return vm_exception('OOG EXTENDING MEMORY') if msg.static: return vm_exception('Cannot CREATE inside a static context') if ext.get_balance(msg.to) >= value and msg.depth < MAX_DEPTH: cd = CallData(mem, mstart, msz) ingas = compustate.gas if ext.post_anti_dos_hardfork(): ingas = all_but_1n(ingas, opcodes.CALL_CHILD_LIMIT_DENOM) create_msg = Message(msg.to, b'', value, ingas, cd, msg.depth + 1) o, gas, addr = ext.create(create_msg) if o: stk.append(utils.coerce_to_int(addr)) else: stk.append(0) compustate.gas = compustate.gas - ingas + gas else: stk.append(0) # Calls elif op in ('CALL', 'CALLCODE', 'DELEGATECALL', 'STATICCALL'): # Pull arguments from the stack if op in ('CALL', 'CALLCODE'): gas, to, value, meminstart, meminsz, memoutstart, memoutsz = \ stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop() else: gas, to, meminstart, meminsz, memoutstart, memoutsz = \ stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop(), stk.pop() value = 0 # Static context prohibition if msg.static and value > 0 and op == 'CALL': return vm_exception( 'Cannot make a non-zero-value call inside a static context' ) # Expand memory if not mem_extend(mem, compustate, op, meminstart, meminsz) or \ not mem_extend(mem, compustate, op, memoutstart, memoutsz): return vm_exception('OOG EXTENDING MEMORY') to = utils.int_to_addr(to) # Extra gas costs based on various factors extra_gas = 0 # Creating a new account if op == 'CALL' and not ext.account_exists(to) and ( value > 0 or not ext.post_spurious_dragon_hardfork()): extra_gas += opcodes.GCALLNEWACCOUNT # Value transfer if value > 0: extra_gas += opcodes.GCALLVALUETRANSFER # Cost increased from 40 to 700 in Tangerine Whistle if ext.post_anti_dos_hardfork(): extra_gas += opcodes.CALL_SUPPLEMENTAL_GAS # Compute child gas limit if ext.post_anti_dos_hardfork(): if compustate.gas < extra_gas: return vm_exception('OUT OF GAS', needed=extra_gas) gas = min( gas, all_but_1n(compustate.gas - extra_gas, opcodes.CALL_CHILD_LIMIT_DENOM)) else: if compustate.gas < gas + extra_gas: return vm_exception('OUT OF GAS', needed=gas + extra_gas) submsg_gas = gas + opcodes.GSTIPEND * (value > 0) # Verify that there is sufficient balance and depth if ext.get_balance(msg.to) < value or msg.depth >= MAX_DEPTH: compustate.gas -= (gas + extra_gas - submsg_gas) stk.append(0) else: # Subtract gas from parent compustate.gas -= (gas + extra_gas) assert compustate.gas >= 0 cd = CallData(mem, meminstart, meminsz) # Generate the message if op == 'CALL': call_msg = Message(msg.to, to, value, submsg_gas, cd, msg.depth + 1, code_address=to, static=msg.static) elif ext.post_homestead_hardfork() and op == 'DELEGATECALL': call_msg = Message(msg.sender, msg.to, msg.value, submsg_gas, cd, msg.depth + 1, code_address=to, transfers_value=False, static=msg.static) elif ext.post_metropolis_hardfork() and op == 'STATICCALL': call_msg = Message(msg.to, to, value, submsg_gas, cd, msg.depth + 1, code_address=to, static=True) elif op in ('DELEGATECALL', 'STATICCALL'): return vm_exception('OPCODE %s INACTIVE' % op) elif op == 'CALLCODE': call_msg = Message(msg.to, msg.to, value, submsg_gas, cd, msg.depth + 1, code_address=to, static=msg.static) else: raise Exception("Lolwut") # Get result result, gas, data = ext.msg(call_msg) if result == 0: stk.append(0) else: stk.append(1) # Set output memory for i in range(min(len(data), memoutsz)): mem[memoutstart + i] = data[i] compustate.gas += gas compustate.last_returned = bytearray(data) # Return opcode elif op == 'RETURN': s0, s1 = stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, s0, s1): return vm_exception('OOG EXTENDING MEMORY') return peaceful_exit('RETURN', compustate.gas, mem[s0:s0 + s1]) # Revert opcode (Metropolis) elif op == 'REVERT': if not ext.post_metropolis_hardfork(): return vm_exception('Opcode not yet enabled') s0, s1 = stk.pop(), stk.pop() if not mem_extend(mem, compustate, op, s0, s1): return vm_exception('OOG EXTENDING MEMORY') return revert(compustate.gas, mem[s0:s0 + s1]) # SUICIDE opcode (also called SELFDESTRUCT) elif op == 'SUICIDE': if msg.static: return vm_exception('Cannot SUICIDE inside a static context') to = utils.encode_int(stk.pop()) to = ((b'\x00' * (32 - len(to))) + to)[12:] xfer = ext.get_balance(msg.to) if ext.post_anti_dos_hardfork(): extra_gas = opcodes.SUICIDE_SUPPLEMENTAL_GAS + \ (not ext.account_exists(to)) * (xfer > 0 or not ext.post_spurious_dragon_hardfork()) * opcodes.GCALLNEWACCOUNT if not eat_gas(compustate, extra_gas): return vm_exception("OUT OF GAS") ext.set_balance(to, ext.get_balance(to) + xfer) ext.set_balance(msg.to, 0) ext.add_suicide(msg.to) log_msg.debug('SUICIDING', addr=utils.checksum_encode(msg.to), to=utils.checksum_encode(to), xferring=xfer) return peaceful_exit('SUICIDED', compustate.gas, []) return peaceful_exit('CODE OUT OF RANGE', compustate.gas, [])
def web3_sha3(argument): print 'web3_sha3' return '0x' + sha3(argument[2:].decode('hex')).encode('hex')
def random_addr(): priv = utils.sha3(os.urandom(4096)) addr = utils.checksum_encode(utils.privtoaddr(priv)) return priv.hex(), addr
def send_and_wait_valid(self, raiden, mediated_transfer, maker_payer_hop): """ Start the second half of the exchange and wait for the SecretReveal for it. This will send the taker mediated transfer with the maker as a target, once the maker receives the transfer he is expected to send a RevealSecret backwards. """ # the taker cannot discard the transfer since the secret is controlled # by another node (the maker), so we have no option but to wait for a # valid response until the lock expires response_iterator = self._send_and_wait_block( raiden, mediated_transfer.recipient, mediated_transfer, mediated_transfer.lock.expiration, ) # Usually the RevealSecret for the MediatedTransfer from this node to # the maker should arrive first, but depending on the number of hops # and if the maker-path is optimistically revealing the Secret, then # the Secret message might arrive first. secret = None for response in response_iterator: valid_reveal = ( isinstance(response, RevealSecret) and response.hashlock == mediated_transfer.lock.hashlock and response.sender == maker_payer_hop ) valid_refund = ( isinstance(response, RefundTransfer) and response.sender == maker_payer_hop and response.lock.amount == mediated_transfer.lock.amount and response.lock.expiration <= mediated_transfer.lock.expiration and response.token == mediated_transfer.token ) if response is None: log.error( 'TAKER SWAP TIMED OUT node:%s hashlock:%s', pex(raiden.address), pex(mediated_transfer.lock.hashlock), ) return (response, secret) elif isinstance(response, Secret): if sha3(response.secret) != mediated_transfer.lock.hashlock: log.error("Secret doesn't match the hashlock, ignoring.") continue secret = response elif valid_reveal: return (response, secret) elif valid_refund: return (response, secret) elif log.isEnabledFor(logging.ERROR): log.error( 'Invalid message [%s] supplied to the task, ignoring.', repr(response), ) return (None, secret)
def get_deposit_hash(owner, token, value): return u.sha3(owner + token + b'\x00' * 31 + u.int_to_bytes(value))
int_to_addr, zpad, parse_as_bin, parse_as_int, decode_hex, sha3, is_string, is_numeric, ) from rlp.sedes import big_endian_int, Binary, binary, CountableList from ethereum import utils from ethereum import trie from ethereum.trie import Trie from ethereum.securetrie import SecureTrie BLANK_HASH = utils.sha3(b"") BLANK_ROOT = utils.sha3rlp(b"") STATE_DEFAULTS = { "txindex": 0, "gas_used": 0, "gas_limit": 3141592, "block_number": 0, "block_coinbase": "\x00" * 20, "block_difficulty": 1, "timestamp": 0, "logs": [], "receipts": [], "bloom": 0, "suicides": [], "recent_uncles": {},
def confirm_tx(tx, root, key): return sign(u.sha3(tx.hash + root), key)
def _update_root_hash(self): val = rlp_encode(self.root_node) key = utils.sha3(val) self.db.put(key, str_to_bytes(val)) self._root_hash = key
def verify_signature(addr, h, sig): pub = bitcoin.ecdsa_raw_recover(h, sig) # sig=V,R,S pub = bitcoin.encode_pubkey(pub, 'bin') addr_ = utils.sha3(pub[1:])[12:] assert addr_ == addr return True
def _wait_for_unlock_or_close(self, raiden, graph, channel, mediated_transfer): # noqa """ Wait for a Secret message from our partner to update the local state, if the Secret message is not sent within time the channel will be closed. Note: Must be called only once the secret is known. Must call `unregister_task` after this function returns. """ assert graph.token_address == mediated_transfer.token if not isinstance(mediated_transfer, MediatedTransfer): raise ValueError('MediatedTransfer expected.') block_to_close = mediated_transfer.lock.expiration - raiden.config['reveal_timeout'] hashlock = mediated_transfer.lock.hashlock identifier = mediated_transfer.identifier token = mediated_transfer.token while channel.our_state.balance_proof.is_unclaimed(hashlock): current_block = raiden.get_block_number() if current_block > block_to_close: if log.isEnabledFor(logging.WARN): log.warn( 'Closing channel (%s, %s) to prevent expiration of lock %s %s', pex(channel.our_state.address), pex(channel.partner_state.address), pex(hashlock), repr(self), ) channel.external_state.close( channel.partner_state.balance_proof.transfer, ) return try: response = self.response_queue.get( timeout=DEFAULT_EVENTS_POLL_TIMEOUT ) except Empty: pass else: if isinstance(response, Secret): secret = response.secret hashlock = sha3(secret) if response.identifier == identifier and response.token == token: raiden.handle_secret( identifier, graph.token_address, secret, response, hashlock, ) else: # cannot use the message but the secret is okay raiden.handle_secret( identifier, graph.token_address, secret, None, hashlock, ) if log.isEnabledFor(logging.ERROR): log.error( 'Invalid Secret message received, expected message' ' for token=%s identifier=%s received=%s', token, identifier, response, ) elif isinstance(response, RevealSecret): secret = response.secret hashlock = sha3(secret) raiden.handle_secret( identifier, graph.token_address, secret, None, hashlock, ) elif log.isEnabledFor(logging.ERROR): log.error( 'Invalid message ignoring. %s %s', repr(response), repr(self), )
bin = '0x608060405260a060405190810160405280608081526020017f447da3cd62f803c191a7f65e91e582a2c56002c59c6205676b561b7e43dee69d81526020017f889e8a7e4e22cb6ca321f7f0ff29005d1b7aca5f0afa26f88e6bce1d2b4503c881526020017f9ff55640b109eb0ceb6b304c8d1f0b3015d5f656a49df24aae9daeabf06085bf81526020017f3b554dc5628fc3a4b0b1d3849ae8530a415219818afadccc05e40c0c9e19b34181525060009080519060200190620000c49291906200060c565b506000600160006101000a81548160ff0219169083151502179055506103ff60025560a060405190810160405280608081526020017fbd49fe4da96732c03a350fa45cd8ea71fd30d768f08c9bfc896fb03daaf8d3fb81526020017fcf6c9c08fdd65e089ae96db1b0051e9b620a9debffabf1c7f4ce663c1e9740cd81526020017fb1654a9f09a83051a75cadf9869d34a25c7ccfac84f9cda891f0130eb7b98cdf81526020017fba3c1e7d2efcc5c3b328d770989329537c8d56b4a16921ef56594f7406caf94d81525060039080519060200190620001a69291906200060c565b506000600460006101000a81548160ff02191690831515021790555061040060055560a060405190810160405280608081526020017fda04e8c7457591a5f303377378fdf9777bc7f9bb2957458b40107605692fd8a981526020017f38e34c8cc0f63486d375ffc9f17ff170c06b1d9d4d6c40d16bc34b5f145f365981526020017f8c987c624d60c25335b258460f1dcaaa15df44e1c8dff6b556fa5283198956f481526020017f864dbca5ff6a2cb02f551a6e17c45e9efc0b540f21c36d56d6763a188459d8fb81525060069080519060200190620002889291906200060c565b506000600760006101000a81548160ff02191690831515021790555061040060085560606040519081016040528060008054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015620003505780601f10620003245761010080835404028352916020019162000350565b820191906000526020600020905b8154815290600101906020018083116200033257829003601f168201915b50505050508152602001600160009054906101000a900460ff1615158152602001600254815250600960008201518160000190805190602001906200039792919062000693565b5060208201518160010160006101000a81548160ff02191690831515021790555060408201518160020155505060606040519081016040528060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156200046a5780601f106200043e576101008083540402835291602001916200046a565b820191906000526020600020905b8154815290600101906020018083116200044c57829003601f168201915b50505050508152602001600460009054906101000a900460ff1615158152602001600554815250600c6000820151816000019080519060200190620004b192919062000693565b5060208201518160010160006101000a81548160ff02191690831515021790555060408201518160020155505060606040519081016040528060068054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015620005845780601f10620005585761010080835404028352916020019162000584565b820191906000526020600020905b8154815290600101906020018083116200056657829003601f168201915b50505050508152602001600760009054906101000a900460ff1615158152602001600854815250600f6000820151816000019080519060200190620005cb92919062000693565b5060208201518160010160006101000a81548160ff0219169083151502179055506040820151816002015550503480156200060557600080fd5b5062000742565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200064f57805160ff191683800117855562000680565b8280016001018555821562000680579182015b828111156200067f57825182559160200191906001019062000662565b5b5090506200068f91906200071a565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620006d657805160ff191683800117855562000707565b8280016001018555821562000707579182015b8281111562000706578251825591602001919060010190620006e9565b5b5090506200071691906200071a565b5090565b6200073f91905b808211156200073b57600081600090555060010162000721565b5090565b90565b6106c080620007526000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063326cf61c1461005157806358223dc8146100fb575b600080fd5b34801561005d57600080fd5b5061008060048036038101908080356000191690602001909291905050506101f2565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100c05780820151818401526020810190506100a5565b50505050905090810190601f1680156100ed5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561010757600080fd5b5061016c600480360381019080803590602001908201803590602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505050919291929080359060200190929190505050610223565b604051808315151515815260200180602001828103825283818151815260200191508051906020019080838360005b838110156101b657808201518184015260208101905061019b565b50505050905090810190601f1680156101e35780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b6060816040516020018082600019166000191681526020019150506040516020818303038152906040529050919050565b6000606061022f610670565b610237610670565b610361600660006003604051808480546001816001161561010002031660029004801561029b5780601f1061027957610100808354040283529182019161029b565b820191906000526020600020905b815481529060010190602001808311610287575b5050838054600181600116156101000203166002900480156102f45780601f106102d25761010080835404028352918201916102f4565b820191906000526020600020905b8154815290600101906020018083116102e0575b50508280546001816001161561010002031660029004801561034d5780601f1061032b57610100808354040283529182019161034d565b820191906000526020600020905b815481529060010190602001808311610339575b5050935050505060405180910390206101f2565b826000018190525060008260200190151590811515815250508482604001818152505085816000018190525060008160200190151590811515815250508481604001818152505060006103b6838360016104b7565b1415610437577f0b2d8b0c64417145fffc6fbacdebf625b399a33101f3173dd19f63c9928ab3526040518080602001828103825260068152602001807f457175616c21000000000000000000000000000000000000000000000000000081525060200191505060405180910390a160018260000151809050935093506104ae565b7f0b2d8b0c64417145fffc6fbacdebf625b399a33101f3173dd19f63c9928ab35260405180806020018281038252600a8152602001807f4e6f7420457175616c210000000000000000000000000000000000000000000081525060200191505060405180910390a160008260000151809050935093505b50509250929050565b600080600080600080600080600196508815610589578a6020015180156104df575089602001515b1561050c577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9650610588565b600015158b60200151151514801561052c5750600115158a602001511515145b1561053a5760019750610662565b600115158b60200151151514801561055a5750600015158a602001511515145b15610587577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9750610662565b5b5b89604001518b6040015111156105a457866001029750610662565b8a604001518a6040015111156105de57867fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff029750610662565b8a6000015151915060208b5101955060208a51019450600090505b8181101561065d578086015193508085015192508284111561062057866001029750610662565b8383111561065257867fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff029750610662565b6020810190506105f9565b600097505b505050505050509392505050565b606060405190810160405280606081526020016000151581526020016000815250905600a165627a7a723058209ffcbb3cd68c629c839ed1ec686fb031e1dd48d3ed52990269ced068ae7ad6f10029' addr = Web3.toChecksumAddress('0xf3bA0e58C39eEf4e94144fb3a6c10374a25da663') web3, pwd = connect() contract = web3.eth.contract(abi=abi, bytecode=bin, address=addr) p = 153098272504387072266936256155440771844922582242861823323292219309209807318109992190455717597749270325963123403359939192028947724926144342818770586136136126337375436706876614423863264051678326206739626203872223116203206738831155125839612432933059096643057013804321361170650382385182136069811475540151279147259 g = 48095861804730928538428071688224004229592704416264787635743716356958582448226167154685924895443220005707859651277553435409220536317215422963672871914841517783042349761227906722244783116777179995820326154186287286353935949308174273056377987690394866714089833749644657555907806410435558837920979345110898160449 k = 10022446701738583271276071804010446073913280425189472942303437612418862851223244723245226017322005926246813100742541609377103046893136104044015161562561526985453585647020566093167977121428923628169372925889701872928538625011078052920813557913682354018653924330859466163743103828247525446549945542160664745508 h = pow(g, k, p) r = 62555713279948745690349351610356531327032351353192320967421937635293378693946211592624820108119998277825391232074589514501649650827908709815124457628347900961038658650480217718807650468597580969342931489490635246791126151937259525476850522897096329798193623331012272552762850181502944812071200771862243846107 c_val = sha3(int_to_bytes(p) + int_to_bytes(g) + int_to_bytes(h)) c = int.from_bytes(c_val, byteorder='big') hash_eq = contract.functions.hash_equal(int_to_bytes(c_val), count_bitlen(c)) hash_eq.transact() #print("Equal or not ", c_neg) print("Hash Length Solidity", count_bitlen(int.from_bytes(c_sol, byteorder='big'))) print("Hash Length Python", count_bitlen(c)) print("Python c : ", c_val)
def update(self, k, v): h = utils.sha3(k) self.db.put(h, k) self.trie.update(h, v)
def hash(self): return utils.sha3(self.encoded)
def blkhash(n): if n >= ext.block_number or n < ext.block_number - 256: return b'' else: return utils.sha3(to_string(n))
def test_channelmanager(tester_state, tester_token, tester_events, tester_channelmanager_library_address, settle_timeout, netting_channel_abi): # pylint: disable=too-many-locals,too-many-statements address0 = tester.DEFAULT_ACCOUNT address1 = tester.a1 address2 = tester.a2 nonexisting_address = sha3('this_does_not_exist')[:20] channelmanager_path = get_contract_path('ChannelManagerContract.sol') channel_manager = tester_state.abi_contract( None, path=channelmanager_path, language='solidity', constructor_parameters=[tester_token.address], contract_name='ChannelManagerContract', log_listener=tester_events.append, libraries={ 'ChannelManagerLibrary': tester_channelmanager_library_address.encode('hex'), }) participants_count = len(channel_manager.getChannelsParticipants()) assert participants_count == 0, 'newly deployed contract must be empty' netting_channel_translator = ContractTranslator(netting_channel_abi) previous_events = list(tester_events) netting_channel_address1_hex = channel_manager.newChannel( address1, settle_timeout, ) assert len(previous_events) + 1 == len( tester_events), 'ChannelNew event must be fired.' channelnew_event = tester_events[-1] assert channelnew_event == { '_event_type': 'ChannelNew', 'participant1': address0.encode('hex'), 'participant2': address1.encode('hex'), 'netting_channel': netting_channel_address1_hex, 'settle_timeout': settle_timeout, } # should fail if settleTimeout is too low with pytest.raises(TransactionFailed): channel_manager.newChannel(address1, 5) # cannot have two channels at the same time with pytest.raises(TransactionFailed): channel_manager.newChannel(address1, settle_timeout) # should be zero address if there is no channel for the given address assert channel_manager.getChannelWith(nonexisting_address) == '0' * 40 assert len(channel_manager.getChannelsParticipants()) == 2 netting_contract_proxy1 = ABIContract( tester_state, netting_channel_translator, netting_channel_address1_hex, ) assert netting_contract_proxy1.settleTimeout() == settle_timeout previous_events = list(tester_events) netting_channel_address2_hex = channel_manager.newChannel( address2, settle_timeout, ) assert len(previous_events) + 1 == len( tester_events), 'ChannelNew event must be fired.' assert channel_manager.getChannelWith( address1) == netting_channel_address1_hex assert channel_manager.getChannelWith( address2) == netting_channel_address2_hex msg_sender_channels = channel_manager.nettingContractsByAddress( tester.DEFAULT_ACCOUNT) address1_channels = channel_manager.nettingContractsByAddress(address1) nonexisting_channels = channel_manager.nettingContractsByAddress( nonexisting_address) assert len(msg_sender_channels) == 2 assert len(address1_channels) == 1 assert len(nonexisting_channels) == 0 assert len(channel_manager.getChannelsParticipants()) == 4 channelnew_event = tester_events[-1] assert channelnew_event == { '_event_type': 'ChannelNew', 'participant1': address0.encode('hex'), 'participant2': address2.encode('hex'), 'netting_channel': netting_channel_address2_hex, 'settle_timeout': settle_timeout, }
def hash_for_function_signature(sig): return "0x%s" % utils.sha3(sig)[:4].hex()
def delete(self, k): self.trie.delete(utils.sha3(k))