예제 #1
0
def run_block_test(params, config_overrides=None):
    if config_overrides is None:
        config_overrides = {}
    env = Env(db.EphemDB())
    genesis_decl = {}
    for param in ("bloom", "timestamp", "nonce", "extraData", "gasLimit",
                  "coinbase", "difficulty", "parentHash", "mixHash",
                  "gasUsed"):
        genesis_decl[param] = params["genesisBlockHeader"][param]
    genesis_decl["alloc"] = params["pre"]

    old_config = copy.deepcopy(env.config)
    for k, v in config_overrides.items():
        env.config[k] = v

    # print('overrides', config_overrides)
    s = state_from_genesis_declaration(genesis_decl, env, allow_empties=True)
    initialize_genesis_keys(s, Block(s.prev_headers[0], [], []))
    c = chain.Chain(genesis=s, localtime=2**99)
    # print('h', encode_hex(c.state.prev_headers[0].state_root))
    # print(c.state.to_dict())
    # print(params["pre"])
    assert c.state.env == env
    assert c.state.prev_headers[0].state_root == safe_decode(
        params["genesisBlockHeader"]["stateRoot"]), (
            encode_hex(c.state.prev_headers[0].state_root),
            params["genesisBlockHeader"]["stateRoot"])
    assert c.state.trie.root_hash == safe_decode(
        params["genesisBlockHeader"]["stateRoot"])
    assert c.state.prev_headers[0].hash == safe_decode(
        params["genesisBlockHeader"]["hash"])
    #print('std', c.state.to_dict())

    for blk in params["blocks"]:
        if 'blockHeader' not in blk:
            success = True
            try:
                rlpdata = safe_decode(blk["rlp"][2:])
                success = c.add_block(rlp.decode(rlpdata, Block))
            except (ValueError, TypeError, AttributeError, VerificationFailed,
                    DecodingError, DeserializationError, InvalidTransaction,
                    InvalidNonce, KeyError) as e:
                success = False
            assert not success
        else:
            rlpdata = safe_decode(blk["rlp"][2:])
            assert c.add_block(rlp.decode(rlpdata, Block))
    env.config = old_config
    def __init__(self, app):
        self.config = app.config
        sce = self.config['eth']
        if int(sce['pruning']) >= 0:
            self.db = RefcountDB(app.services.db)
            if "I am not pruning" in self.db.db:
                raise RuntimeError(
                    "The database in '{}' was initialized as non-pruning. "
                    "Can not enable pruning now.".format(
                        self.config['data_dir']))
            self.db.ttl = int(sce['pruning'])
            self.db.db.put("I am pruning", "1")
        else:
            self.db = app.services.db
            if "I am pruning" in self.db:
                raise RuntimeError(
                    "The database in '{}' was initialized as pruning. "
                    "Can not disable pruning now".format(
                        self.config['data_dir']))
            self.db.put("I am not pruning", "1")

        if 'network_id' in self.db:
            db_network_id = self.db.get('network_id')
            if db_network_id != str(sce['network_id']):
                raise RuntimeError(
                    "The database in '{}' was initialized with network id {} and can not be used "
                    "when connecting to network id {}. Please choose a different data directory."
                    .format(self.config['data_dir'], db_network_id,
                            sce['network_id']))

        else:
            self.db.put('network_id', str(sce['network_id']))
            self.db.commit()

        assert self.db is not None

        super(ChainService, self).__init__(app)
        log.info('initializing chain')
        coinbase = app.services.accounts.coinbase
        env = Env(self.db, sce['block'])
        self.chain = Chain(env,
                           new_head_cb=self._on_new_head,
                           coinbase=coinbase)

        log.info('chain at', number=self.chain.head.number)
        if 'genesis_hash' in sce:
            assert sce['genesis_hash'] == self.chain.genesis.hex_hash(), \
                "Genesis hash mismatch.\n  Expected: %s\n  Got: %s" % (
                    sce['genesis_hash'], self.chain.genesis.hex_hash())

        self.synchronizer = Synchronizer(self, force_sync=None)

        self.block_queue = Queue(maxsize=self.block_queue_size)
        self.transaction_queue = Queue(maxsize=self.transaction_queue_size)
        self.add_blocks_lock = False
        self.add_transaction_lock = gevent.lock.Semaphore()
        self.broadcast_filter = DuplicatesFilter()
        self.on_new_head_cbs = []
        self.on_new_head_candidate_cbs = []
        self.newblock_processing_times = deque(maxlen=1000)
