Exemplo n.º 1
0
def test_endpointregistry(tester_chain, tester_events):
    account0 = tester.a0
    sender = address_encoder(account0)

    endpointregistry_path = get_contract_path('EndpointRegistry.sol')

    endpointregistry_compiled = _solidity.compile_contract(
        endpointregistry_path, "EndpointRegistry")
    tester_chain.head_state.log_listeners.append(tester_events.append)
    endpointregistry_address = tester_chain.contract(
        endpointregistry_compiled['bin'], language='evm')
    endpoint_registry = tester.ABIContract(tester_chain,
                                           endpointregistry_compiled['abi'],
                                           endpointregistry_address)

    endpoint_registry.registerEndpoint('127.0.0.1:4001')
    assert endpoint_registry.findAddressByEndpoint('127.0.0.1:4001') == sender
    assert endpoint_registry.findEndpointByAddress(sender) == b'127.0.0.1:4001'

    endpoint_registry.registerEndpoint('192.168.0.1:4002')
    assert endpoint_registry.findAddressByEndpoint(
        '192.168.0.1:4002') == sender
    assert endpoint_registry.findEndpointByAddress(
        sender) == b'192.168.0.1:4002'

    assert len(tester_events) == 2

    event0 = event_decoder(tester_events[0], endpoint_registry.translator)
    event1 = event_decoder(tester_events[1], endpoint_registry.translator)
    assert event0['_event_type'] == b'AddressRegistered'
    assert event1['_event_type'] == b'AddressRegistered'
Exemplo n.º 2
0
def init_chain_and_casper():
    genesis = casper_utils.make_casper_genesis(ALLOC, EPOCH_LENGTH, 100, 0.02,
                                               0.002)
    t = tester.Chain(genesis=genesis)
    casper = tester.ABIContract(t, casper_utils.casper_abi,
                                t.chain.config['CASPER_ADDRESS'])
    return t, casper
Exemplo n.º 3
0
 def generate_commit_message(self, state):
     epoch = state.block_number // self.epoch_length
     # PREPARE_COMMIT_CONSISTENCY
     if self.prev_prepare_epoch < self.prev_commit_epoch and self.prev_commit_epoch < epoch:
         return None
     # Create a Casper contract which we can use to get related values
     casper = tester.ABIContract(tester.State(state),
                                 casper_utils.casper_abi,
                                 self.chain.casper_address)
     validator_index = self.get_validator_index(state)
     _e, _a, _se, _sa, _pce = self.get_recommended_casper_msg_contents(
         casper, validator_index)
     # Make the commit message
     commit_msg = casper_utils.mk_commit(validator_index, _e, _a, _pce,
                                         self.key)
     try:  # Attempt to submit the commit, to make sure that it doesn't doesn't violate DBL_PREPARE & it is justified
         casper.commit(commit_msg)
     except tester.TransactionFailed:
         log.info(
             'Commit failed! Validator {} - blockhash {} - valcode addr {}'.
             format(self.get_validator_index(state),
                    self.epoch_blockhash(state, epoch),
                    utils.encode_hex(self.valcode_addr)))
         return None
     # Save the commit as now our last commit epoch
     log.info(
         'Commit submitted: validator %d - epoch %d - prev_commit_epoch %d - hash %s'
         % (self.get_validator_index(state), epoch, self.prev_commit_epoch,
            utils.encode_hex(self.epoch_blockhash(state, epoch))))
     self.prev_commit_epoch = epoch
     return commit_msg
def deploy_auxiliary_tester(tester_chain, tester_nettingchannel_library_address):
    contracts_path = os.path.join(get_project_root(), 'smart_contracts')
    raiden_remap = 'raiden={}'.format(contracts_path)

    contract_libraries = {
        'NettingChannelLibrary': hexlify(tester_nettingchannel_library_address),
    }

    auxiliary_tester_compiled = _solidity.compile_contract(
        get_relative_contract(__file__, 'AuxiliaryTester.sol'),
        'AuxiliaryTester',
        contract_libraries,
        extra_args=raiden_remap
    )
    auxiliary_tester_address = tester_chain.contract(
        auxiliary_tester_compiled['bin'],
        language='evm',
        sender=tester.k0
    )
    auxiliary = tester.ABIContract(
        tester_chain,
        auxiliary_tester_compiled['abi'],
        auxiliary_tester_address
    )
    tester_chain.mine(number_of_blocks=1)

    return auxiliary
