def do_test_speed(rounds=100, num_hashes=1000): import time values = [keccak(str(i)) for i in range(num_hashes)] st = time.time() for i in range(rounds): merkleroot(values) elapsed = time.time() - st print '%d additions per second' % (num_hashes * rounds / elapsed)
def test_duplicates(): hash_0 = keccak('x') hash_1 = keccak('y') assert merkleroot([hash_0, hash_0]) == hash_0, 'duplicates should be removed' assert merkleroot([hash_0, hash_1, hash_0 ]) == merkleroot([hash_0, hash_1 ]), 'duplicates should be removed'
def test_duplicates(): hash_0 = keccak('x') hash_1 = keccak('y') assert merkleroot([hash_0, hash_0]) == hash_0, 'duplicates should be removed' result0 = merkleroot([hash_0, hash_1, hash_0]) result1 = merkleroot([hash_0, hash_1]) assert result0 == result1, 'duplicates should be removed'
def test_small(): values = [x * 32 for x in 'a'] proof_for = values[-1] proof = [proof_for] r = merkleroot(values, proof) assert check_proof(proof, r, proof_for) r = merkleroot('') assert r == ''
def test_many(tree_up_to=10): for number_of_leaves in range(tree_up_to): merkle_tree = [keccak(str(value)) for value in range(number_of_leaves)] for value in merkle_tree: merkle_proof = [value] merkle_root = merkleroot(merkle_tree, merkle_proof) second_proof = get_proof(merkle_tree, value, merkle_root) assert check_proof(merkle_proof, merkle_root, value) is True assert check_proof(second_proof, merkle_root, value) is True assert merkleroot(merkle_tree) == merkleroot(reversed(merkle_tree))
def test_basic3(): values = [x * 32 for x in 'abc'] proof_for = values[-1] proof = [proof_for] r = merkleroot(values, proof) # print pex(r) # print 'proof', pexl(proof) assert check_proof(proof, r, proof_for) proof_for = values[0] proof = [proof_for] r = merkleroot(values, proof) # print pex(r) # print 'proof', pexl(proof) assert check_proof(proof, r, proof_for)
def register_locked_transfer(self, locked_transfer): if not isinstance(locked_transfer, LockedTransfer): raise ValueError('transfer must be LockedTransfer') lock = locked_transfer.lock lockhashed = sha3(lock.as_bytes) if self.is_known(lock.hashlock): raise ValueError('hashlock is already registered') merkletree = self.unclaimed_merkletree() merkletree.append(lockhashed) new_locksroot = merkleroot(merkletree) if locked_transfer.locksroot != new_locksroot: raise ValueError( 'locksroot mismatch expected:{} got:{}'.format( pex(new_locksroot), pex(locked_transfer.locksroot), ) ) self.hashlock_pendinglocks[lock.hashlock] = PendingLock(lock, lockhashed) self.transfer = locked_transfer self.hashlock_unlockedlocks = dict()
def do_test_many(values): for i, v in enumerate(values): proof = [v] r = merkleroot(values, proof) assert check_proof(proof, r, v) proof = get_proof(values, v, r) assert check_proof(proof, r, v)
def compute_merkleroot_with(self, include): """ Compute the resulting merkle root if the lock `include` is added in the tree. """ merkletree = self.balance_proof.unclaimed_merkletree() merkletree.append(sha3(include.as_bytes)) return merkleroot(merkletree)
def test_many(tree_up_to=10): for number_of_leaves in range(tree_up_to): merkle_tree = [ keccak(str(value)) for value in range(number_of_leaves) ] for value in merkle_tree: merkle_proof = get_proof(merkle_tree, value) merkle_root = merkleroot(merkle_tree) second_proof = get_proof(merkle_tree, value, merkle_root) assert check_proof(merkle_proof, merkle_root, value) is True assert check_proof(second_proof, merkle_root, value) is True assert merkleroot(merkle_tree) == merkleroot(reversed(merkle_tree))
def test_locked_transfer(): apps = create_network(num_nodes=2, num_assets=1, channels_per_node=1) a0, a1 = apps c0 = a0.raiden.assetmanagers.values()[0].channels.values()[0] c1 = a1.raiden.assetmanagers.values()[0].channels.values()[0] b0, b1 = c0.balance, c1.balance amount = 10 secret = 'secret' expiration = a0.raiden.chain.block_number + 100 hashlock = sha3(secret) t = c0.create_lockedtransfer(amount=amount, expiration=expiration, hashlock=hashlock) c0.raiden.sign(t) c0.register_transfer(t) c1.register_transfer(t) assert hashlock in c1.locked assert hashlock in c0.partner.locked assert len(c0.locked) == 0 assert len(c0.partner.locked) == 1 assert len(c1.locked) == 1 assert len(c1.partner.locked) == 0 assert c0.balance == b0 assert c0.distributable == c0.balance - amount assert c1.balance == c1.distributable == b1 assert c0.locked.outstanding == 0 assert c0.partner.locked.outstanding == amount assert c1.locked.outstanding == amount assert c1.partner.locked.outstanding == 0 assert c0.locked.root == '' assert c1.partner.locked.root == '' assert c1.locked.root == merkleroot( [sha3(tx.lock.asstring) for tx in c1.locked.locked.values()]) assert c0.partner.locked.root == c1.locked.root # reveal secret c0.claim_locked(secret) c1.claim_locked(secret) assert c0.balance == b0 - amount assert c0.distributable == c0.balance assert c1.balance == c1.distributable == b1 + amount assert c0.locked.outstanding == 0 assert c0.partner.locked.outstanding == 0 assert c1.locked.outstanding == 0 assert c1.partner.locked.outstanding == 0 assert len(c0.locked) == 0 assert len(c0.partner.locked) == 0 assert len(c1.locked) == 0 assert len(c1.partner.locked) == 0 assert c0.locked.root == '' assert c1.partner.locked.root == '' assert c1.locked.root == '' assert c0.partner.locked.root == ''
def compute_proof_for_lock(self, secret, lock): alllocks = chain(self.hashlock_pendinglocks.values(), self.hashlock_unclaimedlocks.values(), self.hashlock_unlockedlocks.values()) merkletree = [l.lockhashed for l in alllocks] # forcing bytes because ethereum.abi doesnt work with bytearray lock_encoded = bytes(lock.as_bytes) lock_hash = sha3(lock_encoded) merkle_proof = [lock_hash] merkleroot(merkletree, merkle_proof) return UnlockProof( merkle_proof, lock_encoded, secret, )
def test_multiple(): "does not support repeated values" values = [x * 32 for x in 'abada'] proof_for = values[-1] proof = [proof_for] with pytest.raises(AssertionError): r = merkleroot(values, proof) assert check_proof(proof, r, proof_for)
def test_two(): hash_0 = 'a' * 32 hash_1 = 'b' * 32 merkle_tree = [hash_0, hash_1] merkle_proof = get_proof(merkle_tree, hash_0) merkle_root = merkleroot(merkle_tree) assert merkle_proof == [hash_1] assert merkle_root == keccak(hash_0 + hash_1) assert check_proof(merkle_proof, merkle_root, hash_0) merkle_proof = get_proof(merkle_tree, hash_1) merkle_root = merkleroot(merkle_tree) assert merkle_proof == [hash_0] assert merkle_root == keccak(hash_0 + hash_1) assert check_proof(merkle_proof, merkle_root, hash_1)
def test_one(): hash_0 = 'a' * 32 merkle_tree = [hash_0] merkle_proof = get_proof(merkle_tree, hash_0) merkle_root = merkleroot(merkle_tree) assert merkle_proof == [] assert merkle_root == hash_0 assert check_proof(merkle_proof, merkle_root, hash_0) is True
def test_one(): hash_0 = 'a' * 32 merkle_tree = [hash_0] merkle_proof = [hash_0] # modified in place merkle_root = merkleroot(merkle_tree, merkle_proof) assert merkle_proof == [] assert merkle_root == hash_0 assert check_proof(merkle_proof, merkle_root, hash_0) is True
def test_two(): hash_0 = 'a' * 32 hash_1 = 'b' * 32 merkle_tree = [hash_0, hash_1] merkle_proof = [hash_0] # modified in place merkle_root = merkleroot(merkle_tree, merkle_proof) assert merkle_proof == [hash_1] assert merkle_root == keccak(hash_0 + hash_1) assert check_proof(merkle_proof, merkle_root, hash_0) merkle_proof = [hash_1] # modified in place merkle_root = merkleroot(merkle_tree, merkle_proof) assert merkle_proof == [hash_0] assert merkle_root == keccak(hash_0 + hash_1) assert check_proof(merkle_proof, merkle_root, hash_1)
def assert_locked(channel0, lock_list): """ Assert the locks create from `channel`. """ # a locked transfer is registered in the _partner_ state hashroot = merkleroot(sha3(lock.as_bytes) for lock in lock_list) assert len(channel0.partner_state.locked) == len(lock_list) assert channel0.partner_state.locked.root == hashroot assert channel0.partner_state.locked.outstanding == sum(lock.amount for lock in lock_list) for lock in lock_list: assert lock.hashlock in channel0.partner_state.locked
def test_get_proof(): values = [x * 32 for x in 'ab'] proof_for = values[-1] proof = [proof_for] r = merkleroot(values, proof) # print pex(r) # print 'proof', proof assert check_proof(proof, r, proof_for) proof_for = values[-1] proof = get_proof(values, proof_for, r) assert check_proof(proof, r, proof_for)
def assert_locked(channel0, outstanding_locks): """ Assert the locks create from `channel`. """ # a locked transfer is registered in the _partner_ state hashroot = merkleroot(sha3(lock.as_bytes) for lock in outstanding_locks) assert len(channel0.our_state.balance_proof.hashlock_pendinglocks) == len(outstanding_locks) assert channel0.our_state.balance_proof.merkleroot_for_unclaimed() == hashroot assert channel0.our_state.locked() == sum(lock.amount for lock in outstanding_locks) assert channel0.outstanding == sum(lock.amount for lock in outstanding_locks) for lock in outstanding_locks: assert lock.hashlock in channel0.our_state.balance_proof.hashlock_pendinglocks
def test_three(): def sort_join(first, second): return ''.join(sorted([first, second])) hash_0 = 'a' * 32 hash_1 = 'b' * 32 hash_2 = 'c' * 32 merkle_tree = [hash_0, hash_1, hash_2] hash_01 = ( b'me\xef\x9c\xa9=5\x16\xa4\xd3\x8a\xb7\xd9\x89\xc2\xb5\x00' b'\xe2\xfc\x89\xcc\xdc\xf8x\xf9\xc4m\xaa\xf6\xad\r[' ) assert keccak(hash_0 + hash_1) == hash_01 calculated_root = keccak(hash_2 + hash_01) merkle_proof = get_proof(merkle_tree, hash_0) merkle_root = merkleroot(merkle_tree) assert merkle_proof == [hash_1, hash_2] assert merkle_root == calculated_root assert check_proof(merkle_proof, merkle_root, hash_0) merkle_proof = get_proof(merkle_tree, hash_1) merkle_root = merkleroot(merkle_tree) assert merkle_proof == [hash_0, hash_2] assert merkle_root == calculated_root assert check_proof(merkle_proof, merkle_root, hash_1) merkle_proof = get_proof(merkle_tree, hash_2) merkle_root = merkleroot(merkle_tree) # with an odd number of values, the last value wont appear by itself in the # proof since it isn't hashed with another value assert merkle_proof == [keccak(hash_0 + hash_1)] assert merkle_root == calculated_root assert check_proof(merkle_proof, merkle_root, hash_2)
def test_get_proof(): hash_0 = 'a' * 32 hash_1 = 'b' * 32 merkle_tree = [hash_0, hash_1] merkle_proof = get_proof(merkle_tree, hash_0) merkle_root = merkleroot(merkle_tree) assert check_proof(merkle_proof, merkle_root, hash_0) second_merkle_proof = get_proof(merkle_tree, hash_0, merkle_root) assert check_proof(second_merkle_proof, merkle_root, hash_0) assert merkle_proof == second_merkle_proof
def compute_merkleroot_without(self, exclude): """ Compute the resulting merkle root if the lock `exclude` is removed. """ if isinstance(exclude, Lock): raise ValueError('exclude must be a Lock') merkletree = self.balance_proof.unclaimed_merkletree() if exclude.hashlock not in merkletree: raise ValueError('unknown lock `exclude`', exclude=exclude) exclude_hash = sha3(exclude.as_bytes) merkletree.remove(exclude_hash) root = merkleroot(merkletree) return root
def root_with(self, lock=None, exclude=None): """ Calculate the merkle root of the hashes in the container. Args: lock: Additional hashlock to be included in the merkle tree, used to calculate the updated merkle root without changing the store. exclude: Hashlock to be ignored, used to calculated a the updated merkle root without changing the store. """ if lock and not isinstance(lock, Lock): raise ValueError('lock must be a Lock') if exclude and not isinstance(exclude, Lock): raise ValueError('exclude must be a Lock') lock_hash = exclude_hash = None # temporarily add if lock: lock_hash = sha3(lock.as_bytes) self._cached_lock_hashes.append(lock_hash) # temporarily remove if exclude: exclude_hash = sha3(exclude.as_bytes) self._cached_lock_hashes.remove(exclude_hash) root = merkleroot(self._cached_lock_hashes) # remove the temporarily added hash if lock_hash: assert lock_hash in self._cached_lock_hashes self._cached_lock_hashes.remove(lock_hash) # reinclude the temporarily removed hash if exclude: self._cached_lock_hashes.append(exclude_hash) return root
def compute_merkleroot_with(self, include): merkletree = self.balance_proof.unclaimed_merkletree() merkletree.append(sha3(include.as_bytes)) return merkleroot(merkletree)
def test_ncc(): token_library_path = get_contract_path('StandardToken.sol') token_path = get_contract_path('HumanStandardToken.sol') s = tester.state() assert s.block.number < 1150000 s.block.number = 1158001 assert s.block.number > 1150000 # Token creation lib_token = s.abi_contract(None, path=token_library_path, language="solidity") token = s.abi_contract(None, path=token_path, language="solidity", libraries={'StandardToken': lib_token.address.encode('hex')}, constructor_parameters=[10000, "raiden", 0, "rd"]) # Getter creation lib_getter = s.abi_contract(None, path=decode_lib, language="solidity") getter = s.abi_contract(None, path=getter_path, language="solidity", libraries={'Decoder': lib_getter.address.encode('hex')}) INITIATOR_PRIVKEY = tester.k0 INITIATOR_ADDRESS = privtoaddr(INITIATOR_PRIVKEY) RECIPIENT_PRIVKEY = tester.k1 RECIPIENT_ADDRESS = privtoaddr(RECIPIENT_PRIVKEY) ASSET_ADDRESS = token.address HASHLOCK = sha3(INITIATOR_PRIVKEY) LOCK_AMOUNT = 29 LOCK_EXPIRATION = 31 LOCK = Lock(LOCK_AMOUNT, LOCK_EXPIRATION, HASHLOCK) LOCKSROOT = merkleroot([ sha3(LOCK.as_bytes), ]) # print direct_transfer.encode('hex') nonce = 1 asset = ASSET_ADDRESS balance = 1 recipient = RECIPIENT_ADDRESS locksroot = LOCKSROOT msg = DirectTransfer( nonce, asset, balance, recipient, locksroot, ).sign(INITIATOR_PRIVKEY) packed = msg.packed() direct_transfer = str(packed.data) # pure python recover sen = recover_publickey(direct_transfer[:148], str(packed.signature)) assert address_from_key(sen) == tester.a0 # addr = getter.ecTest(direct_transfer[:148], sig) # assert addr == INITIATOR_ADDRESS.encode('hex') sender = getter.getSender(direct_transfer) assert sender == tester.a0.encode('hex') # with sigSplit directly in Getters.sol r, s, v = getter.sigSplit(str(packed.signature)) assert r == str(packed.signature[:32]) assert s == str(packed.signature[32:64]) assert v == packed.signature[64] + 27 sender = getter.getSender(direct_transfer) assert sender == tester.a0.encode('hex')
INITIATOR_ADDRESS = privtoaddr(INITIATOR_PRIVKEY) SECRET = 'secret' RECIPIENT_PRIVKEY = 'y' * 32 RECIPIENT_ADDRESS = privtoaddr(RECIPIENT_PRIVKEY) TARGET_PRIVKEY = 'z' * 32 TARGET_ADDRESS = privtoaddr(TARGET_PRIVKEY) ASSET_ADDRESS = sha3('asset')[:20] HASHLOCK = sha3(INITIATOR_PRIVKEY) LOCK_AMOUNT = 29 LOCK_EXPIRATION = 31 LOCK = Lock(LOCK_AMOUNT, LOCK_EXPIRATION, HASHLOCK) LOCKSROOT = merkleroot([ sha3(LOCK.as_bytes), ]) # print direct_transfer.encode('hex') 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(None, path=decoder_path, language="solidity") assert data[0] == '\x04' # make sure data has right cmdid o1 = c.decodeSecret(data) assert o1[0][26:32] == 'secret'
def test_non_hash(): with pytest.raises(NoHash32Error): merkleroot(['not32bytes', 'neither'])
def test_empy(): r = merkleroot('') assert r == ''
def test_close_single_direct_transfer(state, channel, token, events): # pylint: disable=too-many-locals,too-many-statements # test tokens and distribute tokens assert token.balanceOf(tester.a0) == 10000 assert token.balanceOf(tester.a1) == 0 assert token.transfer(tester.a1, 5000) is True assert token.balanceOf(tester.a0) == 5000 assert token.balanceOf(tester.a1) == 5000 # test global variables assert channel.settleTimeout() == 30 assert channel.assetAddress() == token.address.encode('hex') assert channel.opened() == 0 assert channel.closed() == 0 assert channel.settled() == 0 # test participants variables changed when constructing assert channel.addressAndBalance()[0] == tester.a0.encode('hex') assert channel.addressAndBalance()[2] == tester.a1.encode('hex') # test atIndex() # private must be removed from the function in order to work # assert channel.atIndex(sha3('address1')[:20]) == 0 # assert channel.atIndex(sha3('address2')[:20]) == 1 # test deposit(uint) with pytest.raises(TransactionFailed): channel.deposit(30, sender=tester.k2) # not participant assert token.balanceOf(channel.address) == 0 assert token.approve(channel.address, 30) is True # allow the contract do deposit assert channel.addressAndBalance()[1] == 0 with pytest.raises(TransactionFailed): channel.deposit(5001) channel.deposit(30) assert channel.addressAndBalance()[1] == 30 assert token.balanceOf(channel.address) == 30 assert token.balanceOf(tester.a0) == 4970 assert channel.opened() == state.block.number # test open() # private must be removed from the function in order to work # assert channel.opened() == 0 # channel is not yet opened # channel.open() # assert channel.opened() > 0 # assert channel.opened() <= state.block.number # test partner(address) # private must be removed from the function in order to work # assert channel.partner(sha3('address1')[:20]) == sha3('address2')[:20].encode('hex') # assert channel.partner(sha3('address2')[:20]) == sha3('address1')[:20].encode('hex') # test addressAndBalance() a1, d1, a2, d2 = channel.addressAndBalance() assert a1 == tester.a0.encode('hex') assert a2 == tester.a1.encode('hex') assert d1 == 30 assert d2 == 0 # test close(message) initiator_privkey = tester.k0 recipient_privkey = tester.k1 recipient_address = privtoaddr(recipient_privkey) asset_address = token.address hashlock = sha3(initiator_privkey) lock_amount = 29 lock_expiration = 31 lock = Lock(lock_amount, lock_expiration, hashlock) locksroot = merkleroot([ sha3(lock.as_bytes), ]) nonce = 1 asset = asset_address transfered_amount = 1 recipient = recipient_address locksroot = locksroot msg = DirectTransfer( nonce, asset, transfered_amount, recipient, locksroot, ) msg.sign(initiator_privkey) packed = msg.packed() direct_transfer = str(packed.data) channel.closeSingleTransfer(direct_transfer) with pytest.raises(TransactionFailed): channel.closeSingleTransfer(direct_transfer, sender=tester.k2) # not participant assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex') # assert channel.participants(0)[10] == 1 # assert channel.participants(0)[11] == token.address.encode('hex') # assert channel.participants(0)[9] == tester.a0.encode('hex') # assert channel.participants(0)[12] == tester.a1.encode('hex') # assert channel.participants(0)[3] == 1 # assert channel.participants(0)[13] == locksroot # assert channel.participants(0)[7] == '\x00' * 32 assert len(events) == 2 assert events[0]['_event_type'] == 'ChannelNewBalance' assert events[0]['assetAddress'] == token.address.encode('hex') assert events[0]['balance'] == 30 assert events[0]['participant'] == tester.a0.encode('hex') assert events[1]['_event_type'] == 'ChannelClosed' assert events[1]['closingAddress'] == tester.a0.encode('hex') assert events[1]['blockNumber'] == state.block.number
def root(self): if not self._cached_root: self._cached_root = merkleroot(self._cached_lock_hashes) return self._cached_root
def test_empty(): assert merkleroot([]) == '' assert merkleroot(['']) == ''
def merkleroot_for_unclaimed(self): alllocks = chain( self.hashlock_pendinglocks.values(), self.hashlock_unclaimedlocks.values() ) return merkleroot(lock.lockhashed for lock in alllocks)
def test_single(): hash_0 = keccak('x') assert merkleroot([hash_0]) == hash_0
def merkleroot_for_unclaimed(self): alllocks = chain(self.hashlock_pendinglocks.values(), self.hashlock_unclaimedlocks.values()) return merkleroot(lock.lockhashed for lock in alllocks)
def test_unlock(token, channel, events, state): secret1 = 'x' * 32 hashlock1 = sha3(secret1) lock_amount1 = 29 lock_expiration1 = 1158003 lock1 = Lock(lock_amount1, lock_expiration1, hashlock1) lockhash1 = sha3(lock1.as_bytes) merkleproof1 = [lockhash1] locksroot1 = merkleroot([ lockhash1, ], merkleproof1) nonce = 10 asset = token.address transfered_amount = 1 recipient = tester.a1 msg1 = DirectTransfer( nonce, asset, transfered_amount, recipient, locksroot1, ) msg1.sign(tester.k0) packed = msg1.packed() direct_transfer1 = str(packed.data) secret2 = 'y' * 32 hashlock2 = sha3(secret2) lock_amount2 = 20 lock_expiration2 = 1158030 lock2 = Lock(lock_amount2, lock_expiration2, hashlock2) lockhash2 = sha3(lock2.as_bytes) merkleproof2 = [lockhash2] locksroot2 = merkleroot([ lockhash2, ], merkleproof2) msg2 = DirectTransfer( 2, # nonce asset, 3, # transfered_amount tester.a0, # recipient '', ) msg2.sign(tester.k1) packed = msg2.packed() direct_transfer2 = str(packed.data) channel.close(direct_transfer1, direct_transfer2) channel.unlock( str(lock1.as_bytes), ''.join(merkleproof1), secret1, ) # TODO: it must not be possible to unlock the same lock twive # with pytest.raises(TransactionFailed): # channel.unlock( # str(lock1.as_bytes), # ''.join(merkleproof1), # secret1, # ) # expiration has passed, should fail state.block.number = 1158031 with pytest.raises(TransactionFailed): channel.unlock( str(lock2.as_bytes), ''.join(merkleproof2), secret2, )
def test_duplicates(): h = keccak('x') h1 = keccak('y') assert merkleroot([h, h]) == h assert merkleroot([h, h1, h]) == merkleroot([h, h1])
def test_multiple_empty(): r = merkleroot(['', '']) assert r == ''
def test_update_mediated_transfer(state, token, channel, events): # test tokens and distribute tokens assert token.balanceOf(tester.a0) == 10000 assert token.balanceOf(tester.a1) == 0 assert token.transfer(tester.a1, 5000) is True assert token.balanceOf(tester.a0) == 5000 assert token.balanceOf(tester.a1) == 5000 # test global variables assert channel.settleTimeout() == 30 assert channel.assetAddress() == token.address.encode('hex') assert channel.opened() == 0 assert channel.closed() == 0 assert channel.settled() == 0 hashlock1 = sha3(tester.k0) lock_amount1 = 29 lock_expiration1 = 31 lock1 = Lock(lock_amount1, lock_expiration1, hashlock1) locksroot1 = merkleroot([ sha3(lock1.as_bytes), ]) hashlock2 = sha3(tester.k1) lock_amount2 = 29 lock_expiration2 = 31 lock2 = Lock(lock_amount2, lock_expiration2, hashlock2) locksroot2 = merkleroot([ sha3(lock2.as_bytes), ]) nonce = 1 asset = token.address transfered_amount = 3 recipient = tester.a2 locksroot = locksroot1 target = tester.a1 initiator = tester.a0 msg1 = MediatedTransfer( nonce, asset, transfered_amount, recipient, locksroot, lock1, target, initiator, fee=0, ) msg1.sign(tester.k0) packed = msg1.packed() mediated_transfer1 = str(packed.data) nonce = 2 asset = token.address transfered_amount = 4 recipient = tester.a2 locksroot = locksroot2 target = tester.a0 initiator = tester.a1 msg2 = MediatedTransfer( nonce, asset, transfered_amount, recipient, locksroot, lock2, target, initiator, fee=0, ) msg2.sign(tester.k1) packed = msg2.packed() mediated_transfer2 = str(packed.data) # not yet closed with pytest.raises(TransactionFailed): channel.updateTransfer(mediated_transfer1, sender=tester.k1) channel.close(mediated_transfer1, mediated_transfer2) # Test with message sender tester.a0 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex') # assert channel.participants(0)[10] == 1 # assert channel.participants(0)[11] == token.address.encode('hex') # assert channel.participants(0)[9] == tester.a0.encode('hex') # assert channel.participants(0)[12] == tester.a1.encode('hex') # assert channel.participants(0)[3] == 1 # assert channel.participants(0)[13] == locksroot1 # assert channel.participants(0)[7] == '\x00' * 32 # Test with message sender tester.a1 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex') # assert channel.participants(1)[10] == 2 # assert channel.participants(1)[11] == token.address.encode('hex') # assert channel.participants(1)[9] == tester.a1.encode('hex') # assert channel.participants(1)[12] == tester.a0.encode('hex') # assert channel.participants(1)[3] == 3 # assert channel.participants(1)[13] == locksroot2 # assert channel.participants(1)[7] == '\x00' * 32 hashlock3 = sha3(tester.k1) lock_amount3 = 29 lock_expiration3 = 31 lock3 = Lock(lock_amount3, lock_expiration3, hashlock3) locksroot3 = merkleroot([ sha3(lock3.as_bytes), ]) nonce = 3 asset = token.address transfered_amount = 4 recipient = tester.a2 locksroot = locksroot3 target = tester.a0 initiator = tester.a1 msg3 = MediatedTransfer( nonce, asset, transfered_amount, recipient, locksroot, lock3, target, initiator, fee=0, ) msg3.sign(tester.k1) packed = msg3.packed() mediated_transfer3 = str(packed.data) # closingAddress == getSender(message) with pytest.raises(TransactionFailed): channel.updateTransfer(mediated_transfer1) channel.updateTransfer(mediated_transfer3, sender=tester.k1) # Test with message sender tester.a1 # assert channel.participants(1)[10] == 3 # assert channel.participants(1)[11] == token.address.encode('hex') # assert channel.participants(1)[9] == tester.a1.encode('hex') # assert channel.participants(1)[12] == tester.a0.encode('hex') # assert channel.participants(1)[3] == 5 # assert channel.participants(1)[13] == locksroot3 # assert channel.participants(1)[7] == '\x00' * 32 msg4 = DirectTransfer( 1, # nonce token.address, # asset 5, # transfered_amount tester.a0, # recipient locksroot, ) msg4.sign(tester.k1) packed = msg4.packed() direct_transfer4 = str(packed.data) # nonce too low with pytest.raises(TransactionFailed): channel.updateTransfer(direct_transfer4, sender=tester.k1) # settleTimeout overdue state.block.number = 1158041 with pytest.raises(TransactionFailed): channel.updateTransfer(mediated_transfer3, sender=tester.k1) assert len(events) == 1 assert events[0]['_event_type'] == 'ChannelClosed' assert events[0]['blockNumber'] == 1158002 assert events[0]['closingAddress'] == tester.a0.encode('hex')
def test_single(): h = keccak('x') assert merkleroot([h]) == h
def test_settle(state, channel, token, asset_amount, events): half_amount = asset_amount / 2 assert token.transfer(tester.a1, half_amount) is True token1 = ABIContract( state, token.translator, token.address, default_key=tester.k1, ) assert token.approve(channel.address, half_amount) is True assert token1.approve(channel.address, half_amount) is True channel1 = ABIContract( state, channel.translator, channel.address, default_key=tester.k1, ) channel.deposit(half_amount) channel1.deposit(half_amount) secret1 = 'x' * 32 hashlock1 = sha3(secret1) lock_amount1 = 29 lock_expiration1 = 1158003 lock1 = Lock(lock_amount1, lock_expiration1, hashlock1) lockhash1 = sha3(lock1.as_bytes) merkleproof1 = [lockhash1] locksroot1 = merkleroot([lockhash1], merkleproof1) nonce1 = 1 asset = token.address transfered_amount1 = 1 recipient = tester.a1 locksroot = locksroot1 msg1 = DirectTransfer( nonce1, asset, transfered_amount1, recipient, locksroot, ) msg1.sign(tester.k0) packed = msg1.packed() direct_transfer1 = str(packed.data) secret2 = 'y' * 32 hashlock2 = sha3(secret2) lock_amount2 = 20 lock_expiration2 = 1158005 lock2 = Lock(lock_amount2, lock_expiration2, hashlock2) lockhash2 = sha3(lock2.as_bytes) merkleproof2 = [lockhash2] locksroot2 = merkleroot([lockhash2], merkleproof2) locksroot = locksroot2 nonce2 = 2 transfered_amount2 = 3 msg2 = DirectTransfer( nonce2, token.address, # asset transfered_amount2, tester.a0, # recipient locksroot, ) msg2.sign(tester.k1) packed = msg2.packed() direct_transfer2 = str(packed.data) # not yet closed. should fail with pytest.raises(TransactionFailed): channel.settle() channel.close(direct_transfer1, direct_transfer2) channel.unlock( str(lock1.as_bytes), ''.join(merkleproof1), secret1, ) channel.unlock(str(lock2.as_bytes), ''.join(merkleproof2), secret2, sender=tester.k1) secret4 = 'k' * 32 hashlock4 = sha3(secret4) lock_amount4 = 23 lock_expiration4 = 31 lock4 = Lock(lock_amount4, lock_expiration4, hashlock4) hashlock4 = sha3(lock4.as_bytes) merkleproof4 = [hashlock4] # has now message, should fail with pytest.raises(TransactionFailed): channel.unlock( str(lock4.as_bytes), ''.join(merkleproof4), secret4, sender=tester.k1, ) # still timeout with pytest.raises(TransactionFailed): channel.settle() state.block.number = state.block.number + 40 # timeout over channel.settle() balance1 = half_amount + (transfered_amount2 - transfered_amount1) + lock_amount1 - lock_amount2 balance2 = half_amount + (transfered_amount1 - transfered_amount2) - lock_amount1 + lock_amount2 assert token.balanceOf(tester.a0) == balance1 assert token.balanceOf(tester.a1) == balance2 # can settle only once with pytest.raises(TransactionFailed): channel.settle() assert len(events) == 6 assert events[0]['_event_type'] == 'ChannelNewBalance' assert events[0]['assetAddress'] == token.address.encode('hex') assert events[0]['participant'] == tester.a0.encode('hex') assert events[0]['balance'] == 50 assert events[1]['_event_type'] == 'ChannelNewBalance' assert events[1]['assetAddress'] == token.address.encode('hex') assert events[1]['participant'] == tester.a1.encode('hex') assert events[1]['balance'] == 50 assert events[2]['_event_type'] == 'ChannelClosed' assert events[2]['closingAddress'] == tester.a0.encode('hex') assert events[2]['blockNumber'] == 1158002 assert events[3]['_event_type'] == 'ChannelSecretRevealed' assert events[3]['secret'] == 'x' * 32 assert events[4]['_event_type'] == 'ChannelSecretRevealed' assert events[4]['secret'] == 'y' * 32 assert events[5]['_event_type'] == 'ChannelSettled' assert events[5]['blockNumber'] == state.block.number
def test_two_messages_mediated_transfer(state, token, channel, events): # test tokens and distribute tokens assert token.balanceOf(tester.a0) == 10000 assert token.balanceOf(tester.a1) == 0 assert token.transfer(tester.a1, 5000) is True assert token.balanceOf(tester.a0) == 5000 assert token.balanceOf(tester.a1) == 5000 # test global variables assert channel.settleTimeout() == 30 assert channel.assetAddress() == token.address.encode('hex') assert channel.opened() == 0 assert channel.closed() == 0 assert channel.settled() == 0 hashlock1 = sha3(tester.k0) lock_amount1 = 29 lock_expiration1 = 31 lock1 = Lock(lock_amount1, lock_expiration1, hashlock1) locksroot1 = merkleroot([ sha3(lock1.as_bytes), ]) hashlock2 = sha3(tester.k1) lock_amount2 = 29 lock_expiration2 = 31 lock2 = Lock(lock_amount2, lock_expiration2, hashlock2) locksroot2 = merkleroot([ sha3(lock2.as_bytes), ]) nonce = 1 asset = token.address transfered_amount = 3 recipient = tester.a2 locksroot = locksroot1 target = tester.a1 initiator = tester.a0 msg1 = MediatedTransfer( nonce, asset, transfered_amount, recipient, locksroot, lock1, target, initiator, fee=0, ) msg1.sign(tester.k0) packed = msg1.packed() mediated_transfer1 = str(packed.data) nonce = 2 asset = token.address transfered_amount = 4 recipient = tester.a2 locksroot = locksroot2 target = tester.a0 initiator = tester.a1 msg2 = MediatedTransfer( nonce, asset, transfered_amount, recipient, locksroot, lock2, target, initiator, fee=0, ) msg2.sign(tester.k1) packed = msg2.packed() mediated_transfer2 = str(packed.data) channel.close(mediated_transfer1, mediated_transfer2) # Test with message sender tester.a0 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex') # assert channel.participants(0)[10] == 1 # assert channel.participants(0)[11] == token.address.encode('hex') # assert channel.participants(0)[9] == tester.a0.encode('hex') # assert channel.participants(0)[12] == tester.a1.encode('hex') # assert channel.participants(0)[3] == 1 # assert channel.participants(0)[13] == locksroot1 # assert channel.participants(0)[7] == '\x00' * 32 # Test with message sender tester.a1 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex')
def test_two_messages_direct_transfer(state, token, channel, events): # test tokens and distribute tokens assert token.balanceOf(tester.a0) == 10000 assert token.balanceOf(tester.a1) == 0 assert token.transfer(tester.a1, 5000) is True assert token.balanceOf(tester.a0) == 5000 assert token.balanceOf(tester.a1) == 5000 # test global variables assert channel.settleTimeout() == 30 assert channel.assetAddress() == token.address.encode('hex') assert channel.opened() == 0 assert channel.closed() == 0 assert channel.settled() == 0 hashlock1 = sha3(tester.k0) lock_amount1 = 29 lock_expiration1 = 31 lock1 = Lock(lock_amount1, lock_expiration1, hashlock1) locksroot1 = merkleroot([ sha3(lock1.as_bytes), ]) nonce = 1 asset = token.address transfered_amount = 1 recipient = tester.a1 locksroot = locksroot1 msg1 = DirectTransfer( nonce, asset, transfered_amount, recipient, locksroot, ) msg1.sign(tester.k0) packed = msg1.packed() direct_transfer1 = str(packed.data) hashlock2 = sha3(tester.k1) lock_amount2 = 29 lock_expiration2 = 31 lock2 = Lock(lock_amount2, lock_expiration2, hashlock2) locksroot2 = merkleroot([ sha3(lock2.as_bytes), ]) locksroot = locksroot2 msg2 = DirectTransfer( 2, # nonce token.address, # asset 3, # transfered_amount tester.a0, # recipient locksroot, ) msg2.sign(tester.k1) packed = msg2.packed() direct_transfer2 = str(packed.data) channel.close(direct_transfer1, direct_transfer2) assert len(events) == 1 assert events[0]['_event_type'] == 'ChannelClosed' assert events[0]['closingAddress'] == tester.a0.encode('hex') assert events[0]['blockNumber'] == state.block.number with pytest.raises(TransactionFailed): # not participant channel.close(direct_transfer1, direct_transfer2, sender=tester.k2) # Test with message sender tester.a0 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex') # assert channel.participants(0)[10] == 1 # assert channel.participants(0)[11] == token.address.encode('hex') # assert channel.participants(0)[9] == tester.a0.encode('hex') # assert channel.participants(0)[12] == tester.a1.encode('hex') # assert channel.participants(0)[3] == 1 # assert channel.participants(0)[13] == locksroot1 # assert channel.participants(0)[7] == '\x00' * 32 # Test with message sender tester.a1 assert channel.closed() == state.block.number assert channel.closingAddress() == tester.a0.encode('hex')