def setUp(self): s = t.state() code = open('sponsor.sol').read() self.c = t.state().abi_contract(code, language='solidity') self.alice_priv = t.k0 self.alice_addr = utils.privtoaddr(self.alice_priv) self.bob_priv = t.k1 self.bob_addr = utils.privtoaddr(self.bob_priv) # wget -qO- https://www.realitykeys.com/api/v1/runkeeper/new --post-data="user_id=29908850&activity=running&measurement=total_distance&comparison=ge&goal=4000&settlement_date=2015-12-23&objection_period_secs=604800&accept_terms_of_service=current&use_existing=1" before_event = json.loads('{"no_pubkey": "", "comparison": null, "measurement": "total_distance", "activity_open_datetime": "2015-12-02 06:35:05", "settlement_date": "2015-12-03", "objection_period_secs": 0, "human_resolution_scheduled_datetime": null, "value": null, "machine_resolution_winner": "No", "id": 6206, "evaluation_method": null, "machine_resolution_value": "246.210454708", "is_user_authenticated": true, "objection_fee_satoshis_paid": 0, "objection_fee_satoshis_due": 1000000, "machine_resolution_scheduled_datetime": "2015-12-03 00:00:00", "user_id": "29908850", "goal": null, "created_datetime": "2015-12-02 06:35:05", "winner": null, "user_profile": "edochan", "winner_value": null, "source": "runkeeper", "yes_pubkey": "", "signature_v2": {"signed_hash": null, "base_unit": 1000000000000000000, "signed_value": null, "sig_der": null, "ethereum_address": "6fde387af081c37d9ffa762b49d340e6ae213395", "fact_hash": "634ab403c50fec82f39e8c4057ea29105708967d386c7f58325a28db333bc418", "sig_r": null, "sig_s": null, "pubkey": "02e577bc17badf301e14d86c33d76be5c3b82a0c416fc93cd124d612761191ec21", "sig_v": null}, "activity_closed_datetime": null, "activity": "walking", "human_resolution_value": null, "user_name": ["edochan"], "winner_privkey": null}') sig_data = before_event['signature_v2'] rk_addr = sig_data['ethereum_address'] event_hash = sig_data['fact_hash'] base_unit = sig_data['base_unit'] # This happens to be the same as the base unit, but there is no deep meaning behind this. ETH_TO_WEI = 1000000000000000000000 self.pledge_id = self.c.add_pledge( self.bob_addr, decode_hex(event_hash), base_unit, 100, # You have to walk at least 100 meters before we pay int(0.01 * ETH_TO_WEI / 100), # We'll give you 0.01 eth per 100 meters (0.0001 eth per meter) after that rk_addr, sender=self.alice_priv, value=int(0.04 * ETH_TO_WEI), # We'll fund you 0.04 eth );
def setUp(self, group, name): addr = os.path.join(self.ROOT, group, name) tester.state() tester.gas_limit = GAS_LIMIT self.state = tester.state() self.contract = self.state.abi_contract(addr, gas=tester.gas_limit) assert(self.state is not None) assert(self.contract is not None)
def test_currency_apis(): s = tester.state() c1 = s.abi_contract(serpent_currency, sender=tester.k0) c2 = s.abi_contract(solidity_currency, language='solidity', sender=tester.k0) o = [] s.block.log_listeners.append(lambda x: o.append(c._translator.listen(x))) for c in (c1, c2): o = [] assert c.coinBalanceOf(tester.a0) == 1000000 assert c.sendCoin(1000, tester.a2, sender=tester.k0) is True assert c.sendCoin(999001, tester.a2, sender=tester.k0) is False assert c.sendCoinFrom(tester.a2, 500, tester.a3, sender=tester.k0) is False c.approveOnce(tester.a0, 500, sender=tester.k2) assert c.sendCoinFrom(tester.a2, 400, tester.a3, sender=tester.k0) is True assert c.sendCoinFrom(tester.a2, 400, tester.a3, sender=tester.k0) is False assert c.sendCoinFrom(tester.a2, 100, tester.a3, sender=tester.k0) is True assert c.sendCoinFrom(tester.a2, 100, tester.a3, sender=tester.k0) is False c.approve(tester.a0, sender=tester.k2) assert c.sendCoinFrom(tester.a2, 100, tester.a3, sender=tester.k0) is True c.disapprove(tester.a0, sender=tester.k2) assert c.sendCoinFrom(tester.a2, 100, tester.a3, sender=tester.k0) is False assert c.coinBalance(sender=tester.k0) == 999000 assert c.coinBalanceOf(tester.a2) == 400 assert c.coinBalanceOf(tester.a3) == 600 assert o == [{"_event_type": b"CoinSent", "from": utils.encode_hex(tester.a0), "value": 1000, "to": utils.encode_hex(tester.a2)}, {"_event_type": b"CoinSent", "from": utils.encode_hex(tester.a2), "value": 400, "to": utils.encode_hex(tester.a3)}, {"_event_type": b"CoinSent", "from": utils.encode_hex(tester.a2), "value": 100, "to": utils.encode_hex(tester.a3)}, {"_event_type": b"CoinSent", "from": utils.encode_hex(tester.a2), "value": 100, "to": utils.encode_hex(tester.a3)}]
def test_difficulty(filename, testname, testdata): testdata = fixture_to_bytes(testdata) parent_timestamp=int(testdata["parentTimestamp"], 10 if testdata["parentTimestamp"].isdigit() else 16) parent_difficulty=int(testdata["parentDifficulty"], 10 if testdata["parentDifficulty"].isdigit() else 16) parent_blk_number=int(testdata["currentBlockNumber"], 10 if testdata["currentBlockNumber"].isdigit() else 16)-1 cur_blk_timestamp=int(testdata["currentTimestamp"], 10 if testdata["currentTimestamp"].isdigit() else 16) reference_dif = int(testdata["currentDifficulty"], 10 if testdata["currentDifficulty"].isdigit() else 16) env = tester.state().env if 'Homestead' in filename: env.config['HOMESTEAD_FORK_BLKNUM'] = 0 if 'difficultyMorden' in filename: env.config['HOMESTEAD_FORK_BLKNUM'] = 494000 parent_bh = blocks.BlockHeader(timestamp=parent_timestamp, difficulty=parent_difficulty, number=parent_blk_number) block = blocks.Block(parent_bh, [], env=env, making=True) calculated_dif = blocks.calc_difficulty(block, cur_blk_timestamp) print(calculated_dif) print(reference_dif) assert calculated_dif == reference_dif
def test_indirect_sort(): set_level(None, 'info') s = tester.state() open(filename9, 'w').write(sort_code) c = s.abi_contract(sort_tester_code) assert c.test([80, 234, 112, 112, 29]) == [29, 80, 112, 112, 234] os.remove(filename9)
def test_compile(self): s = t.state() code = ''' contract Test { struct S { uint x; int y; } mapping (uint => S) SS; function t1(uint a1, uint a2) returns (uint) { macro: $storage=SS[a1].x; $storage += a2; return $storage; } function t2(uint a1, int a2) returns (int) { macro: $storage=SS[a1].y; $storage -= a2; return $storage; } } ''' pp = PreProcessor() code = pp.resolve_macros(code) c = s.abi_contract(code, language='solidity') self.assertEqual(c.t1(0, 10), 10) self.assertEqual(c.t2(0, 4), -4)
def test_echo_contract(): nc.registry.register(EchoContract) s = tester.state() testdata = 'hello' r = s._send(tester.k0, EchoContract.address, 0, testdata) assert r['output'] == testdata nc.registry.unregister(EchoContract)
def __init__(self, *args, **kwargs): super(AbstractTestContract, self).__init__(*args, **kwargs) self.pp = PreProcessor() self.s = t.state() self.s.block.number = HOMESTEAD_BLOCK # t.gas_limit = 4712388 t.gas_limit = 2000000
def test_difficulty(filename, testname, testdata): testdata = fixture_to_bytes(testdata) parent_timestamp = int(testdata["parentTimestamp"], 10 if testdata["parentTimestamp"].isdigit() else 16) parent_difficulty = int( testdata["parentDifficulty"], 10 if testdata["parentDifficulty"].isdigit() else 16) parent_blk_number = int( testdata["currentBlockNumber"], 10 if testdata["currentBlockNumber"].isdigit() else 16) - 1 cur_blk_timestamp = int( testdata["currentTimestamp"], 10 if testdata["currentTimestamp"].isdigit() else 16) reference_dif = int(testdata["currentDifficulty"], 10 if testdata["currentDifficulty"].isdigit() else 16) env = tester.state().env if 'Homestead' in filename: env.config['HOMESTEAD_FORK_BLKNUM'] = 0 if 'difficultyMorden' in filename: env.config['HOMESTEAD_FORK_BLKNUM'] = 494000 parent_bh = blocks.BlockHeader(timestamp=parent_timestamp, difficulty=parent_difficulty, number=parent_blk_number) block = blocks.Block(parent_bh, [], env=env, making=True) calculated_dif = blocks.calc_difficulty(block, cur_blk_timestamp) print(calculated_dif) print(reference_dif) assert calculated_dif == reference_dif
def test_registry(): library_path = get_contract_path('IterableMappingCMC.sol') ncc_path = get_contract_path('IterableMappingNCC.sol') decoder_path = get_contract_path('Decoder.sol') registry_path = get_contract_path('Registry.sol') s = tester.state() assert s.block.number < 1150000 s.block.number = 1158001 assert s.block.number > 1150000 lib_c = s.abi_contract(None, path=library_path, language="solidity") s.mine() lib_ncc = s.abi_contract(None, path=ncc_path, language="solidity") s.mine() lib_dec = s.abi_contract(None, path=decoder_path, language="solidity") s.mine() c = s.abi_contract(None, path=registry_path, language="solidity", libraries={'IterableMappingCMC': lib_c.address.encode('hex'), 'IterableMappingNCC': lib_ncc.address.encode('hex'), 'Decoder': lib_dec.address.encode('hex')}) contract_address = c.addAsset(sha3('asset')[:20]) c.addAsset(sha3('address')[:20]) # if address already exists, throw with pytest.raises(TransactionFailed): c.addAsset(sha3('asset')[:20]) cmc = c.channelManagerByAsset(sha3('asset')[:20]) assert cmc == contract_address # if address does not exist, throw with pytest.raises(TransactionFailed): c.channelManagerByAsset(sha3('mainz')[:20]) adrs = c.assetAddresses() assert len(adrs) == 2 assert adrs[0] == sha3('asset')[:20].encode('hex') assert adrs[1] == sha3('address')[:20].encode('hex')
def test_sub(self): alloc_helper = ContractHelper(ALLOC_CONTRACT_PATH) # remove import alloc_helper.sub([''], regex=IMPORT_TOKEN_REGEX) orig_addresses = [ '0x9d3F257827B17161a098d380822fa2614FF540c8', '0xd7406E50b73972Fa4aa533a881af68B623Ba3F66', '0xd15356D05A7990dE7eC94304B0fD538e550c09C0', '0x3971D17B62b825b151760E2451F818BfB64489A7' ] assert alloc_helper.findall()[:4] == orig_addresses alloc_helper.sub(['0xad00', '0xad01', '0xad02']) changed_addresses = [ '0xad00', '0xad01', '0xad02', '0x3971D17B62b825b151760E2451F818BfB64489A7' ] assert alloc_helper.findall()[:4] == changed_addresses # replace import with contract source gnt_helper = ContractHelper(GNT_CONTRACT_PATH) gnt_helper.sub([alloc_helper.source], regex=IMPORT_ALLOC_REGEX) state = tester.state() state.mine(1) contract = state.abi_contract( gnt_helper.source, language='solidity', sender=tester.k0, constructor_parameters=[0xfac7, 0xfac7, 2, 3]) assert contract
def test_token(): token_library_path = get_contract_path('StandardToken.sol') token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() assert state.block.number < 1150000 state.block.number = 1158001 assert state.block.number > 1150000 token = state.abi_contract( None, path=token_library_path, language='solidity', ) contract_libraries = { 'StandardToken': token.address.encode('hex'), } contract = state.abi_contract( None, path=token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) # pylint: disable=no-member assert contract.balanceOf(tester.a0) == 10000 assert contract.balanceOf(tester.a1) == 0 assert contract.transfer(tester.a1, 5000) is True assert contract.balanceOf(tester.a0) == 5000 assert contract.balanceOf(tester.a1) == 5000
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_token(): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': hexlify(standard_token.address), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.transfer(address1, 5000) is True assert human_token.balanceOf(address0) == 5000 assert human_token.balanceOf(address1) == 5000
def deploy_decoder_tester(asset_address, address1, address2, settle_timeout): state = tester.state(num_accounts=1) # make sure we are on HOMESTEAD state.block.number = 1150001 nettingchannel_lib = state.abi_contract( None, path=os.path.join(get_project_root(), "smart_contracts", "NettingChannelLibrary.sol"), language='solidity' ) state.mine(number_of_blocks=1) decode_tester = state.abi_contract( None, path=get_test_contract_path("DecoderTester.sol"), language='solidity', libraries={ 'NettingChannelLibrary': nettingchannel_lib.address.encode('hex') }, constructor_parameters=( asset_address, address1, address2, settle_timeout ), extra_args="raiden={}".format(os.path.join(get_project_root(), "smart_contracts")) ) state.mine(number_of_blocks=1) return decode_tester
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 __init__(self, *args, **kwargs): super(AbstractTestContract, self).__init__(*args, **kwargs) self.pp = PreProcessor() self.s = t.state() self.s.block.number = self.HOMESTEAD_BLOCK t.gas_limit = 4712388 self.coinbase = self.s.block.coinbase.encode("hex") # Contract code self.contract_dir = 'contracts/solidity/' self.deploy_contracts = [] self.event_factory_name = self.EVENT_MANAGER_DIR + 'EventFactory.sol' self.outcome_token_name = self.EVENT_MANAGER_DIR + 'OutcomeToken.sol' self.outcome_token_library_name = self.EVENT_MANAGER_DIR + 'OutcomeTokenLibrary.sol' self.dao_name = self.DAO_DIR + 'DAO.sol' self.dao_auction_name = self.DAO_DIR + 'DAODutchAuction.sol' self.dao_token_name = self.DAO_DIR + 'DAOToken.sol' self.ether_token_name = self.TOKENS_DIR + 'EtherToken.sol' self.hunchgame_name = self.MARKET_MANAGERS_DIR + 'HunchGameMarketFactory.sol' self.hunchgame_token_name = self.TOKENS_DIR + 'HunchGameToken.sol' self.market_factory_name = self.MARKET_MANAGERS_DIR + 'DefaultMarketFactory.sol' self.lmsr_name = self.MARKET_MAKERS_DIR + 'LMSRMarketMaker.sol' self.math_library_name = self.UTILS_DIR + 'MathLibrary.sol' self.crowdfunding_name = self.MARKET_CROWDFUNDING_DIR + 'MarketCrowdfunding.sol' self.difficulty_oracle_name = self.ORACLES_DIR + 'DifficultyOracle.sol' self.fallback_oracle_name = self.ORACLES_DIR + 'DefaultFallbackOracle.sol' self.ultimate_oracle_name = self.ORACLES_DIR + 'UltimateOracle.sol' self.futarchy_oracle_name = self.ORACLES_DIR + 'FutarchyOracle.sol' self.oraclize_name = self.ORACLES_DIR + 'Oraclize.sol' self.oraclize_oracle_name = self.ORACLES_DIR + 'OraclizeOracle.sol'
def test_nac_tester(): assert issubclass(SampleNAC.afunc.im_class, SampleNAC) state = tester.state() nc.registry.register(SampleNAC) sender = tester.k0 assert 12 == nc.tester_call_method(state, sender, SampleNAC.afunc, 3, 4) print # FIXME fails # assert 30 == nc.tester_call_method(state, sender, SampleNAC.dfunc, [5, 6]) assert ['\0' * 20] * 3 == nc.tester_call_method(state, sender, SampleNAC.gfunc) assert 30 == nc.tester_call_method(state, sender, SampleNAC.efunc, [5, 6]) assert 26 == nc.tester_call_method(state, sender, SampleNAC.bfunc, 13) # FIXME THIS IS STILL BROKEN # assert [1, 2] == nc.tester_call_method(state, sender, SampleNAC.ffunc) # assert [1, 2] == nc.tester_call_method(state, sender, SampleNAC.ffunc2) assert 4, 4 == nc.tester_call_method(state, sender, SampleNAC.cfunc, 4) assert [4] == nc.tester_call_method(state, sender, SampleNAC.ccfunc, 4) assert 42 == nc.tester_call_method(state, sender, SampleNAC.noargs_func) assert None is nc.tester_call_method(state, sender, SampleNAC.void_func, 3) assert None is nc.tester_call_method(state, sender, SampleNAC.special_vars) # values out of range must fail with pytest.raises(abi.EncodingError): nc.tester_call_method(state, sender, SampleNAC.bfunc, -1) with pytest.raises(tester.TransactionFailed): nc.tester_call_method(state, sender, SampleNAC.afunc, 2**15, 2) with pytest.raises(abi.EncodingError): nc.tester_call_method(state, sender, SampleNAC.afunc, [1], 2) nc.registry.unregister(SampleNAC)
def evm_reset(): global evm global snapshots print "Resetting EVM state..." evm = t.state() snapshots = [] return True
def test_endpointregistry(): registry_contract_path = get_contract_path('EndpointRegistry.sol') events = [] state = tester.state() assert state.block.number < 1150000 state.block.number = 1158001 assert state.block.number > 1150000 sender = tester.a0.encode('hex') registry_contract = state.abi_contract( None, path=registry_contract_path, language='solidity', log_listener=events.append, ) sender = tester.a0.encode('hex') registry_contract.registerEndpoint('127.0.0.1:4001') assert registry_contract.findAddressByEndpoint('127.0.0.1:4001') == sender assert registry_contract.findEndpointByAddress(sender) == '127.0.0.1:4001' registry_contract.updateEndpoint('192.168.0.1:4002') assert registry_contract.findAddressByEndpoint( '192.168.0.1:4002') == sender assert registry_contract.findEndpointByAddress( sender) == '192.168.0.1:4002' assert len(events) == 2 assert events[0]['_event_type'] == 'AddressRegistered' assert events[1]['_event_type'] == 'AddressUpdated'
def test_abi_contract(): one_contract = """ contract foo { function seven() returns (int256 y) { y = 7; } function mul2(int256 x) returns (int256 y) { y = x * 2; } } """ two_contracts = one_contract + """ contract baz { function echo(address a) returns (address b) { b = a; return b; } function eight() returns (int256 y) { y = 8; } } """ state = tester.state() contract = state.abi_contract(one_contract, language='solidity') # pylint: disable=no-member assert contract.seven() == 7 assert contract.mul2(2) == 4 assert contract.mul2(-2) == -4
def timeout_case(): print "=================================TIME OUT CASE====================================" s = tester.state() alice = tester.k0 bob = tester.k1 silverToken = s.abi_contract(tokenCode, sender=alice) goldToken = s.abi_contract(tokenCode, sender=bob) start = s.block.gas_used exchangeAlicePart = s.abi_contract(exchangeCode, sender=alice) exchangeBobPart = s.abi_contract(exchangeCode, sender=bob) print "Before exchange happens" print "Alice has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(alice))) print "Bob has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(bob))) print "Alice has {token} gold token".format(token=goldToken.get_balance(utils.privtoaddr(alice))) print "Bob has {} gold token".format(goldToken.get_balance(utils.privtoaddr(bob))) pre_image = "10" block_timeout = 50 exchangeAlicePart.initialize(utils.sha3(pre_image), block_timeout, utils.privtoaddr(bob), exchangeBobPart.address, goldToken.address, sender=alice) exchangeBobPart.initialize(exchangeAlicePart.get_secret(), block_timeout, utils.privtoaddr(alice), 0, silverToken.address, sender=bob) silverToken.send_token(exchangeBobPart.address, 500, sender=alice) print "Bob does not want to do the exchange so he will not send any gold token to alice's part" s.mine(51) exchangeBobPart.refund(silverToken.address) print "" print "" print "After timeout happens" print "Alice has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(alice))) print "Bob has {token} silver token".format(token=silverToken.get_balance(utils.privtoaddr(bob))) print "Alice has {token} gold token".format(token=goldToken.get_balance(utils.privtoaddr(alice))) print "Bob has {} gold token".format(goldToken.get_balance(utils.privtoaddr(bob)))
def test_library_from_code(): with open(path.join(CONTRACTS_DIR, 'seven_library.sol')) as handler: library_code = handler.read() with open(path.join(CONTRACTS_DIR, 'seven_contract_without_import.sol')) as handler: contract_code = handler.read() state = tester.state() state.env.config['HOMESTEAD_FORK_BLKNUM'] = 0 # enable CALLCODE opcode library = state.abi_contract( library_code, path=None, language='solidity', ) libraries = { 'SevenLibrary': encode_hex(library.address), } contract = state.abi_contract( contract_code, path=None, libraries=libraries, language='solidity', ) # pylint: disable=no-member assert library.seven() == 7 assert contract.test() == 7
def test_returnten(): s = tester.state() open(filename, 'w').write(mul2_code) c = s.contract(returnten_code) s.send(tester.k0, c, 0) b2 = rlp.decode(rlp.encode(s.block), blocks.Block, db=s.db) assert rlp.encode(b2) == rlp.encode(s.block)
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 test_blockhashes_10(): s = tester.state() s.mine(10) o = [s.block.get_ancestor_hash(i) for i in range(1, 11)] assert o[0] == s.block.get_parent().hash == s.blocks[9].hash for i in range(1, 9): assert o[i] == s.blocks[9 - i].hash
def test_abicontract_interface(): """ Test for issue #370. """ tester_state = state() contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol') contract_name = 'Simple' simple_compiled = compile_file(contract_path) simple_data = solidity_get_contract_data( simple_compiled, contract_path, contract_name, ) simple_address = tester_state.evm(simple_data['bin']) # ABIContract class must accept json_abi abi_json = json.dumps(simple_data['abi']).encode('utf-8') abi = ABIContract( _state=tester_state, _abi=abi_json, address=simple_address, listen=False, log_listener=None, default_key=None, ) assert abi.test() == 1 # pylint: disable=no-member
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 test_returnten(): s = tester.state() open(filename, 'w').write(mul2_code) c = s.contract(returnten_code) o1 = s.send(tester.k0, c, 0) os.remove(filename) assert utils.big_endian_to_int(o1) == 10
def test_sort(): s = tester.state() c = s.abi_contract(sort_code) assert c.sort([9]) == [9] assert c.sort([9, 5]) == [5, 9] assert c.sort([9, 3, 5]) == [3, 5, 9] assert c.sort([80, 234, 112, 112, 29]) == [29, 80, 112, 112, 234]
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 test_blockhashes_300(): s = tester.state() s.mine(300) o = [s.block.get_ancestor_hash(i) for i in range(1, 257)] assert o[0] == s.block.get_parent().hash == s.blocks[299].hash for i in range(1, 256): assert o[i] == s.blocks[299 - i].hash
def test_crowdfund(): s = tester.state() c = s.abi_contract(crowdfund_code) # Create a campaign with id 100 c.create_campaign(100, 45, 100000, 2) # Create a campaign with id 200 c.create_campaign(200, 48, 100000, 2) # Make some contributions c.contribute(100, value=1, sender=tester.k1) assert 1 == c.progress_report(100) c.contribute(200, value=30000, sender=tester.k2) c.contribute(100, value=59049, sender=tester.k3) assert 59050 == c.progress_report(100) c.contribute(200, value=70001, sender=tester.k4) # Expect the 100001 units to be delivered to the destination # account for campaign 2 assert 100001 == s.block.get_balance(utils.int_to_addr(48)) mida1 = s.block.get_balance(tester.a1) mida3 = s.block.get_balance(tester.a3) # Mine 5 blocks to expire the campaign s.mine(5) # Ping the campaign after expiry c.contribute(100, value=1) # Expect refunds assert mida1 + 1 == s.block.get_balance(tester.a1) assert mida3 + 59049 == s.block.get_balance(tester.a3)
def test_with(): s = tester.state() c = s.abi_contract(with_code) assert c.f1() == [5, 7, 8, 5] assert c.f2() == 2 assert c.f3() == 7 assert c.f4() == [5, 7, 5, 5]
def test_callcode(): s = tester.state() open(filename3, 'w').write(add1_code) c = s.contract(callcode_test_code) o1 = s.send(tester.k0, c, 0) os.remove(filename3) assert utils.big_endian_to_int(o1) == 64
def test_decode_cancel_transfer(): encoded_data = '080000000000000000000001000000000000001f0bd4060688a1800ae986e4840aebc924bb40b5bf3893263bf8b2d0373a34b8d359c5edd82311074760d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df510000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000001d5601c4475f2f6aa73d6a70a56f9c756f24d211a914cc7aff3fb80d2d8741c868f4966fe93b467d28f15befd438b7aa0e7b8fbf5f00ce1abe0cc4a0ddf9bcc7c45c9863b784f474dee3c0682a5aa4c982712b98fcd60f5e5d94038008a97e251300' data = encoded_data.decode('hex') s = tester.state() c = s.abi_contract(decode_code, language="solidity") assert data[0] == '\x08' # make sure data has right cmdid assert len(data) == 253 o1 = c.decodeCancelTransfer1(data) o2 = c.decodeCancelTransfer2(data) nonce = o1[0] assert nonce == 1 expiration = o1[1] assert expiration == int('000000000000001f', 16) asset = o1[2] assert len(asset) == 40 assert asset == sha3('asset')[:20].encode('hex') recipient = o1[3] assert len(recipient) == 40 assert recipient == privtoaddr('y' * 32).encode('hex') locksroot = o2[0] assert locksroot == '60d09b4687c162154b290ee5fcbd7c6285590969b3c873e94b690ee9c4f5df51'.decode( 'hex') balance = o2[1] assert balance == 1 amount = o2[2] assert amount == 29 # int('000000000000000000000000000000000000000000000000000000000000001d', 16) hashlock = o2[3] assert hashlock == sha3('x' * 32) signature = o2[4] assert signature == 'f4966fe93b467d28f15befd438b7aa0e7b8fbf5f00ce1abe0cc4a0ddf9bcc7c45c9863b784f474dee3c0682a5aa4c982712b98fcd60f5e5d94038008a97e251300'.decode( 'hex')
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 setup_class(cls): # needed for 10 headers testing only since max is 3M tester.gas_limit = 5 * 10**6 cls.s = tester.state() cls.c = cls.s.abi_contract(cls.CONTRACT, endowment=2000*cls.ETHER) cls.snapshot = cls.s.snapshot() cls.seed = tester.seed
def setup_class(cls): tester.gas_limit = int(3.7e6) # include costs of debug methods cls.s = tester.state() cls.c = cls.s.abi_contract(cls.CONTRACT_DEBUG, endowment=2000 * cls.ETHER) cls.snapshot = cls.s.snapshot() cls.seed = tester.seed
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 test_decode_secret(): encoded_data = "040000000000000000000000000000000000000000000000000000000000736563726574d37b47b46bea9027a92a6e1c374450092016b9935c0f1e738a9516693f708f5b35937bb4e0a7de93be31585e6aa04984869477ce5283415d4e736e537e59d43501" # longer than expected input bad_encoded_data = "040000000000000000000000000000000000000000000000000000000000736563726574d37b47b46bea9027a92a6e1c374450092016b9935c0f1e738a9516693f708f5b35937bb4e0a7de93be31585e6aa04984869477ce5283415d4e736e537e59d4350101" data = encoded_data.decode('hex') bad_data = bad_encoded_data.decode('hex') s = tester.state() c = s.abi_contract(decode_code, language="solidity") assert data[0] == '\x04' # make sure data has right cmdid o1 = c.decodeSecret(data) assert o1[0][26:32] == 'secret' assert o1[0].encode( 'hex' ) == '0000000000000000000000000000000000000000000000000000736563726574' assert o1[1].encode( 'hex' ) == 'd37b47b46bea9027a92a6e1c374450092016b9935c0f1e738a9516693f708f5b35937bb4e0a7de93be31585e6aa04984869477ce5283415d4e736e537e59d43501' assert len(data) == 101 # length doesn't match with pytest.raises(TransactionFailed): c.decodeSecret(bad_data) with pytest.raises(TransactionFailed): c.decodeSecret(bad_data[0:100])
def test_registrar_apis(): s = tester.state() c1 = s.abi_contract(serpent_namereg, sender=tester.k0) c2 = s.abi_contract(solidity_namereg, language='solidity', sender=tester.k0) o = [] s.block.log_listeners.append(lambda x: o.append(c._translator.listen(x))) for c in (c1, c2): o = [] assert c.reserve('moose', sender=tester.k0) is True assert c.reserve('moose', sender=tester.k0) is False assert c.owner('moose') == utils.encode_hex(tester.a0) c.setAddr('moose', tester.a5) c.setAddr('moose', tester.a6, sender=tester.k1) assert c.addr('moose') == utils.encode_hex(tester.a5) c.transfer('moose', tester.a1, sender=tester.k0) c.transfer('moose', tester.a2, sender=tester.k0) assert c.owner('moose') == utils.encode_hex(tester.a1) c.setContent('moose', 'antlers', sender=tester.k0) c.setContent('moose', 'reindeer', sender=tester.k1) assert c.content('moose')[:8] == 'reindeer' c.setSubRegistrar('moose', tester.a7, sender=tester.k1) c.setSubRegistrar('moose', tester.a8, sender=tester.k2) assert c.subRegistrar('moose') == utils.encode_hex(tester.a7) assert o == [{ "_event_type": b"Changed", "name": b'moose', "__hash_name": utils.sha3(b'moose') }] * 5
def test_token(): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': standard_token.address.encode('hex'), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.transfer(address1, 5000) is True assert human_token.balanceOf(address0) == 5000 assert human_token.balanceOf(address1) == 5000
def test_token_approve(): test_path = os.path.join(os.path.dirname(__file__), 'SimpleApproveTransfer.sol') standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': standard_token.address.encode('hex'), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) test = state.abi_contract( None, path=test_path, language='solidity', constructor_parameters=[human_token.address], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 0 assert human_token.approve(test.address, 5000) is True assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 assert test.transfer(address1, 2000) is True assert human_token.balanceOf(address0) == 10000 - 2000 assert human_token.balanceOf(address1) == 0 + 2000 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 - 2000
def test_reverter(): s = tester.state() c = s.abi_contract(reverter_code, endowment=10 ** 15) c.entry() assert s.block.get_storage_data(c.address, 8080) == 4040 assert s.block.get_balance(decode_hex('0' * 39 + '7')) == 9 assert s.block.get_storage_data(c.address, 8081) == 0 assert s.block.get_balance(decode_hex('0' * 39 + '8')) == 0
def test_datafeeds(): s = tester.state() c1 = s.abi_contract(serpent_datafeed, sender=tester.k0) c2 = s.abi_contract(solidity_datafeed, language='solidity', sender=tester.k0) for c in (c1, c2): c.set('moose', 110, sender=tester.k0) c.set('moose', 125, sender=tester.k1) assert c.get('moose') == 110
def test_abi_address_output(): s = tester.state() c = s.abi_contract(abi_address_output_test_code) c.register(123, b'1212121212121212121212121212121212121212') c.register(123, b'3434343434343434343434343434343434343434') c.register(125, b'5656565656565656565656565656565656565656') assert c.get_address(123) == b'1212121212121212121212121212121212121212' assert c.get_address(125) == b'5656565656565656565656565656565656565656'