예제 #3
0
def init_state(env, pre):
    # Setup env
    state = State(
        env=Env(config=konfig),
        block_prevhash=decode_hex(remove_0x_head(env['previousHash'])),
        prev_headers=[mk_fake_header(i) for i in range(parse_int_or_hex(env['currentNumber']) - 1,
                                                       max(-1, parse_int_or_hex(env['currentNumber']) - 257), -1)],
        block_number=parse_int_or_hex(env['currentNumber']),
        block_coinbase=decode_hex(remove_0x_head(env['currentCoinbase'])),
        block_difficulty=parse_int_or_hex(env['currentDifficulty']),
        gas_limit=parse_int_or_hex(env['currentGasLimit']),
        timestamp=parse_int_or_hex(env['currentTimestamp']))

    # Fill up pre
    for address, h in list(pre.items()):
        assert len(address) in (40, 42)
        address = decode_hex(remove_0x_head(address))
        assert set(h.keys()) == set(['code', 'nonce', 'balance', 'storage'])
        state.set_nonce(address, parse_int_or_hex(h['nonce']))
        state.set_balance(address, parse_int_or_hex(h['balance']))
        state.set_code(address, decode_hex(remove_0x_head(h['code'])))
        for k, v in h['storage'].items():
            state.set_storage_data(address,
                                   big_endian_to_int(decode_hex(k[2:])),
                                   big_endian_to_int(decode_hex(v[2:])))

    state.commit(allow_empties=True)
    # state.commit()
    return state
예제 #4
0
파일: conftest.py 프로젝트: zackster/augur
    def __init__(self):
        tester.GASPRICE = 0
        tester.STARTGAS = long(6.7 * 10**7)
        config_metropolis['GASLIMIT_ADJMAX_FACTOR'] = .000000000001
        config_metropolis['GENESIS_GAS_LIMIT'] = 2**60
        config_metropolis['MIN_GAS_LIMIT'] = 2**60
        config_metropolis['BLOCK_GAS_LIMIT'] = 2**60

        for a in range(10):
            tester.base_alloc[getattr(tester, 'a%i' % a)] = {'balance': 10**24}

        self.chain = Chain(env=Env(config=config_metropolis))
        self.contracts = {}
        self.testerAddress = self.generateTesterMap('a')
        self.testerKey = self.generateTesterMap('k')
        self.testerAddressToKey = dict(zip(self.testerAddress.values(), self.testerKey.values()))
        if path.isfile('./allFiredEvents'):
            remove_file('./allFiredEvents')
        self.relativeContractsPath = '../source/contracts'
        self.relativeTestContractsPath = 'solidity_test_helpers'
        self.externalContractsPath = '../source/contracts/external'
        self.coverageMode = pytest.config.option.cover
        self.subFork = pytest.config.option.subFork
        if self.coverageMode:
            self.chain.head_state.log_listeners.append(self.writeLogToFile)
            self.relativeContractsPath = '../coverageEnv/contracts'
            self.relativeTestContractsPath = '../coverageEnv/solidity_test_helpers'
            self.externalContractsPath = '../coverageEnv/contracts/external'