def epoch_info(epoch):
    height = epoch * 50 + 49
    block = eth.chain.get_block_by_number(height)
    blockhash = block.hash
    ts = block.timestamp
    temp_state = eth.chain.mk_poststate_of_blockhash(blockhash)
    casper = tester.ABIContract(tester.State(temp_state),
                                casper_utils.casper_abi,
                                eth.chain.config['CASPER_ADDRESS'])

    ce, ese = casper.get_current_epoch(), casper.get_expected_source_epoch()
    deposit_scale_factor = casper.get_deposit_scale_factor(ce)
    storage = len(
        tester.State(temp_state).state.account_to_dict(
            eth.chain.config['CASPER_ADDRESS'])["storage"])

    info = {}
    info["number"] = height
    info["blockhash"] = encode_hex(blockhash)
    info["timestamp"] = ts
    info["difficulty"] = block.difficulty
    info["current_epoch"] = ce
    info["validators"] = validators(casper, deposit_scale_factor)
    info["lje"] = casper.get_last_justified_epoch()
    info["lfe"] = casper.get_last_finalized_epoch()
    info["votes"] = votes_and_deposits(casper, ce, ese, deposit_scale_factor)
    info["deposit_scale_factor"] = deposit_scale_factor
    info["storage"] = storage
    return info
Exemplo n.º 6
0
def create_registryproxy(tester_chain, tester_registry_address, log_listener):
    translator = tester.ContractTranslator(CONTRACT_MANAGER.get_abi(CONTRACT_REGISTRY))
    tester_chain.head_state.log_listeners.append(log_listener)
    registry_abi = tester.ABIContract(
        tester_chain,
        translator,
        tester_registry_address,
    )
    return registry_abi
Exemplo n.º 7
0
def create_tokenproxy(tester_chain, tester_token_address, log_listener):
    translator = tester.ContractTranslator(
        CONTRACT_MANAGER.get_abi(CONTRACT_HUMAN_STANDARD_TOKEN))
    tester_chain.head_state.log_listeners.append(log_listener)
    token_abi = tester.ABIContract(
        tester_chain,
        translator,
        tester_token_address,
    )
    return token_abi
Exemplo n.º 8
0
def create_channelmanager_proxy(tester_chain, tester_channelmanager_address, log_listener):
    translator = tester.ContractTranslator(
        CONTRACT_MANAGER.get_abi(CONTRACT_CHANNEL_MANAGER)
    )
    channel_manager_abi = tester.ABIContract(
        tester_chain,
        translator,
        tester_channelmanager_address,
    )
    tester_chain.head_state.log_listeners.append(log_listener)
    return channel_manager_abi
Exemplo n.º 9
0
def create_nettingchannel_proxy(tester_chain, tester_nettingchannel_address, log_listener):
    translator = tester.ContractTranslator(
        CONTRACT_MANAGER.get_abi(CONTRACT_NETTING_CHANNEL)
    )
    tester_chain.head_state.log_listeners.append(log_listener)
    netting_channel_abi = tester.ABIContract(
        tester_chain,
        translator,
        tester_nettingchannel_address,
    )
    return netting_channel_abi
Exemplo n.º 10
0
 def get_validator_index(self, state):
     t = tester.State(state.ephemeral_clone())
     t.state.gas_limit = 9999999999
     casper = tester.ABIContract(t, casper_utils.casper_abi,
                                 self.chain.casper_address)
     if self.valcode_addr is None:
         raise Exception('Valcode address not set')
     try:
         return casper.get_validator_indexes(self.coinbase)
     except tester.TransactionFailed:
         return None
Exemplo n.º 11
0
    def __init__(self, tester_chain, private_key, address):
        if len(tester_chain.head_state.get_code(address)) == 0:
            raise Exception('Contract code empty')

        self.address = address
        self.tester_chain = tester_chain
        self.private_key = private_key

        self.proxy = tester.ABIContract(
            tester_chain,
            CONTRACT_MANAGER.get_abi(CONTRACT_HUMAN_STANDARD_TOKEN), address)
