def _send_transaction(self, _from=None, to=None, gas=None, gas_price=None, value=0, data=''): """ The tester doesn't care about gas so we discard it. """ if _from is None: _from = self.get_coinbase() _from = strip_0x(_from) if len(_from) == 40: _from = ethereum_utils.decode_hex(strip_0x(_from)) sender = t.keys[t.accounts.index(_from)] if to is None: to = '' to = ethereum_utils.decode_hex(strip_0x(to)) if data is None: data = '' data = ethereum_utils.decode_hex(strip_0x(data)) return self.evm.send(sender=sender, to=to, value=value, evmdata=data)
def decode_single(typ, data): base, sub, _ = abi.process_type(typ) if base == "address": return "0x" + data[-40:] elif base == "string" or base == "bytes" or base == "hash": if sub: bytes = ethereum_utils.int_to_32bytearray(int(data, 16)) while bytes and bytes[-1] == 0: bytes.pop() if bytes: return "".join(chr(b) for b in bytes) else: num_bytes = int(data[64 + 2 : 128 + 2], 16) bytes_as_hex = data[2 + 128 : 2 + 128 + (2 * num_bytes)] return ethereum_utils.decode_hex(bytes_as_hex) elif base == "uint": return int(data, 16) elif base == "int": o = int(data, 16) return (o - 2 ** int(sub)) if o >= 2 ** (int(sub) - 1) else o elif base == "ureal": raise NotImplementedError("havent gotten to this") high, low = [int(x) for x in sub.split("x")] # return big_endian_to_int(data) * 1.0 / 2 ** low elif base == "real": raise NotImplementedError("havent gotten to this") high, low = [int(x) for x in sub.split("x")] # return (big_endian_to_int(data) * 1.0 / 2 ** low) % 2 ** high elif base == "bool": return bool(int(data, 16)) else: raise ValueError("Unknown base: `{0}`".format(base))
def new_netting_channel(self, peer1, peer2, settle_timeout): """ Creates a new netting contract between peer1 and peer2. Raises: ValueError: If peer1 or peer2 is not a valid address. """ if not isaddress(peer1): raise ValueError('The pee1 must be a valid address') if not isaddress(peer2): raise ValueError('The peer2 must be a valid address') if privatekey_to_address(self.private_key) == peer1: other = peer2 else: other = peer1 netting_channel_address_hex = self.proxy.newChannel(other, settle_timeout) self.tester_state.mine(number_of_blocks=1) channel = NettingChannelTesterMock( self.tester_state, self.private_key, netting_channel_address_hex, ) return decode_hex(channel.address)
def coinbase(self): """Return the address that should be used as coinbase for new blocks. The coinbase address is given by the config field pow.coinbase_hex. If this does not exist or is `None`, the address of the first account is used instead. If there are no accounts, the coinbase is `DEFAULT_COINBASE`. :raises: :exc:`ValueError` if the coinbase is invalid (no string, wrong length) or there is no account for it and the config flag `accounts.check_coinbase` is set (does not apply to the default coinbase) """ cb_hex = self.app.config.get('pow', {}).get('coinbase_hex') if cb_hex is None: if not self.accounts_with_address: return DEFAULT_COINBASE cb = self.accounts_with_address[0].address else: if not is_string(cb_hex): raise ValueError('coinbase must be string') try: cb = decode_hex(remove_0x_head(cb_hex)) except (ValueError, TypeError): raise ValueError('invalid coinbase') if len(cb) != 20: raise ValueError('wrong coinbase length') if self.config['accounts']['must_include_coinbase']: if cb not in (acct.address for acct in self.accounts): raise ValueError('no account for coinbase') return cb
def channel_from_nettingcontract(our_key, netting_contract, external_state, reveal_timeout): """ Create a `channel.Channel` for the `nettnig_contract`. Use this to make sure that both implementation (the smart contract and the python code) work in tandem. """ our_address = privatekey_to_address(our_key) asset_address_hex = netting_contract.assetAddress(sender=our_key) settle_timeout = netting_contract.settleTimeout(sender=our_key) address_balance = netting_contract.addressAndBalance(sender=our_key) address1_hex, balance1, address2_hex, balance2 = address_balance asset_address = decode_hex(asset_address_hex) address1 = decode_hex(address1_hex) address2 = decode_hex(address2_hex) if our_address == address1: our_balance = balance1 partner_address = address2 partner_balance = balance2 else: our_balance = balance2 partner_address = address1 partner_balance = balance1 our_state = ChannelEndState( our_address, our_balance, ) partner_state = ChannelEndState( partner_address, partner_balance, ) channel = Channel( our_state, partner_state, external_state, asset_address, reveal_timeout, settle_timeout, ) return channel
def _get_block_by_hash(self, block_hash): if len(block_hash) > 32: block_hash = ethereum_utils.decode_hex(strip_0x(block_hash)) for block in self.evm.blocks: if block.hash == block_hash: return block else: raise ValueError("Could not find block for provided hash")
def test_send(): privkey = decode_hex('a06bab413912bc24726e266a1f6613944ea30bf3399ae3375ccf7a663b73b625') recipient = '0x25c6e74ff1d928df98137af4df8430df24f07cd7' nonce = 0 amount = 1000000000000000000 gas_price = 100000000000 gas_limit = 30000 tx = send(privkey, nonce, recipient, amount, gas_price, gas_limit) tx_expected = 'f86c8085174876e8008275309425c6e74ff1d928df98137af4df8430df24f07cd7880de0b6b3a7640000801ba03710b1c12686a52ca22a489a7e2323e33cdab723fe174f466d8d7122c5bc65faa077dd10ef5a9f89630aaecf852b2f9e3679c75f98fb39e91275fe76e53948af05' assert tx_expected == tx.hex()
def data_decoder(data): """Decode `data` representing unformatted data.""" if not data.startswith('0x'): data = '0x' + data if len(data) % 2 != 0: raise BadRequestError('Invalid data encoding, must be even length') try: return decode_hex(data[2:]) except TypeError: raise BadRequestError('Invalid data hex encoding', data[2:])
def run(ctx, node_id, console, fake_account): """Start the daemon""" config = ctx.obj['config'] config['node']['privkey_hex'] = privkeys[node_id] config['discovery']['listen_port'] += node_id config['p2p']['listen_port'] += node_id log.info("starting", config=config) if config['node']['data_dir'] and not os.path.exists(config['node']['data_dir']): os.makedirs(config['node']['data_dir']) app = Casper(config) app.start_console = console for service in services: assert issubclass(service, BaseService) assert service.name not in app.services service.register_with_app(app) assert hasattr(app.services, service.name) # If this service is the account service, then attempt to unlock the coinbase if service is AccountsService: # If the fake_account flag is True, create a temparary fake account based on node_id if fake_account: account = Account.new('', decode_hex(privkeys[node_id])) app.services.accounts.add_account(account, store=False) continue unlock_accounts(ctx.obj['unlock'], app.services.accounts, password=ctx.obj['password']) try: app.services.accounts.coinbase except ValueError as e: log.fatal('invalid coinbase', coinbase=config.get('pow', {}).get('coinbase_hex'), error=e.message) sys.exit() # start app log.info('starting') app.start() if ctx.obj['log_file']: log.info("Logging to file %s", ctx.obj['log_file']) # User requested file logging - remove stderr handler root_logger = slogging.getLogger() for hdl in root_logger.handlers: if isinstance(hdl, StreamHandler) and hdl.stream == sys.stderr: root_logger.removeHandler(hdl) break # wait for interrupt evt = Event() gevent.signal(signal.SIGQUIT, evt.set) gevent.signal(signal.SIGTERM, evt.set) evt.wait() # finally stop app.stop()
def test_block_18315_changes(): pre = {} toadd = [ ['0x0000000000000000000000000000000000000000000000000000000000000000', '0xf9e88bc2b3203e764fe67b4d0f4171b7756117c8'], ['0x0000000000000000000000000000000000000000000000000000000000000001', '0x'], ['0x0000000000000000000000000000000000000000000000000000000000000002', '0x'], ] db = RefcountDB(EphemDB()) db.logging = True NODES = 60 t1 = pruning_trie.Trie(db) t2 = pruning_trie.Trie(db) db.ttl = NODES * 2 c = 0 for k, v in pre.items(): triekey = utils.sha3(utils.zpad(k[2:].decode('hex'), 32)) t1.update(triekey, rlp.encode(v[2:].decode('hex'))) t2.update(triekey, rlp.encode(v[2:].decode('hex'))) db.commit_refcount_changes(c) db.cleanup(c) c += 1 sys.stderr.write('##############################\n') print(utils.encode_hex(t1.root_hash)) print(t1.to_dict()) for k, v in toadd: sys.stderr.write('kv: %s %s\n' % (k, v)) triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32)) if v == '0x': t1.delete(triekey) else: t1.update(triekey, rlp.encode(utils.decode_hex(v[2:]))) db.commit_refcount_changes(c) db.cleanup(c) c += 1 t1.clear_all() db.commit_refcount_changes(c) for i in range(db.ttl + 1): db.cleanup(c) c += 1 t3 = pruning_trie.Trie(db) t3.root_hash = t2.root_hash print(t3.to_dict())
def data_decoder(data): """Decode `data` representing unformatted data.""" if not data.startswith('0x'): data = '0x' + data if len(data) % 2 != 0: success = False # must be even length else: try: return decode_hex(data[2:]) except TypeError: success = False assert not success raise BadRequestError('Invalid data encoding')
def data_decoder(data): """Decode `data` representing unformatted data.""" if not data.startswith('0x'): data = '0x' + data if len(data) % 2 != 0: # workaround for missing leading zeros from netstats assert len(data) < 64 + 2 data = '0x' + '0' * (64 - (len(data) - 2)) + data[2:] #raise BadRequestError('Invalid data encoding, must be even length') try: return decode_hex(data[2:]) except TypeError: raise BadRequestError('Invalid data hex encoding', data[2:])
def __init__(self, config, chain, discovery, transport_class=UDPTransport): self.config = config self.discovery = discovery self.transport = transport_class(config['host'], config['port']) self.raiden = RaidenService( chain, decode_hex(config['privatekey_hex']), self.transport, discovery, config, ) self.services = {'raiden': self.raiden} self.start_console = True
def test_block_18503_changes(): pre = {'0x0c': '0x29d33c02a200937995e632c4597b4dca8e503978'} toadd = [ ['0x', '0x09'], ] db = RefcountDB(EphemDB()) db.logging = True NODES = 60 t1 = pruning_trie.Trie(db) t2 = pruning_trie.Trie(db) db.ttl = NODES * 2 c = 0 for k, v in pre.items(): triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32)) t1.update(triekey, rlp.encode(utils.decode_hex(v[2:]))) t2.update(triekey, rlp.encode(utils.decode_hex(v[2:]))) db.commit_refcount_changes(c) db.cleanup(c) c += 1 print(utils.encode_hex(t1.root_hash)) for k, v in toadd: sys.stderr.write('kv: %s %s\n' % (k, v)) triekey = utils.sha3(utils.zpad(utils.decode_hex(k[2:]), 32)) if v == '0x': t1.delete(triekey) else: t1.update(triekey, rlp.encode(utils.decode_hex(v[2:]))) db.commit_refcount_changes(c) db.cleanup(c) c += 1 t1.clear_all() db.commit_refcount_changes(c) for i in range(db.ttl + 1): db.cleanup(c) c += 1 t3 = pruning_trie.Trie(db) t3.root_hash = t2.root_hash print(t3.to_dict())
def _get_transaction_by_hash(self, txn_hash): txn_hash = strip_0x(txn_hash) if len(txn_hash) == 64: txn_hash = ethereum_utils.decode_hex(txn_hash) for block in reversed(self.evm.blocks): txn_hashes = block.get_transaction_hashes() if txn_hash in txn_hashes: txn_index = txn_hashes.index(txn_hash) txn = block.transaction_list[txn_index] break else: raise ValueError("Transaction not found") return block, txn, txn_index
def __init__(self, shard_id=int_to_big_endian(0), prev_state_root=trie.BLANK_ROOT, tx_list_root=trie.BLANK_ROOT, coinbase=sharding_config['GENESIS_COINBASE'], post_state_root=trie.BLANK_ROOT, receipt_root=trie.BLANK_ROOT, children=[], state_branch_node=utils.sha3rlp([]), signatures=[], mixhash='', nonce='', source_block_numeber=int_to_big_endian(0), source_block_hash=utils.sha3rlp([])): fields = {k: v for k, v in locals().items() if k != 'self'} if len(fields['coinbase']) == 40: fields['coinbase'] = decode_hex(fields['coinbase']) assert len(fields['coinbase']) == 20 super(CollationHeader, self).__init__(**fields)
def __init__(self, prevhash=default_config['GENESIS_PREVHASH'], uncles_hash=utils.sha3rlp([]), coinbase=default_config['GENESIS_COINBASE'], state_root=BLANK_ROOT, tx_list_root=BLANK_ROOT, receipts_root=BLANK_ROOT, bloom=0, difficulty=default_config['GENESIS_DIFFICULTY'], number=0, gas_limit=default_config['GENESIS_GAS_LIMIT'], gas_used=0, timestamp=0, extra_data='', mixhash=default_config['GENESIS_MIXHASH'], nonce=''): # at the beginning of a method, locals() is a dict of all arguments fields = {k: v for k, v in locals().items() if k != 'self'} if len(fields['coinbase']) == 40: fields['coinbase'] = decode_hex(fields['coinbase']) assert len(fields['coinbase']) == 20 self.block = None super(BlockHeader, self).__init__(**fields)
def decode_single(typ, data): base, sub, _ = abi.process_type(typ) # ensure that we aren't trying to decode an empty response. assert len(data) > 2 if base == 'address': return '0x' + strip_0x_prefix(data[-40:]) elif base == 'string' or base == 'bytes' or base == 'hash': if sub: bytes = ethereum_utils.int_to_32bytearray(int(data, 16)) while bytes and bytes[-1] == 0: bytes.pop() if bytes: return ''.join(chr(b) for b in bytes) else: num_bytes = int(data[64 + 2:128 + 2], 16) bytes_as_hex = data[2 + 128:2 + 128 + (2 * num_bytes)] return ethereum_utils.decode_hex(bytes_as_hex) elif base == 'uint': return int(data, 16) elif base == 'int': o = int(data, 16) return (o - 2 ** int(sub)) if o >= 2 ** (int(sub) - 1) else o elif base == 'ureal': raise NotImplementedError('havent gotten to this') high, low = [int(x) for x in sub.split('x')] # return big_endian_to_int(data) * 1.0 / 2 ** low elif base == 'real': raise NotImplementedError('havent gotten to this') high, low = [int(x) for x in sub.split('x')] # return (big_endian_to_int(data) * 1.0 / 2 ** low) % 2 ** high elif base == 'bool': return bool(int(data, 16)) else: raise ValueError("Unknown base: `{0}`".format(base))
from web3.auto import w3 from plasma_cash.child_chain.block import Block from plasma_cash.child_chain.transaction import Transaction from plasma_cash.utils.utils import sign import requests blknum = 1 print(blknum) response = requests.get(f'http://localhost:8546/block/{blknum}') # print("statusecode ", response.status_code) # print(type(response.content)) block = rlp.decode(utils.decode_hex(response.content), Block) # print(block) # print("block_hash ", block.hash) for each_tx in block.transaction_set: print("tx hash ", each_tx) print("tx uid ", each_tx.uid) payload = {'blknum': blknum, 'uid': each_tx.uid} r = requests.get('http://localhost:8546/proof', params=payload) # print("proof status code", r.status_code) if r.status_code == 200: print(type(r.content)) # response = requests.get(f'http://{node_address}/chain') # response2 = requests.get(f'http://{node_address}/balance') # if response.status_code == 200:
o += v return o # Run some tests first from ethereum.tools import tester as t t.gas_limit = 1000000 chain = t.Chain() t.s = chain rlp_decoder_address = t.s.tx(to=b'', data=rlp_decoder_bytes) assert t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'\x45', b'\x95'])) == encode_vals([96, 129, 162, 1, b"\x45", 1, b"\x95"]) assert t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'cow', b'dog']))== encode_vals([96, 131, 166, 3, b"cow", 3, b"dog"]) assert t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([]))== encode_vals([32]) assert t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'\x73' * 100, b'dog']))== encode_vals([96, 228, 263, 100, b"\x73" * 100, 3, b"dog"]) assert t.s.tx(sender=t.k0, to=rlp_decoder_address, data=utils.decode_hex('f6943535353535353535353535353535353535353535a04747474747474747474747474747474747474747474747474747474747474747'))== encode_vals([96, 148, 212, 20, b'\x35' * 20, 32, b'\x47' * 32]) print("Checks passed!") t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([])) g1 = t.s.head_state.receipts[-1].gas_used - t.s.head_state.receipts[-2].gas_used - t.s.last_tx.intrinsic_gas_used t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'\x03' * 500])) g2 = t.s.head_state.receipts[-1].gas_used - t.s.head_state.receipts[-2].gas_used - t.s.last_tx.intrinsic_gas_used t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'\x03'] * 25)) g3 = t.s.head_state.receipts[-1].gas_used - t.s.head_state.receipts[-2].gas_used - t.s.last_tx.intrinsic_gas_used t.s.tx(sender=t.k0, to=rlp_decoder_address, data=rlp.encode([b'\x03'] * 24 + [b'\x03' * 500])) g4 = t.s.head_state.receipts[-1].gas_used - t.s.head_state.receipts[-2].gas_used - t.s.last_tx.intrinsic_gas_used print("500 bytes increment: %d" % (g2 - g1)) print("500 bytes increment: %d" % (g4 - g3)) print("25 items increment: %d" % (g3 - g1)) print("25 items increment: %d" % (g4 - g2))
def get_block(self, blknum): encoded_block = self.child_chain.get_block(blknum) return rlp.decode(utils.decode_hex(encoded_block), Block)
def mk_random_privkey(): k = hex(random.getrandbits(256))[2:-1].zfill(64) assert len(k) == 64 return decode_hex(k)
def get_transaction(self, utxo_id): encoded_transaction = self.child_chain.get_transaction(utxo_id) return rlp.decode(utils.decode_hex(encoded_transaction), Transaction)
EXPDIFF_PERIOD=100000, EXPDIFF_FREE_PERIODS=2, # Delay in Byzantium METROPOLIS_DELAY_PERIODS=30, # Blank account initial nonce ACCOUNT_INITIAL_NONCE=0, # Homestead fork HOMESTEAD_FORK_BLKNUM=1150000, HOMESTEAD_DIFF_ADJUSTMENT_CUTOFF=10, # Metropolis fork METROPOLIS_FORK_BLKNUM=4370000, METROPOLIS_ENTRY_POINT=2**160 - 1, METROPOLIS_STATEROOT_STORE=0x10, METROPOLIS_BLOCKHASH_STORE=0x20, METROPOLIS_WRAPAROUND=65536, METROPOLIS_GETTER_CODE=decode_hex('6000355460205260206020f3'), METROPOLIS_DIFF_ADJUSTMENT_CUTOFF=9, # Constantinople fork CONSTANTINOPLE_FORK_BLKNUM=2**100, # DAO fork DAO_FORK_BLKNUM=1920000, DAO_FORK_BLKHASH=decode_hex( '4985f5ca3d2afbec36529aa96f74de3cc10a2a4a6c44f2157a57d2c6059a11bb'), DAO_FORK_BLKEXTRA=decode_hex('64616f2d686172642d666f726b'), DAO_WITHDRAWER=utils.normalize_address( '0xbf4ed7b27f1d666546e30d74d50d173d20bca754'), # Anti-DoS fork ANTI_DOS_FORK_BLKNUM=2463000, SPURIOUS_DRAGON_FORK_BLKNUM=2675000, CONTRACT_CODE_SIZE_LIMIT=0x6000, # Default consensus strategy: ethash, poa, casper, pbft
from accounts import AccountsService, Account from db_service import DBService 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 = {} @click.group(help='Welcome to {} {}'.format(Casper.client_name, Casper.client_version))
import bitcoin from ethereum import utils, opcodes from ethereum.utils import safe_ord, decode_hex from rlp.utils import ascii_chr ZERO_PRIVKEY_ADDR = decode_hex('3f17f1962b36e491b30a40b2405849e597ba5fb5') def proc_ecrecover(ext, msg): # print('ecrecover proc', msg.gas) OP_GAS = opcodes.GECRECOVER gas_cost = OP_GAS if msg.gas < gas_cost: return 0, 0, [] b = [0] * 32 msg.data.extract_copy(b, 0, 0, 32) h = b''.join([ascii_chr(x) for x in b]) v = msg.data.extract32(32) r = msg.data.extract32(64) s = msg.data.extract32(96) if r >= bitcoin.N or s >= bitcoin.P or v < 27 or v > 28: return 1, msg.gas - opcodes.GECRECOVER, [0] * 32 recovered_addr = bitcoin.ecdsa_raw_recover(h, (v, r, s)) if recovered_addr in (False, (0, 0)): return 1, msg.gas - gas_cost, [] pub = bitcoin.encode_pubkey(recovered_addr, 'bin') o = [0] * 12 + [safe_ord(x) for x in utils.sha3(pub[1:])[-20:]] return 1, msg.gas - gas_cost, o def proc_sha256(ext, msg):
def calculate_code_hash(code): if code[:2] == "0x": code_to_hash = code[2:] else: code_to_hash = code return "0x" + eth.sha3(eth.decode_hex(code_to_hash)).hex()
def test_reimburse(chain): owner_addr, concent_addr, gnt, gntb, cdep = mysetup(chain) other_addr = tester.accounts[1] subtask_id = "subtask_id123".zfill(32) closure_time = 2137 deposit_size = 100000 half_dep = int(deposit_size / 2) do_deposit_223(chain, gnt, gntb, cdep, owner_addr, deposit_size) amnt = gntb.call().balanceOf(cdep.address) assert amnt == gntb.call().balanceOf(cdep.address) q = queue.Queue() cbk = functools.partial(lambda event, q: q.put(event), q=q) cdep.on('ReimburseForSubtask', None, cbk) cdep.on('ReimburseForNoPayment', None, cbk) cdep.on('ReimburseForVerificationCosts', None, cbk) # not concent with pytest.raises(TransactionFailed): chain.wait.for_receipt( cdep.transact({'from': other_addr}).reimburseForSubtask( owner_addr, other_addr, half_dep, subtask_id)) assert amnt == gntb.call().balanceOf(cdep.address) assert q.empty() with pytest.raises(TransactionFailed): chain.wait.for_receipt( cdep.transact({'from': other_addr}).reimburseForNoPayment( owner_addr, other_addr, half_dep, closure_time)) assert amnt == gntb.call().balanceOf(cdep.address) assert q.empty() with pytest.raises(TransactionFailed): chain.wait.for_receipt( cdep.transact({'from': other_addr}).reimburseForVerificationCosts( owner_addr, half_dep, subtask_id)) assert amnt == gntb.call().balanceOf(cdep.address) assert q.empty() # concent chain.wait.for_receipt( cdep.transact({'from': concent_addr}).reimburseForSubtask( owner_addr, other_addr, half_dep, subtask_id)) time.sleep(1) event = q.get() assert 'ReimburseForSubtask' == event['event'] assert owner_addr == utils.decode_hex(event['args']['_requestor'][2:]) assert other_addr == utils.decode_hex(event['args']['_provider'][2:]) assert half_dep == event['args']['_amount'] assert subtask_id == event['args']['_subtask_id'] assert amnt - half_dep == cdep.call().balanceOf(owner_addr) assert amnt - half_dep == gntb.call().balanceOf(cdep.address) amount = 1 chain.wait.for_receipt( cdep.transact({'from': concent_addr}).reimburseForNoPayment( owner_addr, other_addr, amount, closure_time)) event = q.get() assert 'ReimburseForNoPayment' == event['event'] assert owner_addr == utils.decode_hex(event['args']['_requestor'][2:]) assert other_addr == utils.decode_hex(event['args']['_provider'][2:]) assert amount == event['args']['_amount'] assert closure_time == event['args']['_closure_time'] assert amnt - half_dep - amount == cdep.call().balanceOf(owner_addr) assert amnt - half_dep - amount == gntb.call().balanceOf(cdep.address) amount = half_dep - 1 chain.wait.for_receipt( cdep.transact({'from': concent_addr}).reimburseForVerificationCosts( owner_addr, amount, subtask_id)) event = q.get() assert 'ReimburseForVerificationCosts' == event['event'] assert owner_addr == utils.decode_hex(event['args']['_from'][2:]) assert amount == event['args']['_amount'] assert 0 == cdep.call().balanceOf(owner_addr) assert 0 == gntb.call().balanceOf(cdep.address) assert q.empty()
def compile_solidity(sourcecode, name=None, cwd=None, solc='solc', optimize=True, optimize_runs=None, no_optimize_yul=False): process = subprocess.Popen([solc, '--version'], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, stderrdata = process.communicate() try: m = regex.match(r"^Version: (?P<version>\d+\.\d+\.\d+).*$", output.decode('utf-8').split('\n')[1]) version = tuple([int(i) for i in m.group('version').split('.')]) except: raise Exception("Unable to parse solc version") args = [solc, '--allow-paths', '.', '--combined-json', 'bin,abi'] if optimize: args.append('--optimize') if optimize and optimize_runs: args.extend(['--optimize-runs', str(optimize_runs)]) if version >= (0, 6, 0) and no_optimize_yul: args.append('--no-optimize-yul') if cwd is None: cwd = "." cwd = os.path.abspath(cwd) # TODO: distinguish between incorrect paths and requested <stdin> input if os.path.exists(os.path.join(cwd, sourcecode)): filename = sourcecode sourcecode = None else: filename = '<stdin>' args.append(filename) process = subprocess.Popen(args, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, stderrdata = process.communicate(input=sourcecode) try: output = json.loads(output) except json.JSONDecodeError: if output and stderrdata: output += b'\n' + stderrdata elif stderrdata: output = stderrdata raise Exception("Failed to compile source: {}\n{}\n{}".format( filename, ' '.join(args), output.decode('utf-8'))) contract = None try: for key in output['contracts']: if key.startswith(filename + ':'): if name is not None and not key.endswith(':' + name): continue contract = output['contracts'][key] break except KeyError: raise if contract is None: raise Exception( "Unexpected compiler output: unable to find contract in result") abi = json.loads(contract['abi']) data = decode_hex(contract['bin']) return abi, data
def _same_node(addr_info, node_id): if len(node_id) > 32: node_id = decode_hex(node_id) return sha3(node_id)[12:] == addr_info
SOLIDITY_AVAILABLE = 'solidity' in Compilers().compilers # EVM code corresponding to the following solidity code: # # contract LogTest { # event Log(); # # function () { # Log(); # } # } # # (compiled with online Solidity compiler at https://chriseth.github.io/browser-solidity/ version # 0.1.1-34172c3b/RelWithDebInfo-Emscripten/clang/int) LOG_EVM = decode_hex( '606060405260448060116000396000f30060606040523615600d57600d565b60425b7f5e7df75d54' 'e493185612379c616118a4c9ac802de621b010c96f74d22df4b30a60405180905060405180910390' 'a15b565b00') def test_externally(): # The results of the external rpc-tests are not evaluated as: # 1) the Whisper protocol is not implemented and its tests fail; # 2) the eth_accounts method should be skipped; # 3) the eth_getFilterLogs fails due to the invalid test data; os.system(''' git clone https://github.com/ethereum/rpc-tests; cd rpc-tests; git submodule update --init --recursive; npm install; rm -rf /tmp/rpctests; pyethapp -d /tmp/rpctests -l :info,eth.chainservice:debug,jsonrpc:debug -c jsonrpc.listen_port=8081 -c p2p.max_peers=0 -c p2p.min_peers=0 blocktest lib/tests/BlockchainTests/bcRPC_API_Test.json RPC_API_Test & sleep 60 && make test;
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 = {} @click.group(help='Welcome to {} {}'.format(Casper.client_name,
def tester_deploy_contract(tester_state, private_key, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) all_contracts = _solidity.compile_file(contract_path, libraries=dict()) contract = all_contracts[contract_name] contract_interface = contract['abi'] log.info('Deploying "{}" contract'.format(contract_file)) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_name, dependencies) log.info('Deploing dependencies: {}'.format(str(deployment_order))) deployment_order.pop() # remove `contract_name` from the list libraries = dict() for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = _solidity.solidity_resolve_symbols( dependency_contract['bin_hex'], libraries, ) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') libraries[deploy_contract] = encode_hex(contract_address) hex_bytecode = _solidity.solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = hex_bytecode.decode('hex') contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments(constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] log.info('Creating contract {}'.format(contract_name)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
def deploy_solidity_contract(self, sender, contract_name, all_contracts, # pylint: disable=too-many-locals libraries, constructor_parameters, timeout=None, gasprice=default_gasprice): if contract_name not in all_contracts: raise ValueError('Unkonwn contract {}'.format(contract_name)) libraries = dict(libraries) contract = all_contracts[contract_name] contract_interface = contract['abi'] symbols = solidity_unresolved_symbols(contract['bin_hex']) if symbols: available_symbols = list(map(solidity_library_symbol, list(all_contracts.keys()))) # pylint: disable=bad-builtin unknown_symbols = set(symbols) - set(available_symbols) if unknown_symbols: msg = 'Cannot deploy contract, known symbols {}, unresolved symbols {}.'.format( available_symbols, unknown_symbols, ) raise Exception(msg) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_name, dependencies) deployment_order.pop() # remove `contract_name` from the list log.debug('Deploing dependencies: {}'.format(str(deployment_order))) for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = solidity_resolve_symbols(dependency_contract['bin_hex'], libraries) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode transaction_hash_hex = self.send_transaction( sender, to='', data=bytecode, gasprice=gasprice, ) transaction_hash = decode_hex(transaction_hash_hex) self.poll(transaction_hash, timeout=timeout) receipt = self.eth_getTransactionReceipt(transaction_hash) contract_address = receipt['contractAddress'] contract_address = contract_address[2:] # remove the hexadecimal prefix 0x from the address libraries[deploy_contract] = contract_address deployed_code = self.eth_getCode(decode_hex(contract_address)) if deployed_code == '0x': raise RuntimeError("Contract address has no code, check gas usage.") hex_bytecode = solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = decode_hex(hex_bytecode) contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments(constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] transaction_hash_hex = self.send_transaction( sender, to='', data=bytecode, gasprice=gasprice, ) transaction_hash = decode_hex(transaction_hash_hex) self.poll(transaction_hash, timeout=timeout) receipt = self.eth_getTransactionReceipt(transaction_hash) contract_address = receipt['contractAddress'] deployed_code = self.eth_getCode(decode_hex(contract_address[2:])) if deployed_code == '0x': raise RuntimeError("Deployment of {} failed. Contract address has no code, check gas usage.".format( contract_name )) return self.new_contract_proxy( contract_interface, contract_address, )
def _dec(x): if utils.is_string(x) and x.startswith(b'0x'): return utils.decode_hex(x[2:]) return x
# -*- coding: utf8 -*- import bitcoin from rlp.utils import ascii_chr from secp256k1 import PublicKey, ALL_FLAGS from ethereum import utils, opcodes from ethereum.utils import safe_ord, decode_hex ZERO_PRIVKEY_ADDR = decode_hex('3f17f1962b36e491b30a40b2405849e597ba5fb5') def proc_ecrecover(ext, msg): # print('ecrecover proc', msg.gas) OP_GAS = opcodes.GECRECOVER gas_cost = OP_GAS if msg.gas < gas_cost: return 0, 0, [] message_hash_bytes = [0] * 32 msg.data.extract_copy(message_hash_bytes, 0, 0, 32) message_hash = b''.join(map(ascii_chr, message_hash_bytes)) # TODO: This conversion isn't really necessary. # TODO: Invesitage if the check below is really needed. v = msg.data.extract32(32) r = msg.data.extract32(64) s = msg.data.extract32(96) if r >= bitcoin.N or s >= bitcoin.N or v < 27 or v > 28: return 1, msg.gas - opcodes.GECRECOVER, []
def test_sixten(): c = tester.Chain() addr = decode_hex('1231231231231234564564564564561231231231') c.head_state.set_code(addr, serpent.compile_lll(sixten_code)) o1 = c.tx(tester.k0, addr, 0) assert utils.big_endian_to_int(o1) == 610
def get_transaction(self, blknum, txindex): encoded_transaction = self.child_chain.get_transaction(blknum, txindex) return rlp.decode(utils.decode_hex(encoded_transaction), Transaction)
def test_compress_fail(): data = utils.decode_hex("""f9011180a0ab8cdb808c8303bb61fb48e276217be9770fa83ecf3f90f2234d558885f5abf1a0b43efbb595efd0043aca412c296b6064456c48f9ec418b9a1a7283f75b44bdbb8080a0b5d7a91be5ee273cce27e2ad9a160d2faadd5a6ba518d384019b68728a4f62f48080a00a9341b201bfb2dccdb1997c627f3b333310735d2a5cb6060a92e1e5efa961c780a06301b39b2ea8a44df8b0356120db64b788e71f52e1d7a6309d0d2e5b86fee7cb80a083de30075f2e5873ead424025a1fda192f5ea3313226e99c4cdd4aafc7b50493a01b7779e149cadf24d4ffb77ca7e11314b8db7097e4d70b2a173493153ca2e5a0a0939a6b4dae9579776ce0249d7ab2dd888372ed5bd44db16321cf4a7ebe21c4d68080""") assert compress.decompress(compress.compress(data)) == data
def challenge_exit(client, blknum, txindex, oindex, confirm_sig_hex, account): confirmSig = utils.decode_hex(confirm_sig_hex) client.challenge_exit(blknum, txindex, oindex, confirmSig, account) print("Submitted challenge exit")
def run( privatekey, registry_contract_address, discovery_contract_address, listen_address, logging, logfile, scenario, stage_prefix ): # pylint: disable=unused-argument # TODO: only enabled logging on "initiators" slogging.configure(logging, log_file=logfile) (listen_host, listen_port) = split_endpoint(listen_address) config = App.DEFAULT_CONFIG.copy() config['host'] = listen_host config['port'] = listen_port config['privatekey_hex'] = privatekey privatekey_bin = decode_hex(privatekey) rpc_client = JSONRPCClient( '127.0.0.1', 8545, privatekey_bin, ) blockchain_service = BlockChainService( privatekey_bin, rpc_client, GAS_PRICE, ) discovery = ContractDiscovery( blockchain_service, decode_hex(discovery_contract_address) ) registry = blockchain_service.registry( registry_contract_address ) throttle_policy = TokenBucket( config['protocol']['throttle_capacity'], config['protocol']['throttle_fill_rate'] ) transport = UDPTransport( discovery, server._udp_socket((listen_host, listen_port)), throttle_policy, config['protocol'], dict(), ) app = App( config, blockchain_service, registry, discovery, transport, ) app.discovery.register( app.raiden.address, listen_host, listen_port, ) app.raiden.register_payment_network(app.raiden.default_registry.address) if scenario: script = json.load(scenario) tools = ConsoleTools( app.raiden, app.discovery, app.config['settle_timeout'], app.config['reveal_timeout'], ) transfers_by_peer = {} tokens = script['tokens'] token_address = None peer = None our_node = hexlify(app.raiden.address) log.warning("our address is {}".format(our_node)) for token in tokens: # skip tokens that we're not part of nodes = token['channels'] if our_node not in nodes: continue partner_nodes = [ node for node in nodes if node != our_node ] # allow for prefunded tokens if 'token_address' in token: token_address = token['token_address'] else: token_address = tools.create_token(registry_contract_address) transfers_with_amount = token['transfers_with_amount'] # FIXME: in order to do bidirectional channels, only one side # (i.e. only token['channels'][0]) should # open; others should join by calling # raiden.api.deposit, AFTER the channel came alive! # NOTE: leaving unidirectional for now because it most # probably will get to higher throughput log.warning("Waiting for all nodes to come online") api = RaidenAPI(app.raiden) for node in partner_nodes: api.start_health_check_for(node) while True: all_reachable = all( api.get_node_network_state(node) == NODE_NETWORK_REACHABLE for node in partner_nodes ) if all_reachable: break gevent.sleep(5) log.warning("All nodes are online") if our_node != nodes[-1]: our_index = nodes.index(our_node) peer = nodes[our_index + 1] tools.token_network_register(app.raiden.default_registry.address, token_address) amount = transfers_with_amount[nodes[-1]] while True: try: app.discovery.get(peer.decode('hex')) break except KeyError: log.warning("Error: peer {} not found in discovery".format(peer)) time.sleep(random.randrange(30)) while True: try: log.warning("Opening channel with {} for {}".format(peer, token_address)) api.channel_open(app.raiden.default_registry.address, token_address, peer) break except KeyError: log.warning("Error: could not open channel with {}".format(peer)) time.sleep(random.randrange(30)) while True: try: log.warning("Funding channel with {} for {}".format(peer, token_address)) api.channel_deposit( app.raiden.default_registry.address, token_address, peer, amount, ) break except Exception: log.warning("Error: could not deposit {} for {}".format(amount, peer)) time.sleep(random.randrange(30)) if our_index == 0: last_node = nodes[-1] transfers_by_peer[last_node] = int(amount) else: peer = nodes[-2] if stage_prefix is not None: open('{}.stage1'.format(stage_prefix), 'a').close() log.warning("Done with initialization, waiting to continue...") event = gevent.event.Event() gevent.signal(signal.SIGUSR2, event.set) event.wait() transfer_results = {'total_time': 0, 'timestamps': []} def transfer(token_address, amount_per_transfer, total_transfers, peer, is_async): def transfer_(): log.warning("Making {} transfers to {}".format(total_transfers, peer)) initial_time = time.time() times = [0] * total_transfers for index in range(total_transfers): RaidenAPI(app.raiden).transfer( app.raiden.default_registry.address, token_address.decode('hex'), amount_per_transfer, peer, ) times[index] = time.time() transfer_results['total_time'] = time.time() - initial_time transfer_results['timestamps'] = times log.warning("Making {} transfers took {}".format( total_transfers, transfer_results['total_time'])) log.warning("Times: {}".format(times)) if is_async: return gevent.spawn(transfer_) else: transfer_() # If sending to multiple targets, do it asynchronously, otherwise # keep it simple and just send to the single target on my thread. if len(transfers_by_peer) > 1: greenlets = [] for peer_, amount in transfers_by_peer.items(): greenlet = transfer(token_address, 1, amount, peer_, True) if greenlet is not None: greenlets.append(greenlet) gevent.joinall(greenlets) elif len(transfers_by_peer) == 1: for peer_, amount in transfers_by_peer.items(): transfer(token_address, 1, amount, peer_, False) log.warning("Waiting for termination") open('{}.stage2'.format(stage_prefix), 'a').close() log.warning("Waiting for transfers to finish, will write results...") event = gevent.event.Event() gevent.signal(signal.SIGUSR2, event.set) event.wait() open('{}.stage3'.format(stage_prefix), 'a').close() event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() else: log.warning("No scenario file supplied, doing nothing!") open('{}.stage2'.format(stage_prefix), 'a').close() event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() app.stop()
def get_tx(self, blknum, slot): tx_bytes = self.child_chain.get_tx(blknum, slot) tx = rlp.decode(utils.decode_hex(tx_bytes), Transaction) return tx
def app(address, keystore_path, eth_rpc_endpoint, registry_contract_address, discovery_contract_address, listen_address, logging, logfile, max_unresponsive_time, send_ping_time): slogging.configure(logging, log_file=logfile) # config_file = args.config_file (listen_host, listen_port) = split_endpoint(listen_address) config = App.default_config.copy() config['host'] = listen_host config['port'] = listen_port config['max_unresponsive_time'] = max_unresponsive_time config['send_ping_time'] = send_ping_time accmgr = AccountManager(keystore_path) if not accmgr.accounts: raise RuntimeError('No Ethereum accounts found in the user\'s system') if not accmgr.address_in_keystore(address): addresses = list(accmgr.accounts.keys()) formatted_addresses = [ '[{:3d}] - 0x{}'.format(idx, addr) for idx, addr in enumerate(addresses) ] should_prompt = True while should_prompt: idx = click.prompt( "The following accounts were found in your machine:\n\n{}" "\nSelect one of them by index to continue: ".format( "\n".join(formatted_addresses)), type=int ) if idx >= 0 and idx < len(addresses): should_prompt = False else: print("\nError: Provided index '{}' is out of bounds\n".format(idx)) address = addresses[idx] privatekey = accmgr.get_privkey(address) config['privatekey_hex'] = encode_hex(privatekey) endpoint = eth_rpc_endpoint if eth_rpc_endpoint.startswith("http://"): endpoint = eth_rpc_endpoint[len("http://"):] rpc_port = 80 elif eth_rpc_endpoint.startswith("https://"): endpoint = eth_rpc_endpoint[len("https://"):] rpc_port = 443 if ':' not in endpoint: # no port was given in url rpc_host = endpoint else: rpc_host, rpc_port = split_endpoint(endpoint) blockchain_service = BlockChainService( privatekey, decode_hex(registry_contract_address), host=rpc_host, port=rpc_port, ) discovery = ContractDiscovery( blockchain_service, decode_hex(discovery_contract_address) # FIXME: double encoding ) return App(config, blockchain_service, discovery)
def get_tx_and_proof(self, blknum, slot): data = json.loads(self.child_chain.get_tx_and_proof(blknum, slot)) tx = rlp.decode(utils.decode_hex(data['tx']), Transaction) proof = utils.decode_hex(data['proof']) return tx, proof
def get_current_block(self): encoded_block = self.child_chain.get_current_block() return rlp.decode(utils.decode_hex(encoded_block), Block)
def get_proof(self, blknum, slot): return utils.decode_hex(self.child_chain.get_proof(blknum, slot))
def get_balances(self, address): encoded_balances = self.child_chain.get_balances(address) return rlp.decode( utils.decode_hex(encoded_balances), rlp.sedes.lists.List( [rlp.sedes.big_endian_int, rlp.sedes.big_endian_int]))
def test_manual1(self): # from block 1322230 on ropsten decoded_proof_blob = [ '01', [ '5b5782c32df715c083da95b805959d4718ec698915a4b0288e325aa346436be1', '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347', 'fee3a49dc4243fa92019fc4331228043b3c5e825', '13a50145091c1b5bae07abe10da88c54c5111c3fbb74fc91074ad2ffec311f6b', '0c673fc4822ba97cc737cfa7a839d6f6f755deedb1506490911f710bfa9315bf', '0c1fcb2441331ab1abc2e174a7293acce160d0b04f35a4b791bf89e9fd452b10', '00000000000000200000000000000000000000000010002000000000000000000040000000000000000000000010000000000000000000000040000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000100', '0c0b580c', '142cf6', '47e7c4', '0428a1', '596e599f', 'd883010606846765746887676f312e382e338664617277696e', '6ebda3617b113ba6550d08cb34119f940ddb96b509c62b7d0a8420722329d5b4', '61ebb9e58c93ac26', ], '01', '0001', '000101', [ [ 'da42945ae3c75118e89abff39ad566fd0a30b574e5df8ae70ce59d4cc5f19cb1', '', '', '', '', '', '', '', 'ca85a0d0ed219e8583feadf2dce0a73aa05e7d6a790c32efcc1dd6c901195f16', '', '', '', '', '', '', '', '' ], [ '', 'e61bb422a77353192ae2b4b29c3773b018da71d1425b2a48cca04d7da9917fab', '6b46aad90e0a9eeede8f2ad992401e52b3e52ce7d5bf723a48922401d5af95cc', '997f63912b72cdf8a907025644e1df51c313015c4e9e51500fa6ffa52241eef4', '5ad4d0c46a043da4e1da601955a1d29d5bd3b6c5b2dfc2776c8a898f998af498', '457048648440cf69193e770035a2df6f42ab5a6b8bc4d789a92074dc2beb2091', '', '', '', '', '', '', '', '', '', '', '' ], [ '20', 'f88b820beb8506fc23ac00832dd5d8943d04303126cd6e75324825455685b028401e0ec280a4e733ca974e6964610000000000000000000000000000000000000000000000000000000029a0f5405ffd54b78fc27dc56c49364ec22ba94c471f4639f052cfe324e3fc05d1d3a041291d64a8cdf499c386fde5bc04a1ca743aa81f65dc59198d29f8d66ee588a5' ], ], ] block_hash = utils.decode_hex( '51c92d45e39db17e43f0f7333de44c592b504bb8ac24dc3c39135d46655bae4f') result, index, nonce, gas_price, gas, to, value, data, v, r, s, contract_creation = self.verifier_contract.txProof( block_hash, rlp.encode(rec_bin(decoded_proof_blob)), startgas=10**6) self.assertEqual(result, self.verifier_contract.TX_PROOF_RESULT_PRESENT()) self.assertEqual(index, 1) def assert_failed_call(modified_decoded_proof_blob, block_hash=block_hash): with self.assertRaises(t.TransactionFailed): _ = self.verifier_contract.txProof( block_hash, rlp.encode(rec_bin(modified_decoded_proof_blob)), startgas=10**6) assert_failed_call( decoded_proof_blob, block_hash=utils.decode_hex( '51c92d45e39db17e43f0f7333de44c592b504bb8ac24dc3c39135d46655bae40' )) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[0] = 'ab' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[1][ 0] = '5b5782c32df715c083da95b805959d4718ec698915a4b0288e325aa346436be2' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[2] = '02' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[3] = '0101' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[3] = '000100' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[4] = '0001ff' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[5][0][ 0] = 'da42945ae3c75118e89abff39ad566fd0a30b574e5df8ae70ce59d4cc5f19cb2' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[5][1][ 1] = 'e61bb422a77353192ae2b4b29c3773b018da71d1425b2a48cca04d7da9917fac' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[5][2][0] = '21' assert_failed_call(modified_decoded_proof_blob) modified_decoded_proof_blob = copy.deepcopy(decoded_proof_blob) modified_decoded_proof_blob[5][2][1] = modified_decoded_proof_blob[5][ 2][1].replace( 'e733ca974e69646100000000000000000000000000000000000000000000000000000000', 'f733ca974e69646100000000000000000000000000000000000000000000000000000000' ) assert_failed_call(modified_decoded_proof_blob)
def tester_deploy_contract(tester_state, private_key, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) all_contracts = _solidity.compile_file(contract_path, libraries=dict()) contract_key = solidity_get_contract_key(all_contracts, contract_path, contract_name) contract = all_contracts[contract_key] contract_interface = contract['abi'] log.info('Deploying "{}" contract'.format(contract_file)) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_key, dependencies) log.info('Deploying dependencies: {}'.format(str(deployment_order))) deployment_order.pop() # remove `contract_name` from the list libraries = dict() for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = _solidity.solidity_resolve_symbols( dependency_contract['bin_hex'], libraries, ) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') libraries[deploy_contract] = encode_hex(contract_address) hex_bytecode = _solidity.solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = hex_bytecode.decode('hex') contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments( constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] log.info('Creating contract {}'.format(contract_name)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
print("Basic tests passed") zero_address = "0x0000000000000000000000000000000000000000" accounts = [ "0x776ba14735ff84789320718cf0aa43e91f7a8ce1", "0x095ce4e4240fa66ff90282c26847456e3f3b5002" ] recipient = "0x776ba14735ff84789320718cf0aa43e91f7a8ce1" raw_sigs = [ "0x4a89507bf71749fb338ed13fba623a683d9ecab0fb9c389a4298525c043e38281a00ab65628bb18a382eb8c8b4fb4dae95ccc993cf49f617c60d8051180778601c", "0xc84fe5d2a600e033930e0cf73f26e78f4c65b134f9c9992f60f08ce0863abdbe0548a6e8aa2d952659f29c67106b59fdfcd64d67df03c1df620c70c85578ae701b" ] sigs = [(utils.big_endian_to_int(x[64:]), utils.big_endian_to_int(x[:32]), utils.big_endian_to_int(x[32:64])) for x in map(lambda z: utils.decode_hex(z[2:]), raw_sigs)] h = utils.sha3( utils.encode_int32(0) + b'\x00' * 12 + utils.decode_hex(recipient[2:]) + utils.encode_int32(25) + b'') h2 = utils.sha3(b"\x19Ethereum Signed Message:\n32" + h) assert '0x' + utils.encode_hex( utils.sha3(utils.ecrecover_to_pub(h2, sigs[0][0], sigs[0][1], sigs[0][2]))[12:]) == accounts[0] assert '0x' + utils.encode_hex( utils.sha3(utils.ecrecover_to_pub(h2, sigs[1][0], sigs[1][1], sigs[1][2]))[12:]) == accounts[1] x2 = c.contract(open('wallet.v.py').read(), args=[accounts + [t.a3, zero_address, zero_address], 2],
mnemonic = create_mnemonic() hd_privkey = mnemonic_to_hdkey(mnemonic) print('Mnemonic: %s' % mnemonic) #print('HDPublicKey: %s' % bip32_privtopub(hd_privkey)) print('-' * 40) for i,(privkey,addr) in enumerate(derive_keypairs(hd_privkey)): print('Address #%d: 0x%s' % (i, addr)) elif command == 'keys': mnemonic = getpass.getpass('Enter mnemonic:').strip() hd_privkey = mnemonic_to_hdkey(mnemonic) #print('HDPublicKey: %s' % bip32_privtopub(hd_privkey)) for i,(privkey,addr) in enumerate(derive_keypairs(hd_privkey)): print('Address #%d: 0x%s Privkey: %s' % (i, addr, privkey)) elif command == 'send': privkey_hex = getpass.getpass('Enter privkey:') privkey = decode_hex(privkey_hex) assert len(privkey) == 32 nonce = int(sys.argv[2]) recipient = sys.argv[3] amount = int(Decimal(sys.argv[4]) * Decimal(1000000000000000000)) gas_price = int(sys.argv[5]) gas_limit = int(sys.argv[6]) tx = send(privkey, nonce, recipient, amount, gas_price, gas_limit) print('Trasaction:', encode_hex(tx).decode('utf-8')) elif command == 'export': privkey_hex = getpass.getpass('Enter privkey:') privkey = decode_hex(privkey_hex) assert len(privkey) == 32 pw = getpass.getpass('Choose a keystore password:'******'Repeat password:') assert pw == pw2, "Password mismatch"
def pbkdf2_hash(val, params): assert params["prf"] == "hmac-sha256" return pbkdf2.PBKDF2(val, decode_hex(params["salt"]), params["c"], SHA256).read(params["dklen"])
o = [0] * 12 + [safe_ord(x) for x in bitcoin.ripemd.RIPEMD160(d).digest()] return 1, msg.gas - gas_cost, o def proc_identity(ext, msg): #print('identity proc', msg.gas) OP_GAS = opcodes.GIDENTITYBASE + \ opcodes.GIDENTITYWORD * (utils.ceil32(msg.data.size) / 32) gas_cost = OP_GAS if msg.gas < gas_cost: return 0, 0, [] o = [0] * msg.data.size msg.data.extract_copy(o, 0, 0, len(o)) return 1, msg.gas - gas_cost, o specials = { decode_hex(k): v for k, v in { '0000000000000000000000000000000000000001': proc_ecrecover, '0000000000000000000000000000000000000002': proc_sha256, '0000000000000000000000000000000000000003': proc_ripemd160, '0000000000000000000000000000000000000004': proc_identity, }.items() } if __name__ == '__main__': class msg(object): data = 'testdata' gas = 500 proc_ripemd160(None, msg)
def privtoaddr(x): if len(x) > 32: x = decode_hex(x) return sha3(bitcoin.privtopub(x)[1:])[12:]
deployed.update(deploy_files(RAIDEN_CONTRACT_FILES, client)) deployed.update(deploy_files(DISCOVERY_CONTRACT_FILES, client)) return deployed if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('port', type=int) parser.add_argument('privatekey') parser.add_argument('--pretty', default=False, action='store_true') args = parser.parse_args() port = args.port privatekey_hex = args.privatekey privatekey = decode_hex(privatekey_hex) pretty = False client = JSONRPCClient( port=port, privkey=privatekey, print_communication=False, ) patch_send_transaction(client) deployed = deploy_all(client) if args.pretty: indent = 2 else: indent = None
def aes_ctr_decrypt(text, key, params): iv = big_endian_to_int(decode_hex(params["iv"])) ctr = Counter.new(128, initial_value=iv, allow_wraparound=True) mode = AES.MODE_CTR encryptor = AES.new(key, mode, counter=ctr) return encryptor.decrypt(text)
def run(privatekey, registry_contract_address, discovery_contract_address, listen_address, logging, logfile, scenario, stage_prefix, results_filename): # pylint: disable=unused-argument # TODO: only enabled logging on "initiators" slogging.configure(logging, log_file=logfile) (listen_host, listen_port) = split_endpoint(listen_address) config = App.default_config.copy() config['host'] = listen_host config['port'] = listen_port config['privatekey_hex'] = privatekey blockchain_service = BlockChainService( decode_hex(privatekey), decode_hex(registry_contract_address), host="127.0.0.1", port="8545", ) discovery = ContractDiscovery( blockchain_service, decode_hex(discovery_contract_address) ) app = App(config, blockchain_service, discovery) app.discovery.register( app.raiden.address, listen_host, listen_port, ) app.raiden.register_registry(app.raiden.chain.default_registry) if scenario: script = json.load(scenario) tools = ConsoleTools( app.raiden, app.discovery, app.config['settle_timeout'], app.config['reveal_timeout'], ) transfers_by_peer = {} tokens = script['assets'] token_address = None peer = None our_node = app.raiden.address.encode('hex') log.warning("our address is {}".format(our_node)) for token in tokens: # skip tokens/assets that we're not part of nodes = token['channels'] if not our_node in nodes: continue # allow for prefunded tokens if 'token_address' in token: token_address = token['token_address'] else: token_address = tools.create_token() transfers_with_amount = token['transfers_with_amount'] # FIXME: in order to do bidirectional channels, only one side # (i.e. only token['channels'][0]) should # open; others should join by calling # raiden.api.deposit, AFTER the channel came alive! # NOTE: leaving unidirectional for now because it most # probably will get to higher throughput log.warning("Waiting for all nodes to come online") while not all(tools.ping(node) for node in nodes if node != our_node): gevent.sleep(5) log.warning("All nodes are online") if our_node != nodes[-1]: our_index = nodes.index(our_node) peer = nodes[our_index + 1] channel_manager = tools.register_asset(token_address) amount = transfers_with_amount[nodes[-1]] while True: try: app.discovery.get(peer.decode('hex')) break except KeyError: log.warning("Error: peer {} not found in discovery".format(peer)) time.sleep(random.randrange(30)) while True: try: log.warning("Opening channel with {} for {}".format(peer, token_address)) app.raiden.api.open(token_address, peer) break except KeyError: log.warning("Error: could not open channel with {}".format(peer)) time.sleep(random.randrange(30)) while True: try: log.warning("Funding channel with {} for {}".format(peer, token_address)) channel = app.raiden.api.deposit(token_address, peer, amount) break except Exception: log.warning("Error: could not deposit {} for {}".format(amount, peer)) time.sleep(random.randrange(30)) if our_index == 0: last_node = nodes[-1] transfers_by_peer[last_node] = int(amount) else: peer = nodes[-2] if stage_prefix is not None: open('{}.stage1'.format(stage_prefix), 'a').close() log.warning("Done with initialization, waiting to continue...") event = gevent.event.Event() gevent.signal(signal.SIGUSR2, event.set) event.wait() transfer_results = {'total_time': 0, 'timestamps': []} def transfer(token_address, amount_per_transfer, total_transfers, peer, is_async): def transfer_(): log.warning("Making {} transfers to {}".format(total_transfers, peer)) initial_time = time.time() times = [0] * total_transfers for index in xrange(total_transfers): app.raiden.api.transfer( token_address.decode('hex'), amount_per_transfer, peer, ) times[index] = time.time() transfer_results['total_time'] = time.time() - initial_time transfer_results['timestamps'] = times log.warning("Making {} transfers took {}".format( total_transfers, transfer_results['total_time'])) log.warning("Times: {}".format(times)) if is_async: return gevent.spawn(transfer_) else: transfer_() # If sending to multiple targets, do it asynchronously, otherwise # keep it simple and just send to the single target on my thread. if len(transfers_by_peer) > 1: greenlets = [] for peer_, amount in transfers_by_peer.items(): greenlet = transfer(token_address, 1, amount, peer_, True) if greenlet is not None: greenlets.append(greenlet) gevent.joinall(greenlets) elif len(transfers_by_peer) == 1: for peer_, amount in transfers_by_peer.items(): transfer(token_address, 1, amount, peer_, False) log.warning("Waiting for termination") open('{}.stage2'.format(stage_prefix), 'a').close() log.warning("Waiting for transfers to finish, will write results...") event = gevent.event.Event() gevent.signal(signal.SIGUSR2, event.set) event.wait() results = tools.channel_stats_for(token_address, peer) if transfer_results['total_time'] != 0: results['total_time'] = transfer_results['total_time'] if len(transfer_results['timestamps']) > 0: results['timestamps'] = transfer_results['timestamps'] results['channel'] = repr(results['channel']) # FIXME log.warning("Results: {}".format(results)) with open(results_filename, 'w') as fp: json.dump(results, fp, indent=2) open('{}.stage3'.format(stage_prefix), 'a').close() event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() else: log.warning("No scenario file supplied, doing nothing!") open('{}.stage2'.format(stage_prefix), 'a').close() event = gevent.event.Event() gevent.signal(signal.SIGQUIT, event.set) gevent.signal(signal.SIGTERM, event.set) gevent.signal(signal.SIGINT, event.set) event.wait() app.stop()
def scrypt_hash(val, params): return scrypt.hash(str(val), decode_hex(params["salt"]), params["n"], params["r"], params["p"], params["dklen"])
def test_merklePatriciaCompactDecode(self): self.assertEqual( utils.decode_hex(''), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('00'))) self.assertEqual( utils.decode_hex('00'), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('10'))) self.assertEqual( utils.decode_hex('0102030405'), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('112345'))) self.assertEqual( utils.decode_hex('000102030405'), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('00012345'))) self.assertEqual( utils.decode_hex('000f010c0b08'), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('200f1cb8'))) self.assertEqual( utils.decode_hex('0f010c0b08'), self.verifier_contract.exposedMerklePatriciaCompactDecode( utils.decode_hex('3f1cb8')))
EXPDIFF_PERIOD=100000, EXPDIFF_FREE_PERIODS=2, # Delay in Byzantium METROPOLIS_DELAY_PERIODS=30, # Blank account initial nonce ACCOUNT_INITIAL_NONCE=0, # Homestead fork HOMESTEAD_FORK_BLKNUM=1150000, HOMESTEAD_DIFF_ADJUSTMENT_CUTOFF=10, # Metropolis fork METROPOLIS_FORK_BLKNUM=4370000, METROPOLIS_ENTRY_POINT=2 ** 160 - 1, METROPOLIS_STATEROOT_STORE=0x10, METROPOLIS_BLOCKHASH_STORE=0x20, METROPOLIS_WRAPAROUND=65536, METROPOLIS_GETTER_CODE=decode_hex('6000355460205260206020f3'), METROPOLIS_DIFF_ADJUSTMENT_CUTOFF=9, # Constantinople fork CONSTANTINOPLE_FORK_BLKNUM=2**100, # DAO fork DAO_FORK_BLKNUM=1920000, DAO_FORK_BLKHASH=decode_hex( '4985f5ca3d2afbec36529aa96f74de3cc10a2a4a6c44f2157a57d2c6059a11bb'), DAO_FORK_BLKEXTRA=decode_hex('64616f2d686172642d666f726b'), DAO_WITHDRAWER=utils.normalize_address( '0xbf4ed7b27f1d666546e30d74d50d173d20bca754'), # Anti-DoS fork ANTI_DOS_FORK_BLKNUM=2463000, SPURIOUS_DRAGON_FORK_BLKNUM=2675000, CONTRACT_CODE_SIZE_LIMIT=0x6000, # Default consensus strategy: ethash, poa, casper, pbft