예제 #5
0
def test_genesis():
    for profile in ['frontier']:  # fixme olympics

        config = dict(eth=dict())

        # Set config values based on profile selection
        merge_dict(config, PROFILES[profile])

        # Load genesis config
        update_config_from_genesis_json(config, config['eth']['genesis'])

        konfig.update_config_with_defaults(
            config, {'eth': {
                'block': blocks.default_config
            }})

        print config['eth'].keys()
        bc = config['eth']['block']
        print bc.keys()
        env = Env(DB(), bc)

        genesis = blocks.genesis(env)
        print 'genesis.hash', genesis.hash.encode('hex')
        print 'expected', config['eth']['genesis_hash']
        assert genesis.hash == config['eth']['genesis_hash'].decode('hex')
예제 #6
0
파일: export.py 프로젝트: qfkjbpc/eth_bpc
def get_chain(data_dir=default_data_dir):
    """
    returns an ethereum.chain.Chain instance
    """
    dbfile = os.path.join(data_dir, 'leveldb')
    db = LevelDB(dbfile)
    return Chain(Env(db))
예제 #7
0
def make_casper_genesis(validators, alloc, timestamp=0, epoch_length=100):
    state = mk_basic_state(alloc, None, env=Env(config=casper_config))
    state.gas_limit = 10**8 * (len(validators) + 1)
    state.timestamp = timestamp
    state.block_difficulty = 1

    header = state.prev_headers[0]
    header.timestamp = timestamp
    header.difficulty = 1

    ct = get_casper_ct()
    initialize(state)
    casper_contract_bootstrap(state,
                              timestamp=header.timestamp,
                              gas_limit=header.gas_limit)

    # Add validators
    for i, (vcode, deposit_size, randao_commitment,
            address) in enumerate(validators):
        validator_inject(state, vcode, deposit_size, randao_commitment,
                         address, i, ct)

    # Start the first epoch
    casper_start_epoch(state)

    assert call_casper(state, 'getEpoch', []) == 0
    assert call_casper(state, 'getTotalDeposits',
                       []) == sum([d for a, d, r, a in validators])
    state.set_storage_data(
        utils.normalize_address(state.config['METROPOLIS_BLOCKHASH_STORE']),
        state.block_number % state.config['METROPOLIS_WRAPAROUND'],
        header.hash)
    state.commit()

    return state
예제 #8
0
    def _update_head_candidate(self, forward_pending_transactions=True):
        "after new head is set"
        log.debug('updating head candidate')
        # collect uncles
        blk = self.head  # parent of the block we are collecting uncles for
        uncles = set(u.header for u in self.get_brothers(blk))
        for i in range(self.env.config['MAX_UNCLE_DEPTH'] + 2):
            for u in blk.uncles:
                assert isinstance(u, blocks.BlockHeader)
                uncles.discard(u)
            if blk.has_parent():
                blk = blk.get_parent()
        assert not uncles or max(u.number for u in uncles) <= self.head.number
        uncles = list(uncles)[:self.env.config['MAX_UNCLES']]

        # create block
        ts = max(int(time.time()), self.head.timestamp + 1)
        _env = Env(OverlayDB(self.head.db), self.env.config, self.env.global_config)
        head_candidate = blocks.Block.init_from_parent(self.head, coinbase=self._coinbase,
                                                       timestamp=ts, uncles=uncles, env=_env)
        assert head_candidate.validate_uncles()

        self.pre_finalize_state_root = head_candidate.state_root
        head_candidate.finalize()

        # add transactions from previous head candidate
        old_head_candidate = self.head_candidate
        self.head_candidate = head_candidate
        if old_head_candidate is not None and forward_pending_transactions:
            log.debug('forwarding pending transactions')
            for tx in old_head_candidate.get_transactions():
                self.add_transaction(tx)
        else:
            log.debug('discarding pending transactions')
def test_genesis_config():
    "test setting genesis alloc using the config"
    alloc = {
        '1' * 40: {
            'wei': 1
        },  # wei
        '2' * 40: {
            'balance': 2
        },  # balance
        '3' * 20: {
            'balance': 3
        },  # 20 bytes
    }
    config = dict(eth=dict(genesis=dict(alloc=alloc)))
    konfig.update_config_with_defaults(
        config, {'eth': {
            'block': blocks.default_config
        }})

    # Load genesis config
    update_config_from_genesis_json(config, config['eth']['genesis'])

    bc = config['eth']['block']
    pprint(bc)
    env = Env(DB(), bc)

    genesis = blocks.genesis(env)
    for address, value_dict in alloc.items():
        value = value_dict.values()[0]
        assert genesis.get_balance(address) == value