Exemplo n.º 12
0
    def __init__(self, tester_chain, private_key, address):
        if len(tester_chain.head_state.get_code(address)) == 0:
            raise Exception('Contract code empty')

        self.address = address
        self.tester_chain = tester_chain
        self.private_key = private_key

        self.proxy = tester.ABIContract(
            tester_chain, CONTRACT_MANAGER.get_abi(CONTRACT_CHANNEL_MANAGER),
            address)
        self.participant_filter = defaultdict(list)
        self.address_filter = defaultdict(list)
Exemplo n.º 13
0
def init_multi_validator_casper(num_validators):
    """"
    Initialize Casper genesis, login an initial validator, and create num_validators validators
    """
    # Begin tests
    genesis = casper_utils.make_casper_genesis(ALLOC, EPOCH_LENGTH, 25, 0.02,
                                               0.002)
    t = tester.Chain(genesis=genesis)
    casper = tester.ABIContract(t, casper_utils.casper_abi,
                                t.chain.config['CASPER_ADDRESS'])
    # Get the val code addresses and network
    network = validator.Network()
    # Initialize validators, starting with the first validator
    validators = []
    # Add our validators
    for i in range(0, num_validators):
        log.info('Adding validator {}'.format(i))
        validators.append(
            validator.Validator(tester.keys[i], copy.deepcopy(genesis),
                                network))
    t = tester.Chain(genesis=genesis)
    casper = tester.ABIContract(t, casper_utils.casper_abi,
                                t.chain.env.config['CASPER_ADDRESS'])
    t.mine(26)
    # Pump the blocks into the validators
    for i in range(1, 27):
        block = t.chain.get_block_by_number(i)
        log.info('Pumping block: {} {}'.format(utils.encode_hex(block.hash),
                                               block.transactions))
        for v in validators:
            v.chain.add_block(block)
    if num_validators < 1:
        return t, casper
    # Submit deposits for new validators
    for i in range(0, num_validators):
        validators[i].broadcast_deposit()
        validators[0].mine_and_broadcast_blocks(1)
    return t, casper, validators
Exemplo n.º 14
0
def get_contract_with_gas_estimation_for_constants(source_code, *args,
                                                   **kwargs):
    abi = tester.languages['viper'].mk_full_signature(source_code)
    # Take out constants from the abi for the purpose of gas estimation
    for func in abi:
        func['constant'] = False
    ct = tester.ContractTranslator(abi)
    byte_code = tester.languages['viper'].compile(source_code) + (
        ct.encode_constructor_arguments(kwargs['args']) if kwargs else b'')
    address = chain.tx(to=b'', data=byte_code)
    contract = tester.ABIContract(chain, abi, address)
    for func_name in contract.translator.function_data:
        set_decorator_to_contract_function(contract, source_code, func_name)
    return contract
Exemplo n.º 15
0
    def __init__(self, tester_chain, private_key, address):
        if len(tester_chain.head_state.get_code(address)) == 0:
            raise Exception('Contract code empty')

        self.address = address
        self.tester_chain = tester_chain
        self.private_key = private_key

        self.registry_proxy = tester.ABIContract(
            self.tester_chain, CONTRACT_MANAGER.get_abi(CONTRACT_REGISTRY),
            self.address)
        self.tokenadded_filters = list()

        self.address_to_channelmanager = dict()
        self.token_to_channelmanager = dict()
