コード例 #1
0
def casper_setup_block(chain,
                       state=None,
                       timestamp=None,
                       coinbase='\x35' * 20,
                       extra_data='moo ha ha says the laughing cow.'):
    state = state or chain.state
    blk = Block(BlockHeader())
    now = timestamp or chain.time()
    prev_blknumber = call_casper(state, 'getBlockNumber')
    blk.header.number = prev_blknumber + 1
    blk.header.difficulty = 1
    blk.header.gas_limit = call_casper(state, 'getGasLimit')
    blk.header.timestamp = max(now, state.prev_headers[0].timestamp + 1)
    blk.header.prevhash = apply_const_message(
        state,
        sender=casper_config['METROPOLIS_ENTRY_POINT'],
        to=casper_config['METROPOLIS_BLOCKHASH_STORE'],
        data=utils.encode_int32(prev_blknumber))
    blk.header.coinbase = coinbase
    blk.header.extra_data = extra_data
    blk.header.bloom = 0
    blk.uncles = []
    initialize(state, blk)
    for tx in get_dunkle_candidates(chain, state):
        assert apply_transaction(state, tx)
        blk.transactions.append(tx)
    log_bc.info('Block set up with number %d and prevhash %s, %d dunkles' %
                (blk.header.number, utils.encode_hex(
                    blk.header.prevhash), len(blk.transactions)))
    return blk
コード例 #2
0
 def add(self, item: Block) -> None:
     if item.get_marker() in self.buffer:
         self.buffer[item.get_marker()].hashes.update(item.hashes)
     else:
         self.buffer[item.get_marker()] = item
     if len(self.buffer) > self.size:
         self.buffer.popitem(False)
     self.metric.observe(len(self.buffer))
コード例 #3
0
 def get_latest_block(self, timeout=0) -> (Block, Block):
     r = requests.get(self.url.format(self.token), timeout=timeout)
     if r.status_code != 200:
         raise APIException(r.json())
     r_json = r.json()["result"]
     id = int(r_json["number"], 16)
     ancestor = Block(id-1, [uncle[2:] for uncle in r_json["uncles"]])
     ancestor.hashes.add(r_json["parentHash"][2:])
     return Block(id, [r_json["hash"][2:]]), ancestor
コード例 #4
0
 def get_latest_block(self, timeout=0) -> (Block, Block):
     r = requests.post(self.url.format(self.token), json={
         "jsonrpc": "2.0",
         "method": "eth_getBlockByNumber",
         "params": ["latest", False],
         "id": "1",
     }, timeout=timeout)
     if r.status_code != 200:
         raise APIException(r.json())
     r_json = r.json()["result"]
     id = int(r_json["number"], 16)
     ancestor = Block(id-1, [uncle[2:] for uncle in r_json["uncles"]])
     ancestor.hashes.add(r_json["parentHash"][2:])
     return Block(id, [r_json["hash"][2:]]), ancestor
コード例 #5
0
def mk_block_from_prevstate(chain, state=None, timestamp=None,
                            coinbase=b'\x35' * 20, extra_data='moo ha ha says the laughing cow.'):
    state = state or chain.state
    blk = Block(BlockHeader())
    now = timestamp or chain.time()
    blk.header.number = state.prev_headers[0].number + 1
    blk.header.difficulty = calc_difficulty(
        state.prev_headers[0], now, chain.config)
    blk.header.gas_limit = calc_gaslimit(state.prev_headers[0], chain.config)
    blk.header.timestamp = max(now, state.prev_headers[0].timestamp + 1)
    blk.header.prevhash = state.prev_headers[0].hash
    blk.header.coinbase = coinbase
    blk.header.extra_data = extra_data
    blk.header.bloom = 0
    blk.transactions = []
    return blk