예제 #10
0
 def resetToSnapshot(self, snapshot):
     if not 'state' in snapshot: raise "snapshot is missing 'state'"
     if not 'contracts' in snapshot: raise "snapshot is missing 'contracts'"
     self.chain = Chain(genesis=snapshot['state'], env=Env(config=config_metropolis))
     self.contracts = {}
     for contractName in snapshot['contracts']:
         contract = snapshot['contracts'][contractName]
         self.contracts[contractName] = ABIContract(self.chain, contract['translator'], contract['address'])
예제 #11
0
 def __init__(self, root=b'', env=Env(), **kwargs):
     self.env = env
     self.trie = SecureTrie(Trie(self.db, root))
     for k, v in STATE_DEFAULTS.items():
         setattr(self, k, kwargs.get(k, copy.copy(v)))
     self.journal = []
     self.cache = {}
     self.log_listeners = []
예제 #12
0
def get_contract_code(init_code):
    s = State(env=Env(config=casper_config))
    s.gas_limit = 10**9
    apply_transaction(s, Transaction(0, 0, 10**8, '', 0, init_code))
    addr = utils.mk_metropolis_contract_address(
        casper_config['METROPOLIS_ENTRY_POINT'], init_code)
    o = s.get_code(addr)
    assert o
    return o
예제 #13
0
def get_env(env):
    d = {
        None: config_metropolis,
        'mainnet': default_config,
        'homestead': config_homestead,
        'tangerine': config_tangerine,
        'spurious': config_spurious,
        'metropolis': config_metropolis,
    }
    return env if isinstance(env, Env) else Env(config=d[env])
예제 #14
0
파일: conftest.py 프로젝트: zackster/augur
 def resetToSnapshot(self, snapshot):
     if not 'state' in snapshot: raise "snapshot is missing 'state'"
     if not 'contracts' in snapshot: raise "snapshot is missing 'contracts'"
     self.chain = Chain(genesis=snapshot['state'], env=Env(config=config_metropolis))
     if self.coverageMode:
         self.chain.head_state.log_listeners.append(self.writeLogToFile)
     self.contracts = {}
     for contractName in snapshot['contracts']:
         contract = snapshot['contracts'][contractName]
         self.contracts[contractName] = ABIContract(self.chain, contract['translator'], contract['address'])
예제 #15
0
 def __init__(self, root=b'', env=Env(), executing_on_head=False, **kwargs):
     self.env = env
     self.trie = SecureTrie(Trie(RefcountDB(self.db), root))
     for k, v in STATE_DEFAULTS.items():
         setattr(self, k, kwargs.get(k, copy.copy(v)))
     self.journal = []
     self.cache = {}
     self.log_listeners = []
     self.deletes = []
     self.changed = {}
     self.executing_on_head = executing_on_head