Exemplo n.º 16
0
 def generate_prepare_message(self, state):
     epoch = state.block_number // self.epoch_length
     # NO_DBL_PREPARE: Don't prepare if we have already
     if epoch in self.prepares:
         return None
     # Create a Casper contract which we can use to get related values
     casper = tester.ABIContract(tester.State(state),
                                 casper_utils.casper_abi,
                                 self.chain.casper_address)
     # Get the ancestry hash and source ancestry hash
     validator_index = self.get_validator_index(state)
     _e, _a, _se, _sa, _pce = self.get_recommended_casper_msg_contents(
         casper, validator_index)
     # PREPARE_COMMIT_CONSISTENCY
     if _se < self.prev_commit_epoch and self.prev_commit_epoch < epoch:
         return None
     prepare_msg = casper_utils.mk_prepare(validator_index, _e, _a, _se,
                                           _sa, self.key)
     try:  # Attempt to submit the prepare, to make sure that it is justified
         casper.prepare(prepare_msg)
     except tester.TransactionFailed:
         log.info(
             'Prepare failed! Validator {} - hash justified {} - validator start {} - valcode addr {}'
             .format(
                 self.get_validator_index(state),
                 casper.get_consensus_messages__ancestry_hash_justified(
                     epoch, _a),
                 casper.get_validators__dynasty_start(validator_index),
                 utils.encode_hex(self.valcode_addr)))
         return None
     # Save the prepare message we generated
     self.prepares[epoch] = prepare_msg
     # Save the highest source epoch we have referenced in our prepare's source epoch
     if epoch > self.prev_prepare_epoch:
         self.prev_prepare_epoch = epoch
     log.info(
         'Prepare submitted: validator %d - epoch %d - prev_commit_epoch %d - hash %s'
         % (self.get_validator_index(state), epoch, self.prev_commit_epoch,
            utils.encode_hex(self.epoch_blockhash(state, epoch))))
     return prepare_msg
Exemplo n.º 17
0
def main():
    c = tester.Chain()
    owner = tester.a0
    owner_key = tester.k0

    whitelist_evm, whitelist_abi = sol_compile('whitelist.sol')
    addr = c.contract(whitelist_evm, language='evm', sender=owner_key)
    whitelist = tester.ABIContract(c, whitelist_abi, addr)

    assert binascii.unhexlify(whitelist.owner()[2:]) == owner

    whitelist.add(owner)
    assert whitelist.check(owner)
    addresses = [tester.a1, tester.a2, tester.a3]
    whitelist.add_all(addresses)
    assert all(map(whitelist.check, addresses))
    whitelist.remove(owner)
    assert not whitelist.check(owner)
    for a in addresses:
        whitelist.remove(a)
        assert not whitelist.check(a)
    whitelist.destroy()

    print('TEST PASSED')
Exemplo n.º 18
0
 def __init__(self, test_string, epoch_length, withdrawal_delay,
              base_interest_factor, base_penalty_factor):
     if test_string == '':
         raise Exception("Please pass in a valid test string")
     self.test_string = test_string
     self.genesis = casper_utils.make_casper_genesis(
         ALLOC, epoch_length, withdrawal_delay, base_interest_factor,
         base_penalty_factor)
     self.t = tester.Chain(genesis=self.genesis)
     self.casper = tester.ABIContract(
         self.t, casper_utils.casper_abi,
         self.t.chain.env.config['CASPER_ADDRESS'])
     self.saved_blocks = dict()
     self.validators = dict()
     # Register token handlers
     self.handlers = dict()
     self.handlers['B'] = self.mine_blocks
     self.handlers['J'] = self.join
     self.handlers['P'] = self.prepare
     self.handlers['C'] = self.commit
     self.handlers['S'] = self.save_block
     self.handlers['R'] = self.revert_to_block
     self.handlers['H'] = self.check_head_equals_block
     self.handlers['X'] = self.slash
Exemplo n.º 19
0
def pool(casper_chain, pool_abi, pool_address):
    return tester.ABIContract(casper_chain, pool_abi, pool_address)
Exemplo n.º 20
0
init_txs, casper_address = mk_initializers(casper_config, t.k0)
for tx in init_txs:
    if s.head_state.gas_used + tx.startgas > s.head_state.gas_limit:
        s.mine(1)
    s.direct_tx(tx)

ct = abi.ContractTranslator(purity_checker_abi)
# Check that the RLP decoding library and the sig hashing library are "pure"
assert utils.big_endian_to_int(
    s.tx(t.k0, purity_checker_address, 0,
         ct.encode('submit', [viper_rlp_decoder_address]))) == 1
assert utils.big_endian_to_int(
    s.tx(t.k0, purity_checker_address, 0,
         ct.encode('submit', [sig_hasher_address]))) == 1

casper = t.ABIContract(s, casper_abi, casper_address)
s.mine(1)

