idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
36,100 | def record_changeset ( self , custom_changeset_id : uuid . UUID = None ) -> uuid . UUID : if custom_changeset_id is not None : if custom_changeset_id in self . journal_data : raise ValidationError ( "Tried to record with an existing changeset id: %r" % custom_changeset_id ) else : changeset_id = custom_changeset_id els... | Creates a new changeset . Changesets are referenced by a random uuid4 to prevent collisions between multiple changesets . |
36,101 | def pop_changeset ( self , changeset_id : uuid . UUID ) -> Dict [ bytes , Union [ bytes , DeletedEntry ] ] : if changeset_id not in self . journal_data : raise KeyError ( changeset_id , "Unknown changeset in JournalDB" ) all_ids = tuple ( self . journal_data . keys ( ) ) changeset_idx = all_ids . index ( changeset_id )... | Returns all changes from the given changeset . This includes all of the changes from any subsequent changeset giving precidence to later changesets . |
36,102 | def commit_changeset ( self , changeset_id : uuid . UUID ) -> Dict [ bytes , Union [ bytes , DeletedEntry ] ] : does_clear = self . has_clear ( changeset_id ) changeset_data = self . pop_changeset ( changeset_id ) if not self . is_empty ( ) : if does_clear : self . latest = { } self . _clears_at . add ( self . latest_i... | Collapses all changes for the given changeset into the previous changesets if it exists . |
36,103 | def _validate_changeset ( self , changeset_id : uuid . UUID ) -> None : if not self . journal . has_changeset ( changeset_id ) : raise ValidationError ( "Changeset not found in journal: {0}" . format ( str ( changeset_id ) ) ) | Checks to be sure the changeset is known by the journal |
36,104 | def record ( self , custom_changeset_id : uuid . UUID = None ) -> uuid . UUID : return self . journal . record_changeset ( custom_changeset_id ) | Starts a new recording and returns an id for the associated changeset |
36,105 | def discard ( self , changeset_id : uuid . UUID ) -> None : self . _validate_changeset ( changeset_id ) self . journal . pop_changeset ( changeset_id ) | Throws away all journaled data starting at the given changeset |
36,106 | def commit ( self , changeset_id : uuid . UUID ) -> None : self . _validate_changeset ( changeset_id ) journal_data = self . journal . commit_changeset ( changeset_id ) if self . journal . is_empty ( ) : self . reset ( ) for key , value in journal_data . items ( ) : try : if value is DELETED_ENTRY : del self . wrapped_... | Commits a given changeset . This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys . |
36,107 | def FQP_point_to_FQ2_point ( pt : Tuple [ FQP , FQP , FQP ] ) -> Tuple [ FQ2 , FQ2 , FQ2 ] : return ( FQ2 ( pt [ 0 ] . coeffs ) , FQ2 ( pt [ 1 ] . coeffs ) , FQ2 ( pt [ 2 ] . coeffs ) , ) | Transform FQP to FQ2 for type hinting . |
36,108 | def as_opcode ( cls : Type [ T ] , logic_fn : Callable [ ... , Any ] , mnemonic : str , gas_cost : int ) -> Type [ T ] : if gas_cost : @ functools . wraps ( logic_fn ) def wrapped_logic_fn ( computation : 'BaseComputation' ) -> Any : computation . consume_gas ( gas_cost , mnemonic , ) return logic_fn ( computation ) el... | Class factory method for turning vanilla functions into Opcode classes . |
36,109 | def _wipe_storage ( self , address : Address ) -> None : account_store = self . _get_address_store ( address ) self . _dirty_accounts . add ( address ) account_store . delete ( ) | Wipe out the storage without explicitly handling the storage root update |
36,110 | def setup_main_filler ( name : str , environment : Dict [ Any , Any ] = None ) -> Dict [ str , Dict [ str , Any ] ] : return setup_filler ( name , merge ( DEFAULT_MAIN_ENVIRONMENT , environment or { } ) ) | Kick off the filler generation process by creating the general filler scaffold with a test name and general information about the testing environment . |
36,111 | def pre_state ( * raw_state : GeneralState , filler : Dict [ str , Any ] ) -> None : @ wraps ( pre_state ) def _pre_state ( filler : Dict [ str , Any ] ) -> Dict [ str , Any ] : test_name = get_test_name ( filler ) old_pre_state = filler [ test_name ] . get ( "pre_state" , { } ) pre_state = normalize_state ( raw_state ... | Specify the state prior to the test execution . Multiple invocations don t override the state but extend it instead . |
36,112 | def expect ( post_state : Dict [ str , Any ] = None , networks : Any = None , transaction : TransactionDict = None ) -> Callable [ ... , Dict [ str , Any ] ] : return partial ( _expect , post_state , networks , transaction ) | Specify the expected result for the test . |
36,113 | def calldataload ( computation : BaseComputation ) -> None : start_position = computation . stack_pop ( type_hint = constants . UINT256 ) value = computation . msg . data_as_bytes [ start_position : start_position + 32 ] padded_value = value . ljust ( 32 , b'\x00' ) normalized_value = padded_value . lstrip ( b'\x00' ) ... | Load call data into memory . |
36,114 | def clamp ( inclusive_lower_bound : int , inclusive_upper_bound : int , value : int ) -> int : if value <= inclusive_lower_bound : return inclusive_lower_bound elif value >= inclusive_upper_bound : return inclusive_upper_bound else : return value | Bound the given value between inclusive_lower_bound and inclusive_upper_bound . |
36,115 | def integer_squareroot ( value : int ) -> int : if not isinstance ( value , int ) or isinstance ( value , bool ) : raise ValueError ( "Value must be an integer: Got: {0}" . format ( type ( value ) , ) ) if value < 0 : raise ValueError ( "Value cannot be negative: Got: {0}" . format ( value , ) ) with decimal . localcon... | Return the integer square root of value . |
36,116 | def _commit_unless_raises ( cls , write_target_db : BaseDB ) -> Iterator [ 'AtomicDBWriteBatch' ] : readable_write_batch = cls ( write_target_db ) try : yield readable_write_batch except Exception : cls . logger . exception ( "Unexpected error in atomic db write, dropped partial writes: %r" , readable_write_batch . _di... | Commit all writes inside the context unless an exception was raised . |
36,117 | def slt ( computation : BaseComputation ) -> None : left , right = map ( unsigned_to_signed , computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) , ) if left < right : result = 1 else : result = 0 computation . stack_push ( signed_to_unsigned ( result ) ) | Signed Lesser Comparison |
36,118 | def build ( obj : Any , * applicators : Callable [ ... , Any ] ) -> Any : if isinstance ( obj , BaseChain ) : return pipe ( obj , copy ( ) , * applicators ) else : return pipe ( obj , * applicators ) | Run the provided object through the series of applicator functions . |
36,119 | def name ( class_name : str , chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : return chain_class . configure ( __name__ = class_name ) | Assign the given name to the chain class . |
36,120 | def chain_id ( chain_id : int , chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : return chain_class . configure ( chain_id = chain_id ) | Set the chain_id for the chain class . |
36,121 | def fork_at ( vm_class : Type [ BaseVM ] , at_block : int , chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : if chain_class . vm_configuration is not None : base_configuration = chain_class . vm_configuration else : base_configuration = tuple ( ) vm_configuration = base_configuration + ( ( at_block , vm_class... | Adds the vm_class to the chain s vm_configuration . |
36,122 | def enable_pow_mining ( chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : if not chain_class . vm_configuration : raise ValidationError ( "Chain class has no vm_configuration" ) vm_configuration = _mix_in_pow_mining ( chain_class . vm_configuration ) return chain_class . configure ( vm_configuration = vm_confi... | Inject on demand generation of the proof of work mining seal on newly mined blocks into each of the chain s vms . |
36,123 | def disable_pow_check ( chain_class : Type [ BaseChain ] ) -> Type [ BaseChain ] : if not chain_class . vm_configuration : raise ValidationError ( "Chain class has no vm_configuration" ) if issubclass ( chain_class , NoChainSealValidationMixin ) : chain_class_without_seal_validation = chain_class else : chain_class_wit... | Disable the proof of work validation check for each of the chain s vms . This allows for block mining without generation of the proof of work seal . |
36,124 | def genesis ( chain_class : BaseChain , db : BaseAtomicDB = None , params : Dict [ str , HeaderParams ] = None , state : GeneralState = None ) -> BaseChain : if state is None : genesis_state = { } else : genesis_state = _fill_and_normalize_state ( state ) genesis_params_defaults = _get_default_genesis_params ( genesis_... | Initialize the given chain class with the given genesis header parameters and chain state . |
36,125 | def mine_block ( chain : MiningChain , ** kwargs : Any ) -> MiningChain : if not isinstance ( chain , MiningChain ) : raise ValidationError ( '`mine_block` may only be used on MiningChain instances' ) chain . mine_block ( ** kwargs ) return chain | Mine a new block on the chain . Header parameters for the new block can be overridden using keyword arguments . |
36,126 | def import_block ( block : BaseBlock , chain : BaseChain ) -> BaseChain : chain . import_block ( block ) return chain | Import the provided block into the chain . |
36,127 | def copy ( chain : MiningChain ) -> MiningChain : if not isinstance ( chain , MiningChain ) : raise ValidationError ( "`at_block_number` may only be used with 'MiningChain" ) base_db = chain . chaindb . db if not isinstance ( base_db , AtomicDB ) : raise ValidationError ( "Unsupported database type: {0}" . format ( typ... | Make a copy of the chain at the given state . Actions performed on the resulting chain will not affect the original chain . |
36,128 | def chain_split ( * splits : Iterable [ Callable [ ... , Any ] ] ) -> Callable [ [ BaseChain ] , Iterable [ BaseChain ] ] : if not splits : raise ValidationError ( "Cannot use `chain_split` without providing at least one split" ) @ functools . wraps ( chain_split ) @ to_tuple def _chain_split ( chain : BaseChain ) -> I... | Construct and execute multiple concurrent forks of the chain . |
36,129 | def at_block_number ( block_number : BlockNumber , chain : MiningChain ) -> MiningChain : if not isinstance ( chain , MiningChain ) : raise ValidationError ( "`at_block_number` may only be used with 'MiningChain" ) at_block = chain . get_canonical_block_by_number ( block_number ) db = chain . chaindb . db chain_at_bloc... | Rewind the chain back to the given block number . Calls to things like get_canonical_head will still return the canonical head of the chain however you can use mine_block to mine fork chains . |
36,130 | def load_json_fixture ( fixture_path : str ) -> Dict [ str , Any ] : with open ( fixture_path ) as fixture_file : file_fixtures = json . load ( fixture_file ) return file_fixtures | Loads a fixture file caching the most recent files it loaded . |
36,131 | def load_fixture ( fixture_path : str , fixture_key : str , normalize_fn : Callable [ ... , Any ] = identity ) -> Dict [ str , Any ] : file_fixtures = load_json_fixture ( fixture_path ) fixture = normalize_fn ( file_fixtures [ fixture_key ] ) return fixture | Loads a specific fixture from a fixture file optionally passing it through a normalization function . |
36,132 | def construct_evm_runtime_identifier ( ) -> str : return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}" . format ( __version__ , platform = sys . platform , v = sys . version_info , imp = sys . implementation , ) | Constructs the EVM runtime identifier string |
36,133 | def binary_gas_search ( state : BaseState , transaction : BaseTransaction , tolerance : int = 1 ) -> int : if not hasattr ( transaction , 'sender' ) : raise TypeError ( "Transaction is missing attribute sender." , "If sending an unsigned transaction, use SpoofTransaction and provide the" , "sender using the 'from' para... | Run the transaction with various gas limits progressively approaching the minimum needed to succeed without an OutOfGas exception . |
36,134 | def commit_to ( self , db : BaseDB ) -> None : self . logger . debug2 ( 'persist storage root to data store' ) if self . _trie_nodes_batch is None : raise ValidationError ( "It is invalid to commit an account's storage if it has no pending changes. " "Always check storage_lookup.has_changed_root before attempting to co... | Trying to commit changes when nothing has been written will raise a ValidationError |
36,135 | def _validate_flushed ( self ) -> None : journal_diff = self . _journal_storage . diff ( ) if len ( journal_diff ) > 0 : raise ValidationError ( "StorageDB had a dirty journal when it needed to be clean: %r" % journal_diff ) | Will raise an exception if there are some changes made since the last persist . |
36,136 | def write ( self , start_position : int , size : int , value : bytes ) -> None : if size : validate_uint256 ( start_position ) validate_uint256 ( size ) validate_is_bytes ( value ) validate_length ( value , length = size ) validate_lte ( start_position + size , maximum = len ( self ) ) for idx , v in enumerate ( value ... | Write value into memory . |
36,137 | def read ( self , start_position : int , size : int ) -> memoryview : return memoryview ( self . _bytes ) [ start_position : start_position + size ] | Return a view into the memory |
36,138 | def read_bytes ( self , start_position : int , size : int ) -> bytes : return bytes ( self . _bytes [ start_position : start_position + size ] ) | Read a value from memory and return a fresh bytes instance |
36,139 | def extend_memory ( self , start_position : int , size : int ) -> None : validate_uint256 ( start_position , title = "Memory start position" ) validate_uint256 ( size , title = "Memory size" ) before_size = ceil32 ( len ( self . _memory ) ) after_size = ceil32 ( start_position + size ) before_cost = memory_gas_cost ( b... | Extend the size of the memory to be at minimum start_position + size bytes in length . Raise eth . exceptions . OutOfGas if there is not enough gas to pay for extending the memory . |
36,140 | def memory_read ( self , start_position : int , size : int ) -> memoryview : return self . _memory . read ( start_position , size ) | Read and return a view of size bytes from memory starting at start_position . |
36,141 | def memory_read_bytes ( self , start_position : int , size : int ) -> bytes : return self . _memory . read_bytes ( start_position , size ) | Read and return size bytes from memory starting at start_position . |
36,142 | def consume_gas ( self , amount : int , reason : str ) -> None : return self . _gas_meter . consume_gas ( amount , reason ) | Consume amount of gas from the remaining gas . Raise eth . exceptions . OutOfGas if there is not enough gas remaining . |
36,143 | def stack_pop ( self , num_items : int = 1 , type_hint : str = None ) -> Any : return self . _stack . pop ( num_items , type_hint ) | Pop and return a number of items equal to num_items from the stack . type_hint can be either uint256 or bytes . The return value will be an int or bytes type depending on the value provided for the type_hint . |
36,144 | def stack_push ( self , value : Union [ int , bytes ] ) -> None : return self . _stack . push ( value ) | Push value onto the stack . |
36,145 | def prepare_child_message ( self , gas : int , to : Address , value : int , data : BytesOrView , code : bytes , ** kwargs : Any ) -> Message : kwargs . setdefault ( 'sender' , self . msg . storage_address ) child_message = Message ( gas = gas , to = to , value = value , data = data , code = code , depth = self . msg . ... | Helper method for creating a child computation . |
36,146 | def apply_child_computation ( self , child_msg : Message ) -> 'BaseComputation' : child_computation = self . generate_child_computation ( child_msg ) self . add_child_computation ( child_computation ) return child_computation | Apply the vm message child_msg as a child computation . |
36,147 | def _get_log_entries ( self ) -> List [ Tuple [ int , bytes , List [ int ] , bytes ] ] : if self . is_error : return [ ] else : return sorted ( itertools . chain ( self . _log_entries , * ( child . _get_log_entries ( ) for child in self . children ) ) ) | Return the log entries for this computation and its children . |
36,148 | def apply_computation ( cls , state : BaseState , message : Message , transaction_context : BaseTransactionContext ) -> 'BaseComputation' : with cls ( state , message , transaction_context ) as computation : if message . code_address in computation . precompiles : computation . precompiles [ message . code_address ] ( ... | Perform the computation that would be triggered by the VM message . |
36,149 | def compute_homestead_difficulty ( parent_header : BlockHeader , timestamp : int ) -> int : parent_tstamp = parent_header . timestamp validate_gt ( timestamp , parent_tstamp , title = "Header.timestamp" ) offset = parent_header . difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR sign = max ( 1 - ( timestamp - parent_tsta... | Computes the difficulty for a homestead block based on the parent block . |
36,150 | def snapshot ( self ) -> Tuple [ Hash32 , UUID ] : return self . state_root , self . _account_db . record ( ) | Perform a full snapshot of the current state . |
36,151 | def revert ( self , snapshot : Tuple [ Hash32 , UUID ] ) -> None : state_root , account_snapshot = snapshot self . _account_db . state_root = state_root self . _account_db . discard ( account_snapshot ) | Revert the VM to the state at the snapshot |
36,152 | def get_computation ( self , message : Message , transaction_context : 'BaseTransactionContext' ) -> 'BaseComputation' : if self . computation_class is None : raise AttributeError ( "No `computation_class` has been set for this State" ) else : computation = self . computation_class ( self , message , transaction_contex... | Return a computation instance for the given message and transaction_context |
36,153 | def apply_transaction ( self , transaction : BaseOrSpoofTransaction ) -> 'BaseComputation' : if self . state_root != BLANK_ROOT_HASH and not self . _account_db . has_root ( self . state_root ) : raise StateRootNotFound ( self . state_root ) else : return self . execute_transaction ( transaction ) | Apply transaction to the vm state |
36,154 | def get_env_value ( name : str , required : bool = False , default : Any = empty ) -> str : if required and default is not empty : raise ValueError ( "Using `default` with `required=True` is invalid" ) elif required : try : value = os . environ [ name ] except KeyError : raise KeyError ( "Must set environment variable ... | Core function for extracting the environment variable . |
36,155 | def make_receipt ( self , base_header : BlockHeader , transaction : BaseTransaction , computation : BaseComputation , state : BaseState ) -> Receipt : raise NotImplementedError ( "VM classes must implement this method" ) | Generate the receipt resulting from applying the transaction . |
36,156 | def execute_bytecode ( self , origin : Address , gas_price : int , gas : int , to : Address , sender : Address , value : int , data : bytes , code : bytes , code_address : Address = None , ) -> BaseComputation : if origin is None : origin = sender message = Message ( gas = gas , to = to , sender = sender , value = valu... | Execute raw bytecode in the context of the current state of the virtual machine . |
36,157 | def import_block ( self , block : BaseBlock ) -> BaseBlock : if self . block . number != block . number : raise ValidationError ( "This VM can only import blocks at number #{}, the attempted block was #{}" . format ( self . block . number , block . number , ) ) self . block = self . block . copy ( header = self . confi... | Import the given block to the chain . |
36,158 | def mine_block ( self , * args : Any , ** kwargs : Any ) -> BaseBlock : packed_block = self . pack_block ( self . block , * args , ** kwargs ) final_block = self . finalize_block ( packed_block ) self . validate_block ( final_block ) return final_block | Mine the current block . Proxies to self . pack_block method . |
36,159 | def finalize_block ( self , block : BaseBlock ) -> BaseBlock : if block . number > 0 : self . _assign_block_rewards ( block ) self . state . persist ( ) return block . copy ( header = block . header . copy ( state_root = self . state . state_root ) ) | Perform any finalization steps like awarding the block mining reward and persisting the final state root . |
36,160 | def pack_block ( self , block : BaseBlock , * args : Any , ** kwargs : Any ) -> BaseBlock : if 'uncles' in kwargs : uncles = kwargs . pop ( 'uncles' ) kwargs . setdefault ( 'uncles_hash' , keccak ( rlp . encode ( uncles ) ) ) else : uncles = block . uncles provided_fields = set ( kwargs . keys ( ) ) known_fields = set ... | Pack block for mining . |
36,161 | def generate_block_from_parent_header_and_coinbase ( cls , parent_header : BlockHeader , coinbase : Address ) -> BaseBlock : block_header = generate_header_from_parent_header ( cls . compute_difficulty , parent_header , coinbase , timestamp = parent_header . timestamp + 1 , ) block = cls . get_block_class ( ) ( block_h... | Generate block from parent header and coinbase . |
36,162 | def previous_hashes ( self ) -> Optional [ Iterable [ Hash32 ] ] : return self . get_prev_hashes ( self . header . parent_hash , self . chaindb ) | Convenience API for accessing the previous 255 block hashes . |
36,163 | def create_transaction ( self , * args : Any , ** kwargs : Any ) -> BaseTransaction : return self . get_transaction_class ( ) ( * args , ** kwargs ) | Proxy for instantiating a signed transaction for this VM . |
36,164 | def create_unsigned_transaction ( cls , * , nonce : int , gas_price : int , gas : int , to : Address , value : int , data : bytes ) -> 'BaseUnsignedTransaction' : return cls . get_transaction_class ( ) . create_unsigned_transaction ( nonce = nonce , gas_price = gas_price , gas = gas , to = to , value = value , data = d... | Proxy for instantiating an unsigned transaction for this VM . |
36,165 | def validate_block ( self , block : BaseBlock ) -> None : if not isinstance ( block , self . get_block_class ( ) ) : raise ValidationError ( "This vm ({0!r}) is not equipped to validate a block of type {1!r}" . format ( self , block , ) ) if block . is_genesis : validate_length_lte ( block . header . extra_data , 32 , ... | Validate the the given block . |
36,166 | def validate_uncle ( cls , block : BaseBlock , uncle : BaseBlock , uncle_parent : BaseBlock ) -> None : if uncle . block_number >= block . number : raise ValidationError ( "Uncle number ({0}) is higher than block number ({1})" . format ( uncle . block_number , block . number ) ) if uncle . block_number != uncle_parent ... | Validate the given uncle in the context of the given block . |
36,167 | def is_cleanly_mergable ( * dicts : Dict [ Any , Any ] ) -> bool : if len ( dicts ) <= 1 : return True elif len ( dicts ) == 2 : if not all ( isinstance ( d , Mapping ) for d in dicts ) : return False else : shared_keys = set ( dicts [ 0 ] . keys ( ) ) & set ( dicts [ 1 ] . keys ( ) ) return all ( is_cleanly_mergable (... | Check that nothing will be overwritten when dictionaries are merged using deep_merge . |
36,168 | def deleted_keys ( self ) -> Iterable [ bytes ] : for key , value in self . _changes . items ( ) : if value is DELETED : yield key | List all the keys that have been deleted . |
36,169 | def apply_to ( self , db : Union [ BaseDB , ABC_Mutable_Mapping ] , apply_deletes : bool = True ) -> None : for key , value in self . _changes . items ( ) : if value is DELETED : if apply_deletes : try : del db [ key ] except KeyError : pass else : pass else : db [ key ] = value | Apply the changes in this diff to the given database . You may choose to opt out of deleting any underlying keys . |
36,170 | def join ( cls , diffs : Iterable [ 'DBDiff' ] ) -> 'DBDiff' : tracker = DBDiffTracker ( ) for diff in diffs : diff . apply_to ( tracker ) return tracker . diff ( ) | Join several DBDiff objects into a single DBDiff object . |
36,171 | def hash_log_entries ( log_entries : Iterable [ Tuple [ bytes , List [ int ] , bytes ] ] ) -> Hash32 : logs = [ Log ( * entry ) for entry in log_entries ] encoded_logs = rlp . encode ( logs ) logs_hash = keccak ( encoded_logs ) return logs_hash | Helper function for computing the RLP hash of the logs from transaction execution . |
36,172 | def get_vm_class_for_block_number ( cls , block_number : BlockNumber ) -> Type [ 'BaseVM' ] : if cls . vm_configuration is None : raise AttributeError ( "Chain classes must define the VMs in vm_configuration" ) validate_block_number ( block_number ) for start_block , vm_class in reversed ( cls . vm_configuration ) : if... | Returns the VM class for the given block number . |
36,173 | def validate_chain ( cls , root : BlockHeader , descendants : Tuple [ BlockHeader , ... ] , seal_check_random_sample_rate : int = 1 ) -> None : all_indices = range ( len ( descendants ) ) if seal_check_random_sample_rate == 1 : indices_to_check_seal = set ( all_indices ) else : sample_size = len ( all_indices ) // seal... | Validate that all of the descendents are valid given that the root header is valid . |
36,174 | def from_genesis ( cls , base_db : BaseAtomicDB , genesis_params : Dict [ str , HeaderParams ] , genesis_state : AccountState = None ) -> 'BaseChain' : genesis_vm_class = cls . get_vm_class_for_block_number ( BlockNumber ( 0 ) ) pre_genesis_header = BlockHeader ( difficulty = 0 , block_number = - 1 , gas_limit = 0 ) st... | Initializes the Chain from a genesis state . |
36,175 | def get_vm ( self , at_header : BlockHeader = None ) -> 'BaseVM' : header = self . ensure_header ( at_header ) vm_class = self . get_vm_class_for_block_number ( header . block_number ) return vm_class ( header = header , chaindb = self . chaindb ) | Returns the VM instance for the given block number . |
36,176 | def create_header_from_parent ( self , parent_header : BlockHeader , ** header_params : HeaderParams ) -> BlockHeader : return self . get_vm_class_for_block_number ( block_number = parent_header . block_number + 1 , ) . create_header_from_parent ( parent_header , ** header_params ) | Passthrough helper to the VM class of the block descending from the given header . |
36,177 | def ensure_header ( self , header : BlockHeader = None ) -> BlockHeader : if header is None : head = self . get_canonical_head ( ) return self . create_header_from_parent ( head ) else : return header | Return header if it is not None otherwise return the header of the canonical head . |
36,178 | def get_ancestors ( self , limit : int , header : BlockHeader ) -> Tuple [ BaseBlock , ... ] : ancestor_count = min ( header . block_number , limit ) vm_class = self . get_vm_class_for_block_number ( header . block_number ) block_class = vm_class . get_block_class ( ) block = block_class ( header = header , uncles = [ ... | Return limit number of ancestor blocks from the current canonical head . |
36,179 | def get_block_by_hash ( self , block_hash : Hash32 ) -> BaseBlock : validate_word ( block_hash , title = "Block Hash" ) block_header = self . get_block_header_by_hash ( block_hash ) return self . get_block_by_header ( block_header ) | Returns the requested block as specified by block hash . |
36,180 | def get_block_by_header ( self , block_header : BlockHeader ) -> BaseBlock : vm = self . get_vm ( block_header ) return vm . block | Returns the requested block as specified by the block header . |
36,181 | def get_canonical_block_by_number ( self , block_number : BlockNumber ) -> BaseBlock : validate_uint256 ( block_number , title = "Block Number" ) return self . get_block_by_hash ( self . chaindb . get_canonical_block_hash ( block_number ) ) | Returns the block with the given number in the canonical chain . |
36,182 | def get_canonical_transaction ( self , transaction_hash : Hash32 ) -> BaseTransaction : ( block_num , index ) = self . chaindb . get_transaction_index ( transaction_hash ) VM_class = self . get_vm_class_for_block_number ( block_num ) transaction = self . chaindb . get_transaction_by_index ( block_num , index , VM_class... | Returns the requested transaction as specified by the transaction hash from the canonical chain . |
36,183 | def estimate_gas ( self , transaction : BaseOrSpoofTransaction , at_header : BlockHeader = None ) -> int : if at_header is None : at_header = self . get_canonical_head ( ) with self . get_vm ( at_header ) . state_in_temp_block ( ) as state : return self . gas_estimator ( state , transaction ) | Returns an estimation of the amount of gas the given transaction will use if executed on top of the block specified by the given header . |
36,184 | def import_block ( self , block : BaseBlock , perform_validation : bool = True ) -> Tuple [ BaseBlock , Tuple [ BaseBlock , ... ] , Tuple [ BaseBlock , ... ] ] : try : parent_header = self . get_block_header_by_hash ( block . header . parent_hash ) except HeaderNotFound : raise ValidationError ( "Attempt to import bloc... | Imports a complete block and returns a 3 - tuple |
36,185 | def validate_block ( self , block : BaseBlock ) -> None : if block . is_genesis : raise ValidationError ( "Cannot validate genesis block this way" ) VM_class = self . get_vm_class_for_block_number ( BlockNumber ( block . number ) ) parent_block = self . get_block_by_hash ( block . header . parent_hash ) VM_class . vali... | Performs validation on a block that is either being mined or imported . |
36,186 | def validate_gaslimit ( self , header : BlockHeader ) -> None : parent_header = self . get_block_header_by_hash ( header . parent_hash ) low_bound , high_bound = compute_gas_limit_bounds ( parent_header ) if header . gas_limit < low_bound : raise ValidationError ( "The gas limit on block {0} is too low: {1}. It must be... | Validate the gas limit on the given header . |
36,187 | def validate_uncles ( self , block : BaseBlock ) -> None : has_uncles = len ( block . uncles ) > 0 should_have_uncles = block . header . uncles_hash != EMPTY_UNCLE_HASH if not has_uncles and not should_have_uncles : return elif has_uncles and not should_have_uncles : raise ValidationError ( "Block has uncles but header... | Validate the uncles for the given block . |
36,188 | def apply_transaction ( self , transaction : BaseTransaction ) -> Tuple [ BaseBlock , Receipt , BaseComputation ] : vm = self . get_vm ( self . header ) base_block = vm . block receipt , computation = vm . apply_transaction ( base_block . header , transaction ) header_with_receipt = vm . add_receipt_to_header ( base_bl... | Applies the transaction to the current tip block . |
36,189 | def wait_for_host ( port , interval = 1 , timeout = 30 , to_start = True , queue = None , ssl_pymongo_options = None ) : host = 'localhost:%i' % port start_time = time . time ( ) while True : if ( time . time ( ) - start_time ) > timeout : if queue : queue . put_nowait ( ( port , False ) ) return False try : con = Mong... | Ping server and wait for response . |
36,190 | def shutdown_host ( port , username = None , password = None , authdb = None ) : host = 'localhost:%i' % port try : mc = MongoConnection ( host ) try : if username and password and authdb : if authdb != "admin" : raise RuntimeError ( "given username/password is not for " "admin database" ) else : try : mc . admin . aut... | Send the shutdown command to a mongod or mongos on given port . |
36,191 | def start ( self ) : self . discover ( ) if not self . startup_info : if len ( self . get_tagged ( [ 'down' ] ) ) == len ( self . get_tagged ( [ 'all' ] ) ) : self . args = self . loaded_args print ( "upgrading mlaunch environment meta-data." ) return self . init ( ) else : raise SystemExit ( "These nodes were created ... | Sub - command start . |
36,192 | def is_running ( self , port ) : try : con = self . client ( 'localhost:%s' % port ) con . admin . command ( 'ping' ) return True except ( AutoReconnect , ConnectionFailure , OperationFailure ) : return False | Return True if a host on a specific port is running . |
36,193 | def get_tagged ( self , tags ) : if not hasattr ( tags , '__iter__' ) and type ( tags ) == str : tags = [ tags ] nodes = set ( self . cluster_tags [ 'all' ] ) for tag in tags : if re . match ( r"\w+ \d{1,2}" , tag ) : tag , number = tag . split ( ) try : branch = self . cluster_tree [ tag ] [ int ( number ) - 1 ] excep... | Tag format . |
36,194 | def get_tags_of_port ( self , port ) : return ( sorted ( [ tag for tag in self . cluster_tags if port in self . cluster_tags [ tag ] ] ) ) | Get all tags related to a given port . |
36,195 | def wait_for ( self , ports , interval = 1.0 , timeout = 30 , to_start = True ) : threads = [ ] queue = Queue . Queue ( ) for port in ports : threads . append ( threading . Thread ( target = wait_for_host , args = ( port , interval , timeout , to_start , queue , self . ssl_pymongo_options ) ) ) if self . args and 'verb... | Spawn threads to ping host using a list of ports . |
36,196 | def _load_parameters ( self ) : datapath = self . dir startup_file = os . path . join ( datapath , '.mlaunch_startup' ) if not os . path . exists ( startup_file ) : return False in_dict = json . load ( open ( startup_file , 'rb' ) ) if 'protocol_version' not in in_dict : in_dict [ 'protocol_version' ] = 1 self . loaded... | Load the . mlaunch_startup file that exists in each datadir . |
36,197 | def _create_paths ( self , basedir , name = None ) : if name : datapath = os . path . join ( basedir , name ) else : datapath = basedir dbpath = os . path . join ( datapath , 'db' ) if not os . path . exists ( dbpath ) : os . makedirs ( dbpath ) if self . args [ 'verbose' ] : print ( 'creating directory: %s' % dbpath )... | Create datadir and subdir paths . |
36,198 | def _filter_valid_arguments ( self , arguments , binary = "mongod" , config = False ) : if self . args and self . args [ 'binarypath' ] : binary = os . path . join ( self . args [ 'binarypath' ] , binary ) ret = ( subprocess . Popen ( [ '%s' % binary , '--help' ] , stderr = subprocess . STDOUT , stdout = subprocess . P... | Return a list of accepted arguments . |
36,199 | def _initiate_replset ( self , port , name , maxwait = 30 ) : if not self . args [ 'replicaset' ] and name != 'configRepl' : if self . args [ 'verbose' ] : print ( 'Skipping replica set initialization for %s' % name ) return con = self . client ( 'localhost:%i' % port ) try : rs_status = con [ 'admin' ] . command ( { '... | Initiate replica set . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.