예제 #16
0
def check_snapshot_consistency(snapshot, env=None):
    if env:
        c = chain.Chain(env=env)
    else:
        c = chain.Chain(snapshot, Env())
    snapshot2 = c.state.to_snapshot()
    if snapshot != snapshot2:  # FIXME
        for i, ss in enumerate([snapshot, snapshot2]):
            fn = '/tmp/{}_{}'.format(STATE_STORE_FN, i)
            open(fn, 'w').write(json.dumps(snapshot))
        raise Exception("snapshot difference, see {}*".format(fn[:-1]))
    def __init__(self, app):
        self.config = app.config
        sce = self.config['eth']
        if int(sce['pruning']) >= 0:
            self.db = RefcountDB(app.services.db)
            if "I am not pruning" in self.db.db:
                raise Exception("This database was initialized as non-pruning."
                                " Kinda hard to start pruning now.")
            self.db.ttl = int(sce['pruning'])
            self.db.db.put("I am pruning", "1")
        else:
            self.db = app.services.db
            if "I am pruning" in self.db:
                raise Exception("This database was initialized as pruning."
                                " Kinda hard to stop pruning now.")
            self.db.put("I am not pruning", "1")

        if 'network_id' in self.db:
            db_network_id = self.db.get('network_id')
            if db_network_id != str(sce['network_id']):
                raise Exception(
                    "This database was initialized with network_id {} "
                    "and can not be used when connecting to network_id {}".
                    format(db_network_id, sce['network_id']))

        else:
            self.db.put('network_id', str(sce['network_id']))
            self.db.commit()

        assert self.db is not None

        super(ChainService, self).__init__(app)
        log.info('initializing chain')
        coinbase = app.services.accounts.coinbase
        env = Env(self.db, sce['block'])
        self.chain = Chain(env,
                           new_head_cb=self._on_new_head,
                           coinbase=coinbase)

        log.info('chain at', number=self.chain.head.number)
        if 'genesis_hash' in sce:
            assert sce['genesis_hash'] == self.chain.genesis.hex_hash()

        self.synchronizer = Synchronizer(self, force_sync=None)

        self.block_queue = Queue(maxsize=self.block_queue_size)
        self.transaction_queue = Queue(maxsize=self.transaction_queue_size)
        self.add_blocks_lock = False
        self.add_transaction_lock = gevent.lock.Semaphore()
        self.broadcast_filter = DuplicatesFilter()
        self.on_new_head_cbs = []
        self.on_new_head_candidate_cbs = []
        self.newblock_processing_times = deque(maxlen=1000)
예제 #18
0
 def ephemeral_clone(self):
     snapshot = self.to_snapshot(root_only=True, no_prevblocks=True)
     env2 = Env(OverlayDB(self.env.db), self.env.config)
     s = State.from_snapshot(snapshot, env2)
     for param in STATE_DEFAULTS:
         setattr(s, param, getattr(self, param))
     s.recent_uncles = self.recent_uncles
     s.prev_headers = self.prev_headers
     for acct in self.cache.values():
         assert not acct.touched or not acct.deleted
     s.journal = copy.copy(self.journal)
     s.cache = {}
     return s
예제 #19
0
def get_initial_stuff():
    config_metropolis['BLOCK_GAS_LIMIT'] = 2**60
    chain = tester.Chain(env=Env(config=config_metropolis))
    AdContract_code, ManualAdCampaign_code = rearrange_code('AdContract.sol')

    AdContract = chain.contract(AdContract_code,
                                language='solidity',
                                sender=tester.k0)

    ManualAdCampaign = chain.contract(ManualAdCampaign_code,
                                      language='solidity',
                                      sender=tester.k1)
    return chain, AdContract, ManualAdCampaign
예제 #20
0
    def __init__(self):
        tester.GASPRICE = 0
        config_metropolis['GASLIMIT_ADJMAX_FACTOR'] = .000000000001
        config_metropolis['GENESIS_GAS_LIMIT'] = 2**60
        config_metropolis['MIN_GAS_LIMIT'] = 2**60
        config_metropolis['BLOCK_GAS_LIMIT'] = 2**60

        for a in range(10):
            tester.base_alloc[getattr(tester, 'a%i' % a)] = {'balance': 10**24}

        self.chain = Chain(env=Env(config=config_metropolis))
        self.contracts = {}
        self.testerAddress = self.generateTesterMap('a')
        self.testerKey = self.generateTesterMap('k')
예제 #21
0
    def __init__(self, app):
        super(ChainService, self).__init__(app)
        sce = self.config['eth']
        env = Env(self.db, sce['block'])
        coinbase = app.services.accounts.coinbase
        self.chain = Chain(env, new_head_cb=self._on_new_head, coinbase=coinbase, process_block_cb=self.process_block, revert_block_cb=self.on_revert_blocks)
        self.progress_bar = True

        # sanitize the configured addrs
        for addr in self.start_blocks.keys():
            new_addr = addr
            if new_addr[0:2] == '0x':
                new_addr = new_addr[2:]

            if new_addr != addr:
                self.start_blocks[new_addr] = self.start_blocks[addr]
                del self.start_blocks[addr]
