def test_nettingchannel_settle_timeout_inrange(private_keys, tester_channelmanager, tester_state): """ The netting channel constructor must enforce that settle timeout is in the valid range. Also asserts that the constants.py and the netting channel contract values are synched. """ pkey0 = private_keys[0] pkey1 = private_keys[1] pkey2 = private_keys[2] log_listener = None with pytest.raises(TransactionFailed): small_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MIN - 1 tester_channelmanager.newChannel( privatekey_to_address(pkey1), small_settle_timeout, sender=pkey0, ) with pytest.raises(TransactionFailed): big_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MAX + 1 tester_channelmanager.newChannel( privatekey_to_address(pkey1), big_settle_timeout, sender=pkey0, ) minimum_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MIN netting_channel_address0_hex = tester_channelmanager.newChannel( privatekey_to_address(pkey1), minimum_settle_timeout, sender=pkey0, ) max_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MAX netting_channel_address1_hex = tester_channelmanager.newChannel( privatekey_to_address(pkey2), max_settle_timeout, sender=pkey0, ) netting_channel = tester.ABIContract( tester_state, CONTRACT_MANAGER.get_translator(CONTRACT_NETTING_CHANNEL), netting_channel_address0_hex, log_listener=log_listener, default_key=INVALID_KEY, ) # pylint: disable=no-member assert netting_channel.settleTimeout(sender=pkey0) == minimum_settle_timeout netting_channel2 = tester.ABIContract( tester_state, CONTRACT_MANAGER.get_translator(CONTRACT_NETTING_CHANNEL), netting_channel_address1_hex, log_listener=log_listener, default_key=INVALID_KEY, ) assert netting_channel2.settleTimeout(sender=pkey0) == max_settle_timeout
def deploy_target_contract(self, migration_contract, creator_idx=9): owner = self.monitor(creator_idx) t = abi.ContractTranslator(TARGET_ABI) args = t.encode_constructor_arguments([migration_contract]) addr = self.state.evm(TARGET_INIT + args, sender=owner.key) self.t = tester.ABIContract(self.state, TARGET_ABI, addr) return addr, owner.gas()
def deploy_swap(self, provider, creator_idx=9): owner = self.monitor(creator_idx) t = abi.ContractTranslator(SWAP_ABI) args = t.encode_constructor_arguments((provider, )) addr = self.state.evm(SWAP_INIT + args, sender=owner.key) self.s = tester.ABIContract(self.state, SWAP_ABI, addr) return addr, owner.gas()
def deploy_migration_contract(self, source_contract, creator_idx=9): owner = self.monitor(creator_idx) t = abi.ContractTranslator(MIGRATION_ABI) args = t.encode_constructor_arguments([source_contract]) addr = self.state.evm(MIGRATION_INIT + args, sender=owner.key) self.m = tester.ABIContract(self.state, MIGRATION_ABI, addr) return addr, owner.gas()
def new_nettingcontract(our_key, partner_key, tester_state, log_listener, channelmanager, settle_timeout): if settle_timeout < NETTINGCHANNEL_SETTLE_TIMEOUT_MIN: raise ValueError('settle_timeout must be larger-or-equal to {}'.format( NETTINGCHANNEL_SETTLE_TIMEOUT_MIN )) netting_channel_address0_hex = channelmanager.newChannel( privatekey_to_address(partner_key), settle_timeout, sender=our_key, ) tester_state.mine(number_of_blocks=1) nettingchannel_translator = tester.ContractTranslator( CONTRACT_MANAGER.get_abi(CONTRACT_NETTING_CHANNEL) ) nettingchannel = tester.ABIContract( tester_state, nettingchannel_translator, netting_channel_address0_hex, log_listener=log_listener, default_key=INVALID_KEY, ) return nettingchannel
def __deploy_contract(self, _bin, _abi, creator_idx, *args): gas_before = self.state.block.gas_used t = abi.ContractTranslator(_abi) args = t.encode_constructor_arguments(args) addr = self.state.evm(_bin + args, sender=tester.keys[creator_idx]) contract = tester.ABIContract(self.state, _abi, addr) return contract, addr, self.state.block.gas_used - gas_before
def deploy_wallet(self, _founder, creator_idx=9): assert not hasattr(self, 'c') owner = self.monitor(creator_idx) t = abi.ContractTranslator(WALLET_ABI) args = t.encode_constructor_arguments([]) addr = self.state.evm(WALLET_INIT + args, sender=owner.key) self.wallet = tester.ABIContract(self.state, WALLET_ABI, addr) return addr, owner.gas()
def __deploy_wallet(self, owner_key, owners, required=1, daylimit=WALLET_DAY_LIMIT): t = abi.ContractTranslator(WALLET_ABI) args = t.encode_constructor_arguments((owners, required, daylimit)) addr = self.state.evm(WALLET_INIT + args, sender=owner_key) return tester.ABIContract(self.state, WALLET_ABI, addr)
def create_tokenproxy(tester_state, tester_token_address, log_listener): translator = tester.ContractTranslator(HUMAN_TOKEN_ABI) token_abi = tester.ABIContract( tester_state, translator, tester_token_address, log_listener=log_listener, default_key=INVALID_KEY, ) return token_abi
def create_registryproxy(tester_state, tester_registry_address, log_listener): translator = tester.ContractTranslator(REGISTRY_ABI) registry_abi = tester.ABIContract( tester_state, translator, tester_registry_address, log_listener=log_listener, default_key=INVALID_KEY, ) return registry_abi
def create_registryproxy(tester_state, tester_registry_address, log_listener): translator = tester.ContractTranslator(CONTRACT_MANAGER.get_abi(CONTRACT_REGISTRY)) registry_abi = tester.ABIContract( tester_state, translator, tester_registry_address, log_listener=log_listener, default_key=INVALID_KEY, ) return registry_abi
def create_nettingchannel_proxy(tester_state, tester_nettingchannel_address, log_listener): translator = tester.ContractTranslator(NETTING_CHANNEL_ABI) netting_channel_abi = tester.ABIContract( tester_state, translator, tester_nettingchannel_address, log_listener=log_listener, default_key=INVALID_KEY, ) return netting_channel_abi
def create_channelmanager_proxy(tester_state, tester_channelmanager_address, log_listener): translator = tester.ContractTranslator(CHANNEL_MANAGER_ABI) channel_manager_abi = tester.ABIContract( tester_state, translator, tester_channelmanager_address, log_listener=log_listener, default_key=INVALID_KEY, ) return channel_manager_abi
def create_tokenproxy(tester_state, tester_token_address, log_listener): translator = tester.ContractTranslator( CONTRACT_MANAGER.get_abi(CONTRACT_HUMAN_STANDARD_TOKEN)) token_abi = tester.ABIContract( tester_state, translator, tester_token_address, log_listener=log_listener, default_key=INVALID_KEY, ) return token_abi
def deploy_contract_and_accounts(state, n_devs, start=1, end=2, deploy_contract=True): dev_keys = [] dev_accounts = [] milestone = int(math.log10(n_devs)) notify_step = milestone - 2 notify_value = 10**notify_step if notify_step > 0 else 1 # create developer accounts and keys in fashion of testers for account_number in range(n_devs): if account_number % notify_value == 0: print "Account", account_number + 1, "out of", n_devs dev_keys.append(sha3('dev' + to_string(account_number))) dev_accounts.append(privtoaddr(dev_keys[-1])) # developer balances block = state.block for i in range(n_devs): if i % notify_value == 0: print "Balance", i + 1, "out of", n_devs addr, data = dev_accounts[i], {'wei': 10**24} if len(addr) == 40: addr = decode_hex(addr) assert len(addr) == 20 block.set_balance(addr, parse_int_or_hex(data['wei'])) block.commit_state() block.state.db.commit() dev_addresses = [ContractHelper.dev_address(a) for a in dev_accounts] # deploy the gnt contract with updated developer accounts if deploy_contract: contract, _, _ = deploy_gnt(state, tester.accounts[9], start, end, replacements=[(dev_addresses, DEV_ADDR_REGEX)]) alloc_addr = mk_contract_address(contract.address, 0) allocation = tester.ABIContract(state, ALLOC_ABI, alloc_addr) else: contract, allocation = None, None return contract, allocation, dev_keys, dev_accounts
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.proxy = tester.ABIContract( tester_state, HUMAN_TOKEN_ABI, address, default_key=private_key, )
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.proxy = tester.ABIContract( tester_state, CONTRACT_MANAGER.get_abi(CONTRACT_HUMAN_STANDARD_TOKEN), address, default_key=private_key, )
def deploy_contract(self, start, end, creator_idx=9, migration_master=None): founder = tester.accounts[creator_idx] if migration_master is None: migration_master = founder t = abi.ContractTranslator(GNT_ABI) args = t.encode_constructor_arguments( (founder, migration_master, start, end)) addr = self.state.evm(GNT_INIT + args, sender=tester.keys[creator_idx]) return tester.ABIContract(self.state, GNT_ABI, addr), t
def test_finalize_funding(self): self.deploy_contract(tester.accounts[9], 2, 3) contract = self.c alloc_addr = mk_contract_address(contract.address, 0) allocation = tester.ABIContract(self.state, ALLOC_ABI, alloc_addr) # --------------- # PRE FUNDING # --------------- self.state.mine(1) with self.assertRaises(TransactionFailed): contract.finalize() # --------------- # FUNDING # --------------- self.state.mine(1) n_testers = len(tester.accounts) - 1 eths = [(i + 1) * 10000 * denoms.ether for i in xrange(n_testers)] for i, e in enumerate(eths): contract.create(sender=tester.keys[i], value=e) assert contract.balanceOf( tester.accounts[i]) == contract.tokenCreationRate() * e with self.assertRaises(TransactionFailed): contract.finalize() # --------------- # POST FUNDING # --------------- self.state.mine(2) total_tokens = contract.totalSupply() assert total_tokens == sum(eths) * contract.tokenCreationRate() contract.finalize() with self.assertRaises(TransactionFailed): contract.finalize() factory_percent = 12 devs_percent = 6 sum_percent = factory_percent + devs_percent tokens_extra = total_tokens * sum_percent / (100 - sum_percent) assert contract.totalSupply() == total_tokens + tokens_extra assert contract.balanceOf(allocation.address) == tokens_extra
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.registry_proxy = tester.ABIContract( self.tester_state, REGISTRY_ABI, self.address, default_key=private_key, ) self.tokenadded_filters = list()
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.proxy = tester.ABIContract( tester_state, CHANNEL_MANAGER_ABI, address, default_key=private_key, ) self.participant_filter = defaultdict(list) self.address_filter = defaultdict(list)
def deploy_contract(self, founder, start, end, creator_idx=9, migration_master=None): if migration_master is None: migration_master = founder owner = self.monitor(creator_idx) t = abi.ContractTranslator(GNT_ABI) args = t.encode_constructor_arguments( (founder, migration_master, self.starting_block + start, self.starting_block + end)) addr = self.state.evm(GNT_INIT + args, sender=owner.key) self.c = tester.ABIContract(self.state, GNT_ABI, addr) return addr, owner.gas()
def setUp(self): DatabaseFixture.setUp(self) self.state = tester.state() gnt_addr = self.state.evm(decode_hex(TestGNT.INIT_HEX)) self.state.mine() self.gnt = tester.ABIContract(self.state, TestGNT.ABI, gnt_addr) PaymentProcessor.TESTGNT_ADDR = gnt_addr self.privkey = tester.k1 self.client = mock.MagicMock(spec=Client) self.client.get_peer_count.return_value = 0 self.client.is_syncing.return_value = False self.client.get_transaction_count.side_effect = \ lambda addr: self.state.block.get_nonce(decode_hex(addr[2:])) self.client.get_balance.side_effect = \ lambda addr: self.state.block.get_balance(decode_hex(addr[2:])) def call(_from, to, data, **kw): # pyethereum does not have direct support for non-mutating calls. # The implemenation just copies the state and discards it after. # Here we apply real transaction, but with gas price 0. # We assume the transaction does not modify the state, but nonce # will be bumped no matter what. _from = _from[2:].decode('hex') data = data[2:].decode('hex') nonce = self.state.block.get_nonce(_from) value = kw.get('value', 0) tx = Transaction(nonce, 0, 100000, to, value, data) assert _from == tester.a1 tx.sign(tester.k1) block = kw['block'] assert block == 'pending' success, output = apply_transaction(self.state.block, tx) assert success return '0x' + output.encode('hex') def send(tx): success, _ = apply_transaction(self.state.block, tx) assert success # What happens in real RPC eth_send? return '0x' + tx.hash.encode('hex') self.client.call.side_effect = call self.client.send.side_effect = send self.pp = PaymentProcessor(self.client, self.privkey) self.clock = Clock() self.pp._loopingCall.clock = self.clock
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.registry_proxy = tester.ABIContract( self.tester_state, CONTRACT_MANAGER.get_abi(CONTRACT_REGISTRY), self.address, default_key=private_key, ) self.tokenadded_filters = list() self.address_to_channelmanager = dict() self.token_to_channelmanager = dict()
def new_nettingcontract(our_key, partner_key, tester_state, log_listener, channelmanager, settle_timeout): netting_channel_address0_hex = channelmanager.newChannel( privatekey_to_address(partner_key), settle_timeout, sender=our_key, ) tester_state.mine(number_of_blocks=1) nettingchannel_translator = tester.ContractTranslator(NETTING_CHANNEL_ABI) nettingchannel = tester.ABIContract( tester_state, nettingchannel_translator, netting_channel_address0_hex, log_listener=log_listener, default_key=INVALID_KEY, ) return nettingchannel
def __init__(self, tester_state, private_key, address): if len(tester_state.block.get_code(address)) == 0: raise Exception('Contract code empty') self.address = address self.tester_state = tester_state self.private_key = private_key self.proxy = tester.ABIContract( tester_state, NETTING_CHANNEL_ABI, address, default_key=private_key, ) self.newbalance_filters = list() self.secretrevealed_filters = list() self.channelclose_filters = list() self.channelsettle_filters = list() # check we are a participant of the channel self.detail(privatekey_to_address(private_key))
def test_nettingchannel_minimum_settle_timeout(private_keys, tester_channelmanager, tester_state): """ The netting channel constructor must enforce a minimum settle timeout. Also asserts that the constants.py and the netting channel contract values are synched. """ pkey0 = private_keys[0] pkey1 = private_keys[1] log_listener = None with pytest.raises(TransactionFailed): small_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MIN - 1 tester_channelmanager.newChannel( privatekey_to_address(pkey1), small_settle_timeout, sender=pkey0, ) minimum_settle_timeout = NETTINGCHANNEL_SETTLE_TIMEOUT_MIN netting_channel_address0_hex = tester_channelmanager.newChannel( privatekey_to_address(pkey1), minimum_settle_timeout, sender=pkey0, ) netting_channel = tester.ABIContract( tester_state, NETTING_CHANNEL_TRANSLATOR, netting_channel_address0_hex, log_listener=log_listener, default_key=INVALID_KEY, ) # pylint: disable=no-member assert netting_channel.settleTimeout( sender=pkey0) == minimum_settle_timeout
s = tester.state() code = open('spread.sol').read() contract_names = solc_wrapper.contract_names(code) creator = s.abi_contract(code, language='solidity', contract_name='Creator', log_listener=listener) spread_base = s.abi_contract(code, language='solidity', contract_name='Spread', listen=False) spread_addr = creator.create() print spread_addr s.mine() c = tester.ABIContract(s, spread_base.abi, spread_addr, log_listener=listener) print for i in range(10): print print print 'calling start' r = c.start() print spread_contracts for a in spread_contracts: print a, len(s.block.get_code(a)) print 'round', i, len(spread_contracts), s.block.timestamp, max(depths) s.mine()
def deploy_contract(self, owner_idx=9): owner = self.monitor(owner_idx) addr = self.state.evm(decode_hex(LotteryContract.INIT_HEX), sender=owner.key) self.c = tester.ABIContract(self.state, LotteryContract.ABI, addr) return addr, owner.gas()
def test(): s = t.state() t.gas_price = 0 s.block.coinbase = '\x35' * 20 content = open('one_phase_auction.sol').read() + open( 'two_phase_auction.sol').read() + open('adStorer.sol').read() logs = [] c = s.abi_contract(content, language='solidity', log_listener=lambda x: logs.append(x)) opa_sig = t.languages['solidity'].mk_full_signature( content, 'OnePhaseAuction') tpa_sig = t.languages['solidity'].mk_full_signature( content, 'TwoPhaseAuction') auctions = [] while not c.initialize(): pass for i in range(7): a = utils.normalize_address(c.getAuctionAddress(i)) auctions.append( t.ABIContract(s, opa_sig if i < 4 else tpa_sig, a, True, lambda x: logs.append(x))) bids = ( # bidder, value, higherValue, metadata (0, 10000, 100000, 'horse'), (1, 50000, 200000, 'cow'), (2, 102000, 300000, 'dog'), (3, 80000, 400000, 'mooch')) desired_winner = (2, 'dog') desired_balance_changes = [ # First price [0 + 102, 0 + 204, -102000 + 306, 0 + 408], # Second price [0 + 80, 0 + 160, -80000 + 240, 0 + 320], # All pay [-10000 + 242, -50000 + 484, -102000 + 726, -80000 + 968] ] # Test all three auction types start_time = s.block.timestamp for i in range(3): print 'Starting tests for two-phase auction type %d' % i s.block.timestamp = start_time for p in permutations(bids): old_balances = [s.block.get_balance(x) for x in t.accounts] bid_ids = [] for bidder, value, higherValue, metadata in p: _id = auctions[4 + i].commitBid(sha3num(value, '\x35' * 32), metadata, value=higherValue, sender=t.keys[bidder]) assert _id >= 0, _id bid_ids.append(_id) assert not auctions[4 + i].revealBid(_id, value, '\x35' * 32) s.mine(1, coinbase='\x35' * 20) s.block.timestamp += 86400 assert auctions[4 + i].commitBid(sha3num(value, '\x35' * 32), metadata, value=higherValue, sender=t.keys[bidder]) < 0 for _id, (bidder, value, higherValue, metadata) in zip(bid_ids, p): assert not auctions[4 + i].revealBid(_id, value - 1, '\x35' * 32) o = auctions[4 + i].revealBid(_id, value, '\x35' * 32) assert o s.mine(1, coinbase='\x35' * 20) s.block.timestamp += 86400 assert not auctions[4 + i].revealBid(_id, value) while 1: r = auctions[4 + i].ping() if r: break assert auctions[4 + i].getPhase() == 1, auctions[4 + i].getPhase() auction_winner_logs = [ x for x in logs if x["_event_type"] == "AuctionWinner" ] assert len(auction_winner_logs) assert auction_winner_logs[-1]["bidder"] == t.accounts[ desired_winner[0]].encode('hex') assert auction_winner_logs[-1]["metadata"].strip( '\x00') == desired_winner[1] new_balances = [s.block.get_balance(x) for x in t.accounts] deltas = [a - b for a, b in zip(new_balances, old_balances)] assert deltas[:len(desired_balance_changes[i] )] == desired_balance_changes[i], ( deltas, desired_balance_changes[i]) assert c.getWinnerAddress(4 + i) == t.accounts[ desired_winner[0]].encode('hex') assert c.getWinnerUrl(4 + i) == desired_winner[1] bids = ( # bidder, value, metadata, expected result (0, 200, "cow", True), (2, 220, "moose", True), # increases max 200 -> 220 (1, 270, "pig", True), # increases max 220 -> 270 (2, 240, "moose", False), # 240 < 270 (3, 280, "mouse", False), # 280 < 270 * 1.05 (4, 290, "remorse", True), # increases max 270 -> 290 (1, 30, None, False), # 270+30 = 300 < 290 * 1.05 (1, 50, None, True), # increases max 290 -> 270+50 = 320 (2, 110, None, False), # 220+110 = 330 < 320 * 1.05 (2, 170, None, True), # increasea max 320 -> 220+170 = 390 ) desired_winners = [(4, "remorse"), (2, "moose"), (4, "remorse"), (2, "moose")] desired_balance_changes = [[0, 0, 0, 0, -290], [0, 0, -390, 0, 0], [-200, -270, -220, 0, -290], [-200, -320, -390, 0, -290]] for i in range(4): print "Starting tests for one-phase auction type %d" % i s.block.timestamp = start_time bidmap = {} old_balances = [s.block.get_balance(x) for x in t.accounts] for bidder, value, metadata, expected_result in bids: if metadata: o = auctions[i].bid(metadata, value=value, sender=t.keys[bidder]) assert (o >= 0) is expected_result if o >= 0: bidmap[bidder] = o elif i & 1: assert auctions[i].increaseBid( bidmap[bidder], value=value, sender=t.keys[bidder]) is expected_result s.mine(1, coinbase='\x35' * 20) s.block.timestamp += 86400 newish_balances = [s.block.get_balance(x) for x in t.accounts] deltas0 = [a - b for a, b in zip(newish_balances, old_balances)] while not auctions[i].ping(): pass auction_winner_logs = [ x for x in logs if x["_event_type"] == "AuctionWinner" ] assert len(auction_winner_logs) assert auction_winner_logs[-1]["bidder"] == t.accounts[ desired_winners[i][0]].encode('hex') assert auction_winner_logs[-1]["metadata"] == desired_winners[i][1] new_balances = [s.block.get_balance(x) for x in t.accounts] deltas = [a - b for a, b in zip(new_balances, old_balances)] assert deltas[:len(desired_balance_changes[i] )] == desired_balance_changes[i] assert c.getWinnerAddress(i) == t.accounts[desired_winners[i] [0]].encode('hex') assert c.getWinnerUrl(i) == desired_winners[i][1]