コード例 #6
0
 def __init__(self, app):
     super(ChainServiceMock, self).__init__(app)
     self.on_new_head_cbs = []
     self.transaction_queue = TransactionQueue()
     self.is_syncing = False
     self.mined_block = None
     self.block_mined_event = Event()
     self.head_candidate = Block(BlockHeader(difficulty=DIFFICULTY),
                                 db=DB())
コード例 #7
0
def block_from_genesis_declaration(genesis_data, env):
    h = BlockHeader(nonce=parse_as_bin(genesis_data["nonce"]),
                    difficulty=parse_as_int(genesis_data["difficulty"]),
                    mixhash=parse_as_bin(genesis_data.get("mixhash", genesis_data.get("mixHash", "0"*64))),
                    coinbase=parse_as_bin(genesis_data["coinbase"]),
                    bloom=parse_as_int(genesis_data.get("bloom", "0")),
                    timestamp=parse_as_int(genesis_data["timestamp"]),
                    prevhash=parse_as_bin(genesis_data["parentHash"]),
                    extra_data=parse_as_bin(genesis_data["extraData"]),
                    gas_used=parse_as_int(genesis_data.get("gasUsed", "0")),
                    gas_limit=parse_as_int(genesis_data["gasLimit"]))
    return Block(h, [], [])
コード例 #8
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], [], []))
コード例 #9
0
ファイル: test_blocks.py プロジェクト: wub11/pyetherum
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
コード例 #10
0
def mk_block_from_prevstate(chain,
                            state=None,
                            timestamp=None,
                            coinbase=b'\x35' * 20,
                            extra_data=b'moo ha ha says the laughing cow.'):
    state = state or chain.state
    now = timestamp or chain.time()

    blk = Block(header=BlockHeader(
        number=state.prev_headers[0].number + 1,
        difficulty=calc_difficulty(state.prev_headers[0], now, chain.config),
        gas_limit=calc_gaslimit(state.prev_headers[0], chain.config),
        timestamp=max(now, state.prev_headers[0].timestamp + 1),
        prevhash=state.prev_headers[0].hash,
        coinbase=coinbase,
        extra_data=extra_data,
        bloom=0),
                transactions=[])
    return blk
コード例 #11
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
コード例 #12
0
    def __init__(self,
                 genesis=None,
                 env=None,
                 new_head_cb=None,
                 reset_genesis=False,
                 localtime=None,
                 max_history=1000,
                 **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('head_hash'))
            self.state.executing_on_head = True
            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')
            reset_genesis = True
        elif "extraData" in genesis:
            self.state = state_from_genesis_declaration(genesis,
                                                        self.env,
                                                        executing_on_head=True)
            reset_genesis = True
            print('Initializing chain from provided genesis declaration')
        elif "prev_headers" in genesis:
            self.state = State.from_snapshot(genesis,
                                             self.env,
                                             executing_on_head=True)
            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])))
        elif isinstance(genesis, dict):
            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',
                               self.env.config['BLOCK_GAS_LIMIT']),
                    "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

        if self.state.block_number == 0:
            assert self.state.block_number == self.state.prev_headers[0].number
        else:
            assert self.state.block_number - 1 == self.state.prev_headers[
                0].number

        if reset_genesis:
            if isinstance(self.state.prev_headers[0], FakeHeader):
                header = self.state.prev_headers[0].to_block_header()
            else:
                header = self.state.prev_headers[0]
            self.genesis = Block(header)
            self.state.prev_headers[0] = header
            initialize_genesis_keys(self.state, self.genesis)
        else:
            self.genesis = self.get_block_by_number(0)

        self.head_hash = self.state.prev_headers[0].hash
        self.time_queue = []
        self.parent_queue = {}
        self.localtime = time.time() if localtime is None else localtime
        self.max_history = max_history
コード例 #13
0
ファイル: eth_protocol.py プロジェクト: allinXallin/wccLab
 def to_block(self):
     """Convert the transient block to a :class:`ethereum.blocks.Block`"""
     return Block(self.header, transactions=self.transactions, uncles=self.uncles)