예제 #22
0
    def __init__(self, num_accounts=len(keys)):
        global serpent
        if not serpent:
            serpent = __import__('serpent')

        self.temp_data_dir = tempfile.mkdtemp()
        self.db = db.EphemDB()
        self.env = Env(self.db)

        o = {}
        for i in range(num_accounts):
            o[accounts[i]] = {"wei": 10**24}
        for i in range(1, 5):
            o[u.int_to_addr(i)] = {"wei": 1}
        self.block = b.genesis(self.env, start_alloc=o)
        self.blocks = [self.block]
        self.block.timestamp = 1410973349
        self.block.coinbase = a0
        self.block.gas_limit = 10**9
예제 #23
0
파일: evm.py 프로젝트: wub11/pyetherum
    def __init__(self, genesis):
        env = Env(EphemDB(), konfig)
        if not genesis:
            genesis = mk_genesis_data(env)

        if 'config' in genesis:
            if 'homesteadBlock' in genesis['config']:
                env.config['HOMESTEAD_FORK_BLKNUM'] = int(genesis['config']['homesteadBlock'])
                env.config['DAO_FORK_BLKNUM'] = int(genesis['config']['homesteadBlock'])
                env.config['ANTI_DOS_FORK_BLKNUM'] = int(genesis['config']['homesteadBlock'])
                env.config['SPURIOUS_DRAGON_FORK_BLKNUM'] = int(genesis['config']['homesteadBlock'])

        self.state = state_from_genesis_declaration(genesis, env)
        initialize_genesis_keys(self.state, Block(self.state.prev_headers[0], [], []))
def test_profile(profile):
    config = dict(eth=dict())

    konfig.update_config_with_defaults(
        config, {'eth': {
            'block': blocks.default_config
        }})

    # Set config values based on profile selection
    merge_dict(config, PROFILES[profile])

    # Load genesis config
    update_config_from_genesis_json(config, config['eth']['genesis'])

    bc = config['eth']['block']
    pprint(bc)
    env = Env(DB(), bc)

    genesis = blocks.genesis(env)
    assert genesis.hash.encode('hex') == config['eth']['genesis_hash']
예제 #25
0
def mk_basic_state(alloc, header=None, env=None, executing_on_head=False):
    env = env or Env()
    state = State(env=env, executing_on_head=executing_on_head)
    if not header:
        header = {
            "number": 0,
            "gas_limit": env.config['BLOCK_GAS_LIMIT'],
            "gas_used": 0,
            "timestamp": 1467446877,
            "difficulty": 1,
            "uncles_hash": '0x' + encode_hex(BLANK_UNCLES_HASH)
        }
    h = BlockHeader(number=parse_as_int(header['number']),
                    timestamp=parse_as_int(header['timestamp']),
                    difficulty=parse_as_int(header['difficulty']),
                    gas_limit=parse_as_int(header['gas_limit']),
                    uncles_hash=parse_as_bin(header['uncles_hash']))
    state.prev_headers = [h]

    for addr, data in alloc.items():
        addr = normalize_address(addr)
        assert len(addr) == 20
        if 'wei' in data:
            state.set_balance(addr, parse_as_int(data['wei']))
        if 'balance' in data:
            state.set_balance(addr, parse_as_int(data['balance']))
        if 'code' in data:
            state.set_code(addr, parse_as_bin(data['code']))
        if 'nonce' in data:
            state.set_nonce(addr, parse_as_int(data['nonce']))
        if 'storage' in data:
            for k, v in data['storage'].items():
                state.set_storage_data(addr, parse_as_bin(k), parse_as_bin(v))

    state.block_number = header["number"]
    state.gas_limit = header["gas_limit"]
    state.timestamp = header["timestamp"]
    state.block_difficulty = header["difficulty"]
    state.commit()
    return state