# Helper functions for making a prepare, commit, login and logout message


def mk_prepare(validator_index, epoch, ancestry_hash, source_epoch,
               source_ancestry_hash, key):
    sighash = utils.sha3(
        rlp.encode([
            validator_index, epoch, ancestry_hash, source_epoch,
            source_ancestry_hash
        ]))
    v, r, s = utils.ecdsa_raw_sign(sighash, key)
    sig = utils.encode_int32(v) + utils.encode_int32(r) + utils.encode_int32(s)
    return rlp.encode([
Exemplo n.º 21
0
t.gas_limit = 9999999
t.STARTGAS = 2000000
c.mine(1)

EPOCH_LENGTH = c.chain.config['EPOCH_LENGTH']

ct = abi.ContractTranslator(purity_checker_abi)
# Check that the RLP decoding library and the sig hashing library are "pure"
assert utils.big_endian_to_int(
    c.tx(t.k0, purity_checker_address, 0,
         ct.encode('submit', [viper_rlp_decoder_address]))) == 1
assert utils.big_endian_to_int(
    c.tx(t.k0, purity_checker_address, 0,
         ct.encode('submit', [sig_hasher_address]))) == 1

casper = t.ABIContract(c, casper_abi, c.chain.config['CASPER_ADDRESS'])
c.mine(1)

# Begin the test

print("Starting tests")
# Initialize the first epoch
c.mine(EPOCH_LENGTH - c.head_state.block_number)
# casper.initialize_epoch(1)
assert casper.get_nextValidatorIndex() == 0
assert casper.get_current_epoch() == 1
print("Epoch initialized")

# Deposit one validator
induct_validator(c, casper, t.k1, 200 * 10**18)
# Mine two epochs
Exemplo n.º 22
0
 def add_block(self, block):
     # ~~~ Validate ~~~~ #
     # Validate that the block should be added
     if not self.should_add_block(block):
         return False
     # ~~~ Store ~~~~ #
     # Store the block
     self.db.put(block.header.hash, rlp.encode(block))
     self.add_child(block)
     if block.number % self.config['EPOCH_LENGTH'] == 0:
         self.db.put(b'cp_subtree_score' + block.hash, 0)
     # Store the state root
     if block.header.prevhash == self.head_hash:
         temp_state = self.state.ephemeral_clone()
     else:
         temp_state = self.mk_poststate_of_blockhash(block.header.prevhash)
     apply_block(temp_state, block)
     self.db.put(b'state:' + block.header.hash, temp_state.trie.root_hash)
     # ~~~ Finality Gadget Fork Choice ~~~~ #
     old_head_chekpoint = self.head_checkpoint
     # Store the new score
     cp_hash = self.get_prev_checkpoint_hash(block.hash)
     casper = tester.ABIContract(tester.State(temp_state),
                                 casper_utils.casper_abi,
                                 self.config['CASPER_ADDRESS'])
     try:
         new_score = casper.get_main_hash_committed_frac()
         log.info('Got new score! {}'.format(new_score))
     except tester.TransactionFailed:
         new_score = 0
     if self.get_checkpoint_score(
             cp_hash) < new_score or self.get_checkpoint_score(
                 cp_hash) == 0:
         log.info(
             'Updating checkpoint score. Block num: {} - New Score: {}'.
             format(self.get_block(cp_hash).number, new_score))
         self.db.put(b'cp_score:' + cp_hash, new_score)
     # Update our view
     self.update_subtree_scores_and_child_pointers(cp_hash)
     cp = self.get_block(cp_hash)
     # Store the block as its checkpoint child if is is heavier than the current child
     p_cp = cp
     while cp is not self.genesis and self.get_checkpoint_score(
             cp.hash) == 0:
         cp = self.get_prev_checkpoint_block(cp)
     log.info(
         'Recieved block. Block num: {} - Prev cp num: {} - Prev committed cp num: {} - Head cp num: {} - Prev committed cp score: {} - Current head cp score: {}'
         .format(block.number, p_cp.number, cp.number,
                 self.head_checkpoint.number,
                 self.get_checkpoint_score(cp.hash),
                 self.get_checkpoint_score(self.checkpoint_head_hash)))
     log.info('head cp hash: {} - block prev cp hash: {}'.format(
         utils.encode_hex(cp_hash),
         utils.encode_hex(self.checkpoint_head_hash)))
     # Recompute head
     self.recompute_head_checkpoint(cp)
     # Set a new head if required
     log.info('Head cp num: {} - block prev cp num: {}'.format(
         self.head_checkpoint.number, cp.number))
     if self.head_checkpoint == cp:
         if self.head_checkpoint == old_head_chekpoint:
             log.info(
                 'Head checkpoint == old head. CP Head Num: {} - Head diff: {} - Block diff: {}'
                 .format(self.head_checkpoint.number,
                         self.get_pow_difficulty(self.head),
                         self.get_pow_difficulty(block)))
             if self.get_pow_difficulty(
                     self.head) < self.get_pow_difficulty(block):
                 self.set_head(block)
         else:
             log.info('Head checkpoint changed to cp number: {}'.format(
                 self.head_checkpoint.number))
             new_head, _ = self.find_heaviest_pow_block(
                 self.head_checkpoint)
             self.set_head(new_head)
     else:
         log.info('Skipping block: Head checkpoint is not equal to cp!')
     # Are there blocks that we received that were waiting for this block?
     # If so, process them.
     if block.header.hash in self.parent_queue:
         for _blk in self.parent_queue[block.header.hash]:
             self.add_block(_blk)
         del self.parent_queue[block.header.hash]
     return True
Exemplo n.º 23
0
s = tester.Chain()
s.mine()

contract_path = './contractNipopow.sol'
contract_name = 'Crosschain'
contract_compiled = compile_file(contract_path)

contract_data = solidity_get_contract_data(
    contract_compiled,
    contract_path,
    contract_name,
)

contract_address = s.contract(contract_data['bin'], language='evm')

contract_abi = tester.ABIContract(s, contract_data['abi'], contract_address)

import cPickle as pickle
proof = pickle.load(open('proof.pkl'))
proof_f = pickle.load(open('proof-fork50k.pkl'))
proof2 = pickle.load(open('proof-2.pkl'))
proof3 = pickle.load(open('proof-3.pkl'))
proof4 = pickle.load(open('proof-4.pkl'))

# Take a snapshot before trying out test cases
#try: s.revert(s.snapshot())
#except: pass # FIXME: I HAVE NO IDEA WHY THIS IS REQUIRED
s.mine()
base = s.snapshot()

Exemplo n.º 24
0
                             language='vyper',
                             args=[tester.accounts[0], FIVE_DAYS])
# Generate ABI from contract source code
abi = tester.languages['vyper'].mk_full_signature(source_code)
print("ABI: %s", abi)
# Generate Contract Translator from ABI
contract_translator = tester.ContractTranslator(abi)
# Generate Bytecode from contract source code
contract_constructor_args = []
byte_code = tester.languages['vyper'].compile(source_code) + \
    get_encoded_contract_constructor_arguments(contract_constructor_args)
# print("Bytecode: %s", byte_code)
address = tester.s.tx(to=b'', data=byte_code)
print("Address: %s", address)
# Instantiate contract from its ABI and Bytecode
contract_instance = tester.ABIContract(tester.s, abi, address)
print("Contract Instance: %s", contract_instance)
# Execute method on the tester chain to check the beneficiary is correct
assert ethereum_utils.remove_0x_head(
    tester.c.beneficiary()) == tester.accounts[0].hex()
# Execute method on the tester chain to check bidding time is 5 days
assert tester.c.auction_end() == tester.s.head_state.timestamp + FIVE_DAYS
# Revert chain state on failed transaction
tester.s.revert(initial_chain_state)

# Instantiate and deploy contract
contract_instance_web3 = web3.eth.contract(abi=abi, bytecode=byte_code)
print("Contract Instance with Web3: %s", contract_instance)

# Note: If we're running a Geth Node then I can use
# `web3.personal.listAccounts` but when I am using Ganache CLI
Exemplo n.º 25
0
def mk_casper_tester(validator):
    return tester.ABIContract(tester.State(validator.chain.state),
                              casper_utils.casper_abi,
                              validator.chain.casper_address)