def state_from_genesis_declaration(genesis_data, env, block=None, allow_empties=False): if block: assert isinstance(block, Block) else: block = block_from_genesis_declaration(genesis_data, env) state = State(env=env) for addr, data in genesis_data["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, big_endian_to_int(parse_as_bin(k)), big_endian_to_int(parse_as_bin(v))) get_consensus_strategy(state.config).initialize(state, block) state.commit(allow_empties=allow_empties) print('deleting %d' % len(state.deletes)) rdb = RefcountDB(state.db) for delete in state.deletes: rdb.delete(delete) block.header.state_root = state.trie.root_hash state.prev_headers=[block.header] return state
def create_collation(chain, shard_id, parent_collation_hash, expected_period_number, coinbase, key, txqueue=None): """Create a collation chain: MainChain shard_id: id of ShardChain parent_collation_hash: the hash of the parent collation expected_period_number: the period number in which this collation expects to be included coinbase: coinbase key: key for sig txqueue: transaction queue """ log.info('Creating a collation') assert chain.has_shard(shard_id) temp_state = chain.shards[shard_id].mk_poststate_of_collation_hash( parent_collation_hash) cs = get_consensus_strategy(temp_state.config) # Set period_start_prevblock info period_start_prevhash = chain.get_period_start_prevhash( expected_period_number) assert period_start_prevhash is not None period_start_prevblock = chain.get_block(period_start_prevhash) # Call the initialize state transition function cs.initialize(temp_state, period_start_prevblock) # Initialize a collation with the given previous state and current coinbase collation = state_transition.mk_collation_from_prevstate( chain.shards[shard_id], temp_state, coinbase) # Add transactions state_transition.add_transactions(temp_state, collation, txqueue, shard_id, mainchain_state=chain.state) # Call the finalize state transition function state_transition.finalize(temp_state, collation.header.coinbase) # Set state root, receipt root, etc state_transition.set_execution_results(temp_state, collation) collation.header.shard_id = shard_id collation.header.parent_collation_hash = parent_collation_hash collation.header.expected_period_number = expected_period_number collation.header.period_start_prevhash = period_start_prevhash try: sig = sign(collation.signing_hash, key) collation.header.sig = sig except Exception as e: log.info('Failed to sign collation, exception: {}'.format(str(e))) raise e log.info('Created collation successfully') return collation
def apply_collation(state, collation, period_start_prevblock, mainchain_state=None, shard_id=None): """Apply collation """ snapshot = state.snapshot() cs = get_consensus_strategy(state.config) try: # Call the initialize state transition function cs.initialize(state, period_start_prevblock) # assert cs.check_seal(state, period_start_prevblock.header) # Validate tx_list_root in collation first assert state_transition.validate_transaction_tree(collation) for tx in collation.transactions: apply_shard_transaction(mainchain_state, state, shard_id, tx) # Set state root, receipt root, etc state_transition.finalize(state, collation.header.coinbase) assert state_transition.verify_execution_results(state, collation) except (ValueError, AssertionError) as e: state.revert(snapshot) raise e return state
def verify_collation_header(chain, header): """Verify the collation Validate the collation header before calling ShardChain.add_collation chain: MainChain header: the given collation header """ if header.shard_id < 0: raise ValueError('Invalid shard_id %d' % header.shard_id) # Call contract to verify header state = chain.state.ephemeral_clone() block = mk_block_from_prevstate(chain, timestamp=chain.state.timestamp + 14) cs = get_consensus_strategy(state.config) cs.initialize(state, block) try: result = call_valmgr(state, 'add_header', [rlp.encode(header)], sender_addr=header.coinbase) print('result:{}'.format(result)) if not result: raise ValueError('Calling add_header returns False') except: raise ValueError('Calling add_header failed') return True
def make_head_candidate(chain, txqueue=None, parent=None, timestamp=None, coinbase='\x35' * 20, extra_data='moo ha ha says the laughing cow.', min_gasprice=0): log.info('Creating head candidate') if parent is None: temp_state = State.from_snapshot( chain.state.to_snapshot(root_only=True), chain.env) else: temp_state = chain.mk_poststate_of_blockhash(parent.hash) cs = get_consensus_strategy(chain.env.config) # Initialize a block with the given parent and variables blk = mk_block_from_prevstate(chain, temp_state, timestamp, coinbase, extra_data) # Find and set the uncles blk.uncles = cs.get_uncles(chain, temp_state) blk.header.uncles_hash = sha3(rlp.encode(blk.uncles)) # Call the initialize state transition function cs.initialize(temp_state, blk) # Add transactions add_transactions(temp_state, blk, txqueue, min_gasprice) # Call the finalize state transition function cs.finalize(temp_state, blk) # Set state root, receipt root, etc set_execution_results(temp_state, blk) log.info('Created head candidate successfully') return blk, temp_state
def apply_block(state, block): # Pre-processing and verification snapshot = state.snapshot() cs = get_consensus_strategy(state.config) try: # Start a new block context cs.initialize(state, block) # Basic validation assert validate_header(state, block.header) assert cs.check_seal(state, block.header) assert cs.validate_uncles(state, block) assert validate_transaction_tree(state, block) # Process transactions for tx in block.transactions: apply_transaction(state, tx) # Finalize (incl paying block rewards) cs.finalize(state, block) # Verify state root, tx list root, receipt root assert verify_execution_results(state, block) # Post-finalize (ie. add the block header to the state for now) post_finalize(state, block) except (ValueError, AssertionError) as e: state.revert(snapshot) raise e return state
def __init__(self, alloc=None, env=None, deploy_sharding_contracts=False, genesis=None): # MainChain if genesis is None: genesis = mk_basic_state(base_alloc if alloc is None else alloc, None, get_env(env)) self.chain = MainChain(genesis=genesis, reset_genesis=True) self.cs = get_consensus_strategy(self.chain.env.config) self.block = mk_block_from_prevstate( self.chain, timestamp=self.chain.state.timestamp + 1) self.head_state = self.chain.state.ephemeral_clone() self.cs.initialize(self.head_state, self.block) self.last_sender = None self.last_tx = None # ShardChains self.collation = {} self.shard_head_state = {} self.shard_last_sender = {} self.shard_last_tx = {} self.add_header_logs = [] # validator manager contract and other pre-compiled contracts self.is_sharding_contracts_deployed = False if deploy_sharding_contracts: self.is_sharding_contracts_deployed = True self.deploy_initializing_contracts(k0) self.last_sender = k0 self.mine(1)
def __init__(self, alloc=None, env=None): self.chain = chain.Chain(genesis=mk_basic_state( base_alloc if alloc is None else alloc, None, get_env(env)), reset_genesis=True) self.cs = get_consensus_strategy(self.chain.env.config) self.block = mk_block_from_prevstate( self.chain, timestamp=self.chain.state.timestamp + 1) self.head_state = self.chain.state.ephemeral_clone() self.cs.initialize(self.head_state, self.block) self.last_sender = None self.last_tx = None
def __init__(self, alloc=base_alloc, env=None, genesis=None): from ethereum.pow import chain as pow_chain if genesis: if type(genesis)!=dict and genesis.env.config['CONSENSUS_STRATEGY'] == 'hybrid_casper': from ethereum.hybrid_casper import chain as hybrid_casper_chain self.chain = hybrid_casper_chain.Chain(genesis, reset_genesis=True) else: self.chain = pow_chain.Chain(genesis, env=env, reset_genesis=True) else: self.chain = pow_chain.Chain(mk_basic_state(alloc, None, get_env(env)), reset_genesis=True) self.cs = get_consensus_strategy(self.chain.env.config) self.block = mk_block_from_prevstate( self.chain, timestamp=self.chain.state.timestamp + 1) self.head_state = self.chain.state.ephemeral_clone() self.cs.initialize(self.head_state, self.block) self.last_sender = None self.last_tx = None