예제 #26
0
    def __init__(self, num_accounts=len(keys)):
        self.temp_data_dir = tempfile.mkdtemp()
        self.db = db.EphemDB()
        self.env = Env(self.db)
        self.last_tx = None

        initial_balances = {}

        for i in range(num_accounts):
            account = accounts[i]
            initial_balances[account] = {'wei': 10**24}

        for i in range(1, 5):
            address = int_to_addr(i)
            initial_balances[address] = {'wei': 1}

        self.block = blocks.genesis(
            self.env,
            start_alloc=initial_balances,
        )
        self.blocks = [self.block]
        self.block.timestamp = 1410973349
        self.block.coinbase = DEFAULT_ACCOUNT
        self.block.gas_limit = 10**9
예제 #27
0
    def __init__(self, app):
        self.config = app.config
        sce = self.config['eth']
        if int(sce['pruning']) >= 0:
            self.db = RefcountDB(app.services.db)
            if "I am not pruning" in self.db.db:
                raise Exception("This database was initialized as non-pruning."
                                " Kinda hard to start pruning now.")
            self.db.ttl = int(sce['pruning'])
            self.db.db.put("I am pruning", "1")
        else:
            self.db = app.services.db
            if "I am pruning" in self.db:
                raise Exception("This database was initialized as pruning."
                                " Kinda hard to stop pruning now.")
            self.db.put("I am not pruning", "1")

        if 'network_id' in self.db:
            db_network_id = self.db.get('network_id')
            if db_network_id != str(sce['network_id']):
                raise Exception(
                    "This database was initialized with network_id {} "
                    "and can not be used when connecting to network_id {}".
                    format(db_network_id, sce['network_id']))

        else:
            self.db.put('network_id', str(sce['network_id']))
            self.db.commit()

        assert self.db is not None

        WiredService.__init__(self, app)
        log.info('initializing chain')
        coinbase = app.services.accounts.coinbase
        env = Env(self.db, sce['block'])
        self.chain = Chain(env,
                           new_head_cb=self._on_new_head,
                           coinbase=coinbase)

        log.info('chain at', number=self.chain.head.number)
        if 'genesis_hash' in sce:
            assert sce['genesis_hash'] == self.chain.genesis.hex_hash()

        self.transaction_queue = Queue(maxsize=self.transaction_queue_size)
        self.add_blocks_lock = False
        self.add_transaction_lock = gevent.lock.BoundedSemaphore()
        self.broadcast_filter = DuplicatesFilter()
        self.on_new_head_cbs = []
        self.on_new_head_candidate_cbs = []
        self.newblock_processing_times = deque(maxlen=1000)

        # Consensus
        self.consensus_contract = ConsensusContract(
            validators=self.config['hdc']['validators'])
        self.consensus_manager = ConsensusManager(self,
                                                  self.consensus_contract,
                                                  self.consensus_privkey)

        # lock blocks that where proposed, so they don't get mutated
        self.proposal_lock = ProposalLock()
        assert not self.proposal_lock.is_locked()
예제 #28
0
    def __init__(self,
                 genesis=None,
                 env=None,
                 coinbase=b'\x00' * 20,
                 new_head_cb=None,
                 reset_genesis=False,
                 localtime=None,
                 **kwargs):
        self.env = env or Env()
        # Initialize the state
        if b'head_hash' in self.db:  # new head tag
            self.state = self.mk_poststate_of_blockhash(
                self.db.get(b'head_hash'))
            print('Initializing chain from saved head, #%d (%s)' %
                  (self.state.prev_headers[0].number,
                   encode_hex(self.state.prev_headers[0].hash)))
        elif genesis is None:
            raise Exception("Need genesis decl!")
        elif isinstance(genesis, State):
            assert env is None
            self.state = genesis
            self.env = self.state.env
            print('Initializing chain from provided state')
        elif "extraData" in genesis:
            self.state = state_from_genesis_declaration(genesis, self.env)
            reset_genesis = True
            print('Initializing chain from provided genesis declaration')
        elif "prev_headers" in genesis:
            self.state = State.from_snapshot(genesis, self.env)
            reset_genesis = True
            print('Initializing chain from provided state snapshot, %d (%s)' %
                  (self.state.block_number,
                   encode_hex(self.state.prev_headers[0].hash[:8])))
        else:
            print('Initializing chain from new state based on alloc')
            self.state = mk_basic_state(
                genesis, {
                    "number":
                    kwargs.get('number', 0),
                    "gas_limit":
                    kwargs.get('gas_limit', 4712388),
                    "gas_used":
                    kwargs.get('gas_used', 0),
                    "timestamp":
                    kwargs.get('timestamp', 1467446877),
                    "difficulty":
                    kwargs.get('difficulty', 2**25),
                    "hash":
                    kwargs.get('prevhash', '00' * 32),
                    "uncles_hash":
                    kwargs.get('uncles_hash',
                               '0x' + encode_hex(BLANK_UNCLES_HASH))
                }, self.env)
            reset_genesis = True

        assert self.env.db == self.state.db

        initialize(self.state)
        self.new_head_cb = new_head_cb

        self.head_hash = self.state.prev_headers[0].hash
        self.checkpoint_head_hash = b'\x00' * 32
        self.db.put(b'cp_subtree_score' + b'\x00' * 32, 2 / 3.)
        self.commit_logs = []
        self.casper_address = self.config['CASPER_ADDRESS']
        self.db.put(b'GENESIS_NUMBER', to_string(self.state.block_number))
        assert self.state.block_number == self.state.prev_headers[0].number
        if reset_genesis:
            self.genesis = Block(self.state.prev_headers[0], [], [])
            initialize_genesis_keys(self.state, self.genesis)
        else:
            self.genesis = self.get_block_by_number(0)
        self.db.put(b'cp_subtree_score' + self.genesis.hash, 2 / 3.)
        self.min_gasprice = kwargs.get('min_gasprice', 5 * 10**9)
        self.coinbase = coinbase
        self.extra_data = 'moo ha ha says the laughing cow.'
        self.time_queue = []
        self.parent_queue = {}
        self.localtime = time.time() if localtime is None else localtime
예제 #29
0
import rlp
from rlp.utils import decode_hex, encode_hex, ascii_chr, str_to_bytes
from ethereum import processblock as pb
import copy
from ethereum.db import EphemDB
from ethereum.utils import to_string, safe_ord, parse_int_or_hex
from ethereum.utils import remove_0x_head, int_to_hex
from ethereum.config import Env
import json
import os
import time
from ethereum import ethash
from ethereum import ethash_utils

db = EphemDB()
db_env = Env(db)

env = {
    "currentCoinbase":
    b"2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
    "currentDifficulty":
    "256",
    "currentGasLimit":
    "1000000000",
    "currentNumber":
    "257",
    "currentTimestamp":
    "1",
    "previousHash":
    b"5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
}
예제 #30
0
파일: test.py 프로젝트: yep/research
print 'Creating genesis state'
s = make_casper_genesis(
    validators=[(generate_validation_code(privtoaddr(k)), ds * 10**18,
                 r.get(9999))
                for k, ds, r in zip(keys, deposit_sizes, randaos)],
    alloc={privtoaddr(k): {
        'balance': 10**18
    }
           for k in keys},
    timestamp=2,
    epoch_length=50)
g = s.to_snapshot()
print 'Genesis state created'

validators = [
    Validator(g, k, n, Env(config=casper_config), time_offset=4) for k in keys
]
n.agents = validators
n.generate_peers()
lowest_shared_height = -1
made_101_check = 0

for i in range(100000):
    # print 'ticking'
    n.tick()
    if i % 100 == 0:
        print '%d ticks passed' % i
        print 'Validator heads:', [
            v.chain.head.header.number if v.chain.head else None
            for v in validators
        ]