id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,100 | ethereum/py-evm | eth/vm/stack.py | Stack.swap | def swap(self, position: int) -> None:
"""
Perform a SWAP operation on the stack.
"""
idx = -1 * position - 1
try:
self.values[-1], self.values[idx] = self.values[idx], self.values[-1]
except IndexError:
raise InsufficientStack("Insufficient stack items for SWAP{0}".format(position)) | python | def swap(self, position: int) -> None:
"""
Perform a SWAP operation on the stack.
"""
idx = -1 * position - 1
try:
self.values[-1], self.values[idx] = self.values[idx], self.values[-1]
except IndexError:
raise InsufficientStack("Insufficient stack items for SWAP{0}".format(position)) | [
"def",
"swap",
"(",
"self",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"idx",
"=",
"-",
"1",
"*",
"position",
"-",
"1",
"try",
":",
"self",
".",
"values",
"[",
"-",
"1",
"]",
",",
"self",
".",
"values",
"[",
"idx",
"]",
"=",
"self",
".",
"values",
"[",
"idx",
"]",
",",
"self",
".",
"values",
"[",
"-",
"1",
"]",
"except",
"IndexError",
":",
"raise",
"InsufficientStack",
"(",
"\"Insufficient stack items for SWAP{0}\"",
".",
"format",
"(",
"position",
")",
")"
] | Perform a SWAP operation on the stack. | [
"Perform",
"a",
"SWAP",
"operation",
"on",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L89-L97 |
230,101 | ethereum/py-evm | eth/vm/stack.py | Stack.dup | def dup(self, position: int) -> None:
"""
Perform a DUP operation on the stack.
"""
idx = -1 * position
try:
self.push(self.values[idx])
except IndexError:
raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) | python | def dup(self, position: int) -> None:
"""
Perform a DUP operation on the stack.
"""
idx = -1 * position
try:
self.push(self.values[idx])
except IndexError:
raise InsufficientStack("Insufficient stack items for DUP{0}".format(position)) | [
"def",
"dup",
"(",
"self",
",",
"position",
":",
"int",
")",
"->",
"None",
":",
"idx",
"=",
"-",
"1",
"*",
"position",
"try",
":",
"self",
".",
"push",
"(",
"self",
".",
"values",
"[",
"idx",
"]",
")",
"except",
"IndexError",
":",
"raise",
"InsufficientStack",
"(",
"\"Insufficient stack items for DUP{0}\"",
".",
"format",
"(",
"position",
")",
")"
] | Perform a DUP operation on the stack. | [
"Perform",
"a",
"DUP",
"operation",
"on",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/stack.py#L99-L107 |
230,102 | ethereum/py-evm | eth/db/header.py | HeaderDB.get_canonical_block_hash | def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32:
"""
Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_hash(self.db, block_number) | python | def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32:
"""
Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_hash(self.db, block_number) | [
"def",
"get_canonical_block_hash",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
")",
"->",
"Hash32",
":",
"return",
"self",
".",
"_get_canonical_block_hash",
"(",
"self",
".",
"db",
",",
"block_number",
")"
] | Returns the block hash for the canonical block at the given number.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain. | [
"Returns",
"the",
"block",
"hash",
"for",
"the",
"canonical",
"block",
"at",
"the",
"given",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L97-L104 |
230,103 | ethereum/py-evm | eth/db/header.py | HeaderDB.get_canonical_block_header_by_number | def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader:
"""
Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_header_by_number(self.db, block_number) | python | def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader:
"""
Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain.
"""
return self._get_canonical_block_header_by_number(self.db, block_number) | [
"def",
"get_canonical_block_header_by_number",
"(",
"self",
",",
"block_number",
":",
"BlockNumber",
")",
"->",
"BlockHeader",
":",
"return",
"self",
".",
"_get_canonical_block_header_by_number",
"(",
"self",
".",
"db",
",",
"block_number",
")"
] | Returns the block header with the given number in the canonical chain.
Raises BlockNotFound if there's no block header with the given number in the
canonical chain. | [
"Returns",
"the",
"block",
"header",
"with",
"the",
"given",
"number",
"in",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L120-L127 |
230,104 | ethereum/py-evm | eth/db/header.py | HeaderDB.persist_header_chain | def persist_header_chain(self,
headers: Iterable[BlockHeader]
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers
"""
with self.db.atomic_batch() as db:
return self._persist_header_chain(db, headers) | python | def persist_header_chain(self,
headers: Iterable[BlockHeader]
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers
"""
with self.db.atomic_batch() as db:
return self._persist_header_chain(db, headers) | [
"def",
"persist_header_chain",
"(",
"self",
",",
"headers",
":",
"Iterable",
"[",
"BlockHeader",
"]",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")",
"as",
"db",
":",
"return",
"self",
".",
"_persist_header_chain",
"(",
"db",
",",
"headers",
")"
] | Return two iterable of headers, the first containing the new canonical headers,
the second containing the old canonical headers | [
"Return",
"two",
"iterable",
"of",
"headers",
"the",
"first",
"containing",
"the",
"new",
"canonical",
"headers",
"the",
"second",
"containing",
"the",
"old",
"canonical",
"headers"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L198-L206 |
230,105 | ethereum/py-evm | eth/db/header.py | HeaderDB._set_as_canonical_chain_head | def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain
"""
try:
header = cls._get_block_header_by_hash(db, block_hash)
except HeaderNotFound:
raise ValueError(
"Cannot use unknown block hash as canonical head: {}".format(block_hash)
)
new_canonical_headers = tuple(reversed(cls._find_new_ancestors(db, header)))
old_canonical_headers = []
for h in new_canonical_headers:
try:
old_canonical_hash = cls._get_canonical_block_hash(db, h.block_number)
except HeaderNotFound:
# no old_canonical block, and no more possible
break
else:
old_canonical_header = cls._get_block_header_by_hash(db, old_canonical_hash)
old_canonical_headers.append(old_canonical_header)
for h in new_canonical_headers:
cls._add_block_number_to_hash_lookup(db, h)
db.set(SchemaV1.make_canonical_head_hash_lookup_key(), header.hash)
return new_canonical_headers, tuple(old_canonical_headers) | python | def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain
"""
try:
header = cls._get_block_header_by_hash(db, block_hash)
except HeaderNotFound:
raise ValueError(
"Cannot use unknown block hash as canonical head: {}".format(block_hash)
)
new_canonical_headers = tuple(reversed(cls._find_new_ancestors(db, header)))
old_canonical_headers = []
for h in new_canonical_headers:
try:
old_canonical_hash = cls._get_canonical_block_hash(db, h.block_number)
except HeaderNotFound:
# no old_canonical block, and no more possible
break
else:
old_canonical_header = cls._get_block_header_by_hash(db, old_canonical_hash)
old_canonical_headers.append(old_canonical_header)
for h in new_canonical_headers:
cls._add_block_number_to_hash_lookup(db, h)
db.set(SchemaV1.make_canonical_head_hash_lookup_key(), header.hash)
return new_canonical_headers, tuple(old_canonical_headers) | [
"def",
"_set_as_canonical_chain_head",
"(",
"cls",
",",
"db",
":",
"BaseDB",
",",
"block_hash",
":",
"Hash32",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"try",
":",
"header",
"=",
"cls",
".",
"_get_block_header_by_hash",
"(",
"db",
",",
"block_hash",
")",
"except",
"HeaderNotFound",
":",
"raise",
"ValueError",
"(",
"\"Cannot use unknown block hash as canonical head: {}\"",
".",
"format",
"(",
"block_hash",
")",
")",
"new_canonical_headers",
"=",
"tuple",
"(",
"reversed",
"(",
"cls",
".",
"_find_new_ancestors",
"(",
"db",
",",
"header",
")",
")",
")",
"old_canonical_headers",
"=",
"[",
"]",
"for",
"h",
"in",
"new_canonical_headers",
":",
"try",
":",
"old_canonical_hash",
"=",
"cls",
".",
"_get_canonical_block_hash",
"(",
"db",
",",
"h",
".",
"block_number",
")",
"except",
"HeaderNotFound",
":",
"# no old_canonical block, and no more possible",
"break",
"else",
":",
"old_canonical_header",
"=",
"cls",
".",
"_get_block_header_by_hash",
"(",
"db",
",",
"old_canonical_hash",
")",
"old_canonical_headers",
".",
"append",
"(",
"old_canonical_header",
")",
"for",
"h",
"in",
"new_canonical_headers",
":",
"cls",
".",
"_add_block_number_to_hash_lookup",
"(",
"db",
",",
"h",
")",
"db",
".",
"set",
"(",
"SchemaV1",
".",
"make_canonical_head_hash_lookup_key",
"(",
")",
",",
"header",
".",
"hash",
")",
"return",
"new_canonical_headers",
",",
"tuple",
"(",
"old_canonical_headers",
")"
] | Sets the canonical chain HEAD to the block header as specified by the
given block hash.
:return: a tuple of the headers that are newly in the canonical chain, and the headers that
are no longer in the canonical chain | [
"Sets",
"the",
"canonical",
"chain",
"HEAD",
"to",
"the",
"block",
"header",
"as",
"specified",
"by",
"the",
"given",
"block",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L286-L320 |
230,106 | ethereum/py-evm | eth/db/header.py | HeaderDB._add_block_number_to_hash_lookup | def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None:
"""
Sets a record in the database to allow looking up this header by its
block number.
"""
block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(
header.block_number
)
db.set(
block_number_to_hash_key,
rlp.encode(header.hash, sedes=rlp.sedes.binary),
) | python | def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None:
"""
Sets a record in the database to allow looking up this header by its
block number.
"""
block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key(
header.block_number
)
db.set(
block_number_to_hash_key,
rlp.encode(header.hash, sedes=rlp.sedes.binary),
) | [
"def",
"_add_block_number_to_hash_lookup",
"(",
"db",
":",
"BaseDB",
",",
"header",
":",
"BlockHeader",
")",
"->",
"None",
":",
"block_number_to_hash_key",
"=",
"SchemaV1",
".",
"make_block_number_to_hash_lookup_key",
"(",
"header",
".",
"block_number",
")",
"db",
".",
"set",
"(",
"block_number_to_hash_key",
",",
"rlp",
".",
"encode",
"(",
"header",
".",
"hash",
",",
"sedes",
"=",
"rlp",
".",
"sedes",
".",
"binary",
")",
",",
")"
] | Sets a record in the database to allow looking up this header by its
block number. | [
"Sets",
"a",
"record",
"in",
"the",
"database",
"to",
"allow",
"looking",
"up",
"this",
"header",
"by",
"its",
"block",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/header.py#L357-L368 |
230,107 | ethereum/py-evm | eth/_utils/headers.py | compute_gas_limit_bounds | def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]:
"""
Compute the boundaries for the block gas limit based on the parent block.
"""
boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
upper_bound = parent.gas_limit + boundary_range
lower_bound = max(GAS_LIMIT_MINIMUM, parent.gas_limit - boundary_range)
return lower_bound, upper_bound | python | def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]:
"""
Compute the boundaries for the block gas limit based on the parent block.
"""
boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR
upper_bound = parent.gas_limit + boundary_range
lower_bound = max(GAS_LIMIT_MINIMUM, parent.gas_limit - boundary_range)
return lower_bound, upper_bound | [
"def",
"compute_gas_limit_bounds",
"(",
"parent",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"boundary_range",
"=",
"parent",
".",
"gas_limit",
"//",
"GAS_LIMIT_ADJUSTMENT_FACTOR",
"upper_bound",
"=",
"parent",
".",
"gas_limit",
"+",
"boundary_range",
"lower_bound",
"=",
"max",
"(",
"GAS_LIMIT_MINIMUM",
",",
"parent",
".",
"gas_limit",
"-",
"boundary_range",
")",
"return",
"lower_bound",
",",
"upper_bound"
] | Compute the boundaries for the block gas limit based on the parent block. | [
"Compute",
"the",
"boundaries",
"for",
"the",
"block",
"gas",
"limit",
"based",
"on",
"the",
"parent",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L20-L27 |
230,108 | ethereum/py-evm | eth/_utils/headers.py | compute_gas_limit | def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int:
"""
A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit.
"""
if gas_limit_floor < GAS_LIMIT_MINIMUM:
raise ValueError(
"The `gas_limit_floor` value must be greater than the "
"GAS_LIMIT_MINIMUM. Got {0}. Must be greater than "
"{1}".format(gas_limit_floor, GAS_LIMIT_MINIMUM)
)
decay = parent_header.gas_limit // GAS_LIMIT_EMA_DENOMINATOR
if parent_header.gas_used:
usage_increase = (
parent_header.gas_used * GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR
) // (
GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR
) // (
GAS_LIMIT_EMA_DENOMINATOR
)
else:
usage_increase = 0
gas_limit = max(
GAS_LIMIT_MINIMUM,
parent_header.gas_limit - decay + usage_increase
)
if gas_limit < GAS_LIMIT_MINIMUM:
return GAS_LIMIT_MINIMUM
elif gas_limit < gas_limit_floor:
return parent_header.gas_limit + decay
else:
return gas_limit | python | def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int:
"""
A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit.
"""
if gas_limit_floor < GAS_LIMIT_MINIMUM:
raise ValueError(
"The `gas_limit_floor` value must be greater than the "
"GAS_LIMIT_MINIMUM. Got {0}. Must be greater than "
"{1}".format(gas_limit_floor, GAS_LIMIT_MINIMUM)
)
decay = parent_header.gas_limit // GAS_LIMIT_EMA_DENOMINATOR
if parent_header.gas_used:
usage_increase = (
parent_header.gas_used * GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR
) // (
GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR
) // (
GAS_LIMIT_EMA_DENOMINATOR
)
else:
usage_increase = 0
gas_limit = max(
GAS_LIMIT_MINIMUM,
parent_header.gas_limit - decay + usage_increase
)
if gas_limit < GAS_LIMIT_MINIMUM:
return GAS_LIMIT_MINIMUM
elif gas_limit < gas_limit_floor:
return parent_header.gas_limit + decay
else:
return gas_limit | [
"def",
"compute_gas_limit",
"(",
"parent_header",
":",
"BlockHeader",
",",
"gas_limit_floor",
":",
"int",
")",
"->",
"int",
":",
"if",
"gas_limit_floor",
"<",
"GAS_LIMIT_MINIMUM",
":",
"raise",
"ValueError",
"(",
"\"The `gas_limit_floor` value must be greater than the \"",
"\"GAS_LIMIT_MINIMUM. Got {0}. Must be greater than \"",
"\"{1}\"",
".",
"format",
"(",
"gas_limit_floor",
",",
"GAS_LIMIT_MINIMUM",
")",
")",
"decay",
"=",
"parent_header",
".",
"gas_limit",
"//",
"GAS_LIMIT_EMA_DENOMINATOR",
"if",
"parent_header",
".",
"gas_used",
":",
"usage_increase",
"=",
"(",
"parent_header",
".",
"gas_used",
"*",
"GAS_LIMIT_USAGE_ADJUSTMENT_NUMERATOR",
")",
"//",
"(",
"GAS_LIMIT_USAGE_ADJUSTMENT_DENOMINATOR",
")",
"//",
"(",
"GAS_LIMIT_EMA_DENOMINATOR",
")",
"else",
":",
"usage_increase",
"=",
"0",
"gas_limit",
"=",
"max",
"(",
"GAS_LIMIT_MINIMUM",
",",
"parent_header",
".",
"gas_limit",
"-",
"decay",
"+",
"usage_increase",
")",
"if",
"gas_limit",
"<",
"GAS_LIMIT_MINIMUM",
":",
"return",
"GAS_LIMIT_MINIMUM",
"elif",
"gas_limit",
"<",
"gas_limit_floor",
":",
"return",
"parent_header",
".",
"gas_limit",
"+",
"decay",
"else",
":",
"return",
"gas_limit"
] | A simple strategy for adjusting the gas limit.
For each block:
- decrease by 1/1024th of the gas limit from the previous block
- increase by 50% of the total gas used by the previous block
If the value is less than the given `gas_limit_floor`:
- increase the gas limit by 1/1024th of the gas limit from the previous block.
If the value is less than the GAS_LIMIT_MINIMUM:
- use the GAS_LIMIT_MINIMUM as the new gas limit. | [
"A",
"simple",
"strategy",
"for",
"adjusting",
"the",
"gas",
"limit",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L30-L77 |
230,109 | ethereum/py-evm | eth/_utils/headers.py | generate_header_from_parent_header | def generate_header_from_parent_header(
compute_difficulty_fn: Callable[[BlockHeader, int], int],
parent_header: BlockHeader,
coinbase: Address,
timestamp: Optional[int] = None,
extra_data: bytes = b'') -> BlockHeader:
"""
Generate BlockHeader from state_root and parent_header
"""
if timestamp is None:
timestamp = max(int(time.time()), parent_header.timestamp + 1)
elif timestamp <= parent_header.timestamp:
raise ValueError(
"header.timestamp ({}) should be higher than"
"parent_header.timestamp ({})".format(
timestamp,
parent_header.timestamp,
)
)
header = BlockHeader(
difficulty=compute_difficulty_fn(parent_header, timestamp),
block_number=(parent_header.block_number + 1),
gas_limit=compute_gas_limit(
parent_header,
gas_limit_floor=GENESIS_GAS_LIMIT,
),
timestamp=timestamp,
parent_hash=parent_header.hash,
state_root=parent_header.state_root,
coinbase=coinbase,
extra_data=extra_data,
)
return header | python | def generate_header_from_parent_header(
compute_difficulty_fn: Callable[[BlockHeader, int], int],
parent_header: BlockHeader,
coinbase: Address,
timestamp: Optional[int] = None,
extra_data: bytes = b'') -> BlockHeader:
"""
Generate BlockHeader from state_root and parent_header
"""
if timestamp is None:
timestamp = max(int(time.time()), parent_header.timestamp + 1)
elif timestamp <= parent_header.timestamp:
raise ValueError(
"header.timestamp ({}) should be higher than"
"parent_header.timestamp ({})".format(
timestamp,
parent_header.timestamp,
)
)
header = BlockHeader(
difficulty=compute_difficulty_fn(parent_header, timestamp),
block_number=(parent_header.block_number + 1),
gas_limit=compute_gas_limit(
parent_header,
gas_limit_floor=GENESIS_GAS_LIMIT,
),
timestamp=timestamp,
parent_hash=parent_header.hash,
state_root=parent_header.state_root,
coinbase=coinbase,
extra_data=extra_data,
)
return header | [
"def",
"generate_header_from_parent_header",
"(",
"compute_difficulty_fn",
":",
"Callable",
"[",
"[",
"BlockHeader",
",",
"int",
"]",
",",
"int",
"]",
",",
"parent_header",
":",
"BlockHeader",
",",
"coinbase",
":",
"Address",
",",
"timestamp",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"extra_data",
":",
"bytes",
"=",
"b''",
")",
"->",
"BlockHeader",
":",
"if",
"timestamp",
"is",
"None",
":",
"timestamp",
"=",
"max",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"parent_header",
".",
"timestamp",
"+",
"1",
")",
"elif",
"timestamp",
"<=",
"parent_header",
".",
"timestamp",
":",
"raise",
"ValueError",
"(",
"\"header.timestamp ({}) should be higher than\"",
"\"parent_header.timestamp ({})\"",
".",
"format",
"(",
"timestamp",
",",
"parent_header",
".",
"timestamp",
",",
")",
")",
"header",
"=",
"BlockHeader",
"(",
"difficulty",
"=",
"compute_difficulty_fn",
"(",
"parent_header",
",",
"timestamp",
")",
",",
"block_number",
"=",
"(",
"parent_header",
".",
"block_number",
"+",
"1",
")",
",",
"gas_limit",
"=",
"compute_gas_limit",
"(",
"parent_header",
",",
"gas_limit_floor",
"=",
"GENESIS_GAS_LIMIT",
",",
")",
",",
"timestamp",
"=",
"timestamp",
",",
"parent_hash",
"=",
"parent_header",
".",
"hash",
",",
"state_root",
"=",
"parent_header",
".",
"state_root",
",",
"coinbase",
"=",
"coinbase",
",",
"extra_data",
"=",
"extra_data",
",",
")",
"return",
"header"
] | Generate BlockHeader from state_root and parent_header | [
"Generate",
"BlockHeader",
"from",
"state_root",
"and",
"parent_header"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/headers.py#L80-L113 |
230,110 | ethereum/py-evm | eth/tools/_utils/normalization.py | state_definition_to_dict | def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
"""Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
```
"""
if isinstance(state_definition, Mapping):
state_dict = state_definition
elif isinstance(state_definition, Iterable):
state_dicts = [
assoc_in(
{},
state_item[:-1],
state_item[-1]
) if not isinstance(state_item, Mapping) else state_item
for state_item
in state_definition
]
if not is_cleanly_mergable(*state_dicts):
raise ValidationError("Some state item is defined multiple times")
state_dict = deep_merge(*state_dicts)
else:
assert TypeError("State definition must either be a mapping or a sequence")
seen_keys = set(concat(d.keys() for d in state_dict.values()))
bad_keys = seen_keys - set(["balance", "nonce", "storage", "code"])
if bad_keys:
raise ValidationError(
"State definition contains the following invalid account fields: {}".format(
", ".join(bad_keys)
)
)
return state_dict | python | def state_definition_to_dict(state_definition: GeneralState) -> AccountState:
"""Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
```
"""
if isinstance(state_definition, Mapping):
state_dict = state_definition
elif isinstance(state_definition, Iterable):
state_dicts = [
assoc_in(
{},
state_item[:-1],
state_item[-1]
) if not isinstance(state_item, Mapping) else state_item
for state_item
in state_definition
]
if not is_cleanly_mergable(*state_dicts):
raise ValidationError("Some state item is defined multiple times")
state_dict = deep_merge(*state_dicts)
else:
assert TypeError("State definition must either be a mapping or a sequence")
seen_keys = set(concat(d.keys() for d in state_dict.values()))
bad_keys = seen_keys - set(["balance", "nonce", "storage", "code"])
if bad_keys:
raise ValidationError(
"State definition contains the following invalid account fields: {}".format(
", ".join(bad_keys)
)
)
return state_dict | [
"def",
"state_definition_to_dict",
"(",
"state_definition",
":",
"GeneralState",
")",
"->",
"AccountState",
":",
"if",
"isinstance",
"(",
"state_definition",
",",
"Mapping",
")",
":",
"state_dict",
"=",
"state_definition",
"elif",
"isinstance",
"(",
"state_definition",
",",
"Iterable",
")",
":",
"state_dicts",
"=",
"[",
"assoc_in",
"(",
"{",
"}",
",",
"state_item",
"[",
":",
"-",
"1",
"]",
",",
"state_item",
"[",
"-",
"1",
"]",
")",
"if",
"not",
"isinstance",
"(",
"state_item",
",",
"Mapping",
")",
"else",
"state_item",
"for",
"state_item",
"in",
"state_definition",
"]",
"if",
"not",
"is_cleanly_mergable",
"(",
"*",
"state_dicts",
")",
":",
"raise",
"ValidationError",
"(",
"\"Some state item is defined multiple times\"",
")",
"state_dict",
"=",
"deep_merge",
"(",
"*",
"state_dicts",
")",
"else",
":",
"assert",
"TypeError",
"(",
"\"State definition must either be a mapping or a sequence\"",
")",
"seen_keys",
"=",
"set",
"(",
"concat",
"(",
"d",
".",
"keys",
"(",
")",
"for",
"d",
"in",
"state_dict",
".",
"values",
"(",
")",
")",
")",
"bad_keys",
"=",
"seen_keys",
"-",
"set",
"(",
"[",
"\"balance\"",
",",
"\"nonce\"",
",",
"\"storage\"",
",",
"\"code\"",
"]",
")",
"if",
"bad_keys",
":",
"raise",
"ValidationError",
"(",
"\"State definition contains the following invalid account fields: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"bad_keys",
")",
")",
")",
"return",
"state_dict"
] | Convert a state definition to the canonical dict form.
State can either be defined in the canonical form, or as a list of sub states that are then
merged to one. Sub states can either be given as dictionaries themselves, or as tuples where
the last element is the value and all others the keys for this value in the nested state
dictionary. Example:
```
[
("0xaabb", "balance", 3),
("0xaabb", "storage", {
4: 5,
}),
"0xbbcc", {
"balance": 6,
"nonce": 7
}
]
``` | [
"Convert",
"a",
"state",
"definition",
"to",
"the",
"canonical",
"dict",
"form",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/normalization.py#L183-L231 |
230,111 | ethereum/py-evm | eth/db/journal.py | Journal.record_changeset | def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets.
"""
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
else:
changeset_id = uuid.uuid4()
self.journal_data[changeset_id] = {}
return changeset_id | python | def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets.
"""
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
else:
changeset_id = uuid.uuid4()
self.journal_data[changeset_id] = {}
return changeset_id | [
"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",
"else",
":",
"changeset_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
"self",
".",
"journal_data",
"[",
"changeset_id",
"]",
"=",
"{",
"}",
"return",
"changeset_id"
] | Creates a new changeset. Changesets are referenced by a random uuid4
to prevent collisions between multiple changesets. | [
"Creates",
"a",
"new",
"changeset",
".",
"Changesets",
"are",
"referenced",
"by",
"a",
"random",
"uuid4",
"to",
"prevent",
"collisions",
"between",
"multiple",
"changesets",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L93-L109 |
230,112 | ethereum/py-evm | eth/db/journal.py | Journal.pop_changeset | def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
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)
changesets_to_pop = all_ids[changeset_idx:]
popped_clears = tuple(idx for idx in changesets_to_pop if idx in self._clears_at)
if popped_clears:
last_clear_idx = changesets_to_pop.index(popped_clears[-1])
changesets_to_drop = changesets_to_pop[:last_clear_idx]
changesets_to_merge = changesets_to_pop[last_clear_idx:]
else:
changesets_to_drop = ()
changesets_to_merge = changesets_to_pop
# we pull all of the changesets *after* the changeset we are
# reverting to and collapse them to a single set of keys (giving
# precedence to later changesets)
changeset_data = merge(*(
self.journal_data.pop(c_id)
for c_id
in changesets_to_merge
))
# drop the changes on the floor if they came before a clear that is being committed
for changeset_id in changesets_to_drop:
self.journal_data.pop(changeset_id)
self._clears_at.difference_update(popped_clears)
return changeset_data | python | def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets.
"""
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)
changesets_to_pop = all_ids[changeset_idx:]
popped_clears = tuple(idx for idx in changesets_to_pop if idx in self._clears_at)
if popped_clears:
last_clear_idx = changesets_to_pop.index(popped_clears[-1])
changesets_to_drop = changesets_to_pop[:last_clear_idx]
changesets_to_merge = changesets_to_pop[last_clear_idx:]
else:
changesets_to_drop = ()
changesets_to_merge = changesets_to_pop
# we pull all of the changesets *after* the changeset we are
# reverting to and collapse them to a single set of keys (giving
# precedence to later changesets)
changeset_data = merge(*(
self.journal_data.pop(c_id)
for c_id
in changesets_to_merge
))
# drop the changes on the floor if they came before a clear that is being committed
for changeset_id in changesets_to_drop:
self.journal_data.pop(changeset_id)
self._clears_at.difference_update(popped_clears)
return changeset_data | [
"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",
")",
"changesets_to_pop",
"=",
"all_ids",
"[",
"changeset_idx",
":",
"]",
"popped_clears",
"=",
"tuple",
"(",
"idx",
"for",
"idx",
"in",
"changesets_to_pop",
"if",
"idx",
"in",
"self",
".",
"_clears_at",
")",
"if",
"popped_clears",
":",
"last_clear_idx",
"=",
"changesets_to_pop",
".",
"index",
"(",
"popped_clears",
"[",
"-",
"1",
"]",
")",
"changesets_to_drop",
"=",
"changesets_to_pop",
"[",
":",
"last_clear_idx",
"]",
"changesets_to_merge",
"=",
"changesets_to_pop",
"[",
"last_clear_idx",
":",
"]",
"else",
":",
"changesets_to_drop",
"=",
"(",
")",
"changesets_to_merge",
"=",
"changesets_to_pop",
"# we pull all of the changesets *after* the changeset we are",
"# reverting to and collapse them to a single set of keys (giving",
"# precedence to later changesets)",
"changeset_data",
"=",
"merge",
"(",
"*",
"(",
"self",
".",
"journal_data",
".",
"pop",
"(",
"c_id",
")",
"for",
"c_id",
"in",
"changesets_to_merge",
")",
")",
"# drop the changes on the floor if they came before a clear that is being committed",
"for",
"changeset_id",
"in",
"changesets_to_drop",
":",
"self",
".",
"journal_data",
".",
"pop",
"(",
"changeset_id",
")",
"self",
".",
"_clears_at",
".",
"difference_update",
"(",
"popped_clears",
")",
"return",
"changeset_data"
] | Returns all changes from the given changeset. This includes all of
the changes from any subsequent changeset, giving precidence to
later changesets. | [
"Returns",
"all",
"changes",
"from",
"the",
"given",
"changeset",
".",
"This",
"includes",
"all",
"of",
"the",
"changes",
"from",
"any",
"subsequent",
"changeset",
"giving",
"precidence",
"to",
"later",
"changesets",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L111-L146 |
230,113 | ethereum/py-evm | eth/db/journal.py | Journal.commit_changeset | def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Collapses all changes for the given changeset into the previous
changesets if it exists.
"""
does_clear = self.has_clear(changeset_id)
changeset_data = self.pop_changeset(changeset_id)
if not self.is_empty():
# we only have to assign changeset data into the latest changeset if
# there is one.
if does_clear:
# if there was a clear and more changesets underneath then clear the latest
# changeset, and replace with a new clear changeset
self.latest = {}
self._clears_at.add(self.latest_id)
self.record_changeset()
self.latest = changeset_data
else:
# otherwise, merge in all the current data
self.latest = merge(
self.latest,
changeset_data,
)
return changeset_data | python | def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]:
"""
Collapses all changes for the given changeset into the previous
changesets if it exists.
"""
does_clear = self.has_clear(changeset_id)
changeset_data = self.pop_changeset(changeset_id)
if not self.is_empty():
# we only have to assign changeset data into the latest changeset if
# there is one.
if does_clear:
# if there was a clear and more changesets underneath then clear the latest
# changeset, and replace with a new clear changeset
self.latest = {}
self._clears_at.add(self.latest_id)
self.record_changeset()
self.latest = changeset_data
else:
# otherwise, merge in all the current data
self.latest = merge(
self.latest,
changeset_data,
)
return changeset_data | [
"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",
"(",
")",
":",
"# we only have to assign changeset data into the latest changeset if",
"# there is one.",
"if",
"does_clear",
":",
"# if there was a clear and more changesets underneath then clear the latest",
"# changeset, and replace with a new clear changeset",
"self",
".",
"latest",
"=",
"{",
"}",
"self",
".",
"_clears_at",
".",
"add",
"(",
"self",
".",
"latest_id",
")",
"self",
".",
"record_changeset",
"(",
")",
"self",
".",
"latest",
"=",
"changeset_data",
"else",
":",
"# otherwise, merge in all the current data",
"self",
".",
"latest",
"=",
"merge",
"(",
"self",
".",
"latest",
",",
"changeset_data",
",",
")",
"return",
"changeset_data"
] | Collapses all changes for the given changeset into the previous
changesets if it exists. | [
"Collapses",
"all",
"changes",
"for",
"the",
"given",
"changeset",
"into",
"the",
"previous",
"changesets",
"if",
"it",
"exists",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L168-L191 |
230,114 | ethereum/py-evm | eth/db/journal.py | JournalDB._validate_changeset | def _validate_changeset(self, changeset_id: uuid.UUID) -> None:
"""
Checks to be sure the changeset is known by the journal
"""
if not self.journal.has_changeset(changeset_id):
raise ValidationError("Changeset not found in journal: {0}".format(
str(changeset_id)
)) | python | def _validate_changeset(self, changeset_id: uuid.UUID) -> None:
"""
Checks to be sure the changeset is known by the journal
"""
if not self.journal.has_changeset(changeset_id):
raise ValidationError("Changeset not found in journal: {0}".format(
str(changeset_id)
)) | [
"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 | [
"Checks",
"to",
"be",
"sure",
"the",
"changeset",
"is",
"known",
"by",
"the",
"journal"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L354-L361 |
230,115 | ethereum/py-evm | eth/db/journal.py | JournalDB.record | def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Starts a new recording and returns an id for the associated changeset
"""
return self.journal.record_changeset(custom_changeset_id) | python | def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID:
"""
Starts a new recording and returns an id for the associated changeset
"""
return self.journal.record_changeset(custom_changeset_id) | [
"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 | [
"Starts",
"a",
"new",
"recording",
"and",
"returns",
"an",
"id",
"for",
"the",
"associated",
"changeset"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L366-L370 |
230,116 | ethereum/py-evm | eth/db/journal.py | JournalDB.discard | def discard(self, changeset_id: uuid.UUID) -> None:
"""
Throws away all journaled data starting at the given changeset
"""
self._validate_changeset(changeset_id)
self.journal.pop_changeset(changeset_id) | python | def discard(self, changeset_id: uuid.UUID) -> None:
"""
Throws away all journaled data starting at the given changeset
"""
self._validate_changeset(changeset_id)
self.journal.pop_changeset(changeset_id) | [
"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 | [
"Throws",
"away",
"all",
"journaled",
"data",
"starting",
"at",
"the",
"given",
"changeset"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L372-L377 |
230,117 | ethereum/py-evm | eth/db/journal.py | JournalDB.commit | def commit(self, changeset_id: uuid.UUID) -> None:
"""
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.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB().
"""
self._validate_changeset(changeset_id)
journal_data = self.journal.commit_changeset(changeset_id)
if self.journal.is_empty():
# Ensure the journal automatically restarts recording after
# it has been persisted to the underlying db
self.reset()
for key, value in journal_data.items():
try:
if value is DELETED_ENTRY:
del self.wrapped_db[key]
elif value is ERASE_CREATED_ENTRY:
pass
else:
self.wrapped_db[key] = cast(bytes, value)
except Exception:
self._reapply_changeset_to_journal(changeset_id, journal_data)
raise | python | def commit(self, changeset_id: uuid.UUID) -> None:
"""
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.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB().
"""
self._validate_changeset(changeset_id)
journal_data = self.journal.commit_changeset(changeset_id)
if self.journal.is_empty():
# Ensure the journal automatically restarts recording after
# it has been persisted to the underlying db
self.reset()
for key, value in journal_data.items():
try:
if value is DELETED_ENTRY:
del self.wrapped_db[key]
elif value is ERASE_CREATED_ENTRY:
pass
else:
self.wrapped_db[key] = cast(bytes, value)
except Exception:
self._reapply_changeset_to_journal(changeset_id, journal_data)
raise | [
"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",
"(",
")",
":",
"# Ensure the journal automatically restarts recording after",
"# it has been persisted to the underlying db",
"self",
".",
"reset",
"(",
")",
"for",
"key",
",",
"value",
"in",
"journal_data",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"value",
"is",
"DELETED_ENTRY",
":",
"del",
"self",
".",
"wrapped_db",
"[",
"key",
"]",
"elif",
"value",
"is",
"ERASE_CREATED_ENTRY",
":",
"pass",
"else",
":",
"self",
".",
"wrapped_db",
"[",
"key",
"]",
"=",
"cast",
"(",
"bytes",
",",
"value",
")",
"except",
"Exception",
":",
"self",
".",
"_reapply_changeset_to_journal",
"(",
"changeset_id",
",",
"journal_data",
")",
"raise"
] | 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.
If this is the base changeset then all changes will be written to
the underlying database and the Journal starts a new recording.
Typically, callers won't have access to the base changeset, because
it is dropped during .reset() which is called in JournalDB(). | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/journal.py#L379-L408 |
230,118 | ethereum/py-evm | eth/_utils/bn128.py | FQP_point_to_FQ2_point | def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]:
"""
Transform FQP to FQ2 for type hinting.
"""
return (
FQ2(pt[0].coeffs),
FQ2(pt[1].coeffs),
FQ2(pt[2].coeffs),
) | python | def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]:
"""
Transform FQP to FQ2 for type hinting.
"""
return (
FQ2(pt[0].coeffs),
FQ2(pt[1].coeffs),
FQ2(pt[2].coeffs),
) | [
"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. | [
"Transform",
"FQP",
"to",
"FQ2",
"for",
"type",
"hinting",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/bn128.py#L34-L42 |
230,119 | ethereum/py-evm | eth/vm/opcode.py | Opcode.as_opcode | def as_opcode(cls: Type[T],
logic_fn: Callable[..., Any],
mnemonic: str,
gas_cost: int) -> Type[T]:
"""
Class factory method for turning vanilla functions into Opcode classes.
"""
if gas_cost:
@functools.wraps(logic_fn)
def wrapped_logic_fn(computation: 'BaseComputation') -> Any:
"""
Wrapper functionf or the logic function which consumes the base
opcode gas cost prior to execution.
"""
computation.consume_gas(
gas_cost,
mnemonic,
)
return logic_fn(computation)
else:
wrapped_logic_fn = logic_fn
props = {
'__call__': staticmethod(wrapped_logic_fn),
'mnemonic': mnemonic,
'gas_cost': gas_cost,
}
opcode_cls = type("opcode:{0}".format(mnemonic), (cls,), props)
return opcode_cls() | python | def as_opcode(cls: Type[T],
logic_fn: Callable[..., Any],
mnemonic: str,
gas_cost: int) -> Type[T]:
"""
Class factory method for turning vanilla functions into Opcode classes.
"""
if gas_cost:
@functools.wraps(logic_fn)
def wrapped_logic_fn(computation: 'BaseComputation') -> Any:
"""
Wrapper functionf or the logic function which consumes the base
opcode gas cost prior to execution.
"""
computation.consume_gas(
gas_cost,
mnemonic,
)
return logic_fn(computation)
else:
wrapped_logic_fn = logic_fn
props = {
'__call__': staticmethod(wrapped_logic_fn),
'mnemonic': mnemonic,
'gas_cost': gas_cost,
}
opcode_cls = type("opcode:{0}".format(mnemonic), (cls,), props)
return opcode_cls() | [
"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",
":",
"\"\"\"\n Wrapper functionf or the logic function which consumes the base\n opcode gas cost prior to execution.\n \"\"\"",
"computation",
".",
"consume_gas",
"(",
"gas_cost",
",",
"mnemonic",
",",
")",
"return",
"logic_fn",
"(",
"computation",
")",
"else",
":",
"wrapped_logic_fn",
"=",
"logic_fn",
"props",
"=",
"{",
"'__call__'",
":",
"staticmethod",
"(",
"wrapped_logic_fn",
")",
",",
"'mnemonic'",
":",
"mnemonic",
",",
"'gas_cost'",
":",
"gas_cost",
",",
"}",
"opcode_cls",
"=",
"type",
"(",
"\"opcode:{0}\"",
".",
"format",
"(",
"mnemonic",
")",
",",
"(",
"cls",
",",
")",
",",
"props",
")",
"return",
"opcode_cls",
"(",
")"
] | Class factory method for turning vanilla functions into Opcode classes. | [
"Class",
"factory",
"method",
"for",
"turning",
"vanilla",
"functions",
"into",
"Opcode",
"classes",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/opcode.py#L52-L80 |
230,120 | ethereum/py-evm | eth/db/account.py | AccountDB._wipe_storage | def _wipe_storage(self, address: Address) -> None:
"""
Wipe out the storage, without explicitly handling the storage root update
"""
account_store = self._get_address_store(address)
self._dirty_accounts.add(address)
account_store.delete() | python | def _wipe_storage(self, address: Address) -> None:
"""
Wipe out the storage, without explicitly handling the storage root update
"""
account_store = self._get_address_store(address)
self._dirty_accounts.add(address)
account_store.delete() | [
"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 | [
"Wipe",
"out",
"the",
"storage",
"without",
"explicitly",
"handling",
"the",
"storage",
"root",
"update"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/account.py#L287-L293 |
230,121 | ethereum/py-evm | eth/tools/fixtures/fillers/common.py | setup_main_filler | def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]:
"""
Kick off the filler generation process by creating the general filler scaffold with
a test name and general information about the testing environment.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+
"""
return setup_filler(name, merge(DEFAULT_MAIN_ENVIRONMENT, environment or {})) | python | def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]:
"""
Kick off the filler generation process by creating the general filler scaffold with
a test name and general information about the testing environment.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+
"""
return setup_filler(name, merge(DEFAULT_MAIN_ENVIRONMENT, environment or {})) | [
"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.
For tests for the main chain, the `environment` parameter is expected to be a dictionary with
some or all of the following keys:
+------------------------+---------------------------------+
| key | description |
+========================+=================================+
| ``"currentCoinbase"`` | the coinbase address |
+------------------------+---------------------------------+
| ``"currentNumber"`` | the block number |
+------------------------+---------------------------------+
| ``"previousHash"`` | the hash of the parent block |
+------------------------+---------------------------------+
| ``"currentDifficulty"``| the block's difficulty |
+------------------------+---------------------------------+
| ``"currentGasLimit"`` | the block's gas limit |
+------------------------+---------------------------------+
| ``"currentTimestamp"`` | the timestamp of the block |
+------------------------+---------------------------------+ | [
"Kick",
"off",
"the",
"filler",
"generation",
"process",
"by",
"creating",
"the",
"general",
"filler",
"scaffold",
"with",
"a",
"test",
"name",
"and",
"general",
"information",
"about",
"the",
"testing",
"environment",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L114-L138 |
230,122 | ethereum/py-evm | eth/tools/fixtures/fillers/common.py | pre_state | def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None:
"""
Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>})
"""
@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)
defaults = {address: {
"balance": 0,
"nonce": 0,
"code": b"",
"storage": {},
} for address in pre_state}
new_pre_state = deep_merge(defaults, old_pre_state, pre_state)
return assoc_in(filler, [test_name, "pre"], new_pre_state) | python | def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None:
"""
Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>})
"""
@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)
defaults = {address: {
"balance": 0,
"nonce": 0,
"code": b"",
"storage": {},
} for address in pre_state}
new_pre_state = deep_merge(defaults, old_pre_state, pre_state)
return assoc_in(filler, [test_name, "pre"], new_pre_state) | [
"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",
")",
"defaults",
"=",
"{",
"address",
":",
"{",
"\"balance\"",
":",
"0",
",",
"\"nonce\"",
":",
"0",
",",
"\"code\"",
":",
"b\"\"",
",",
"\"storage\"",
":",
"{",
"}",
",",
"}",
"for",
"address",
"in",
"pre_state",
"}",
"new_pre_state",
"=",
"deep_merge",
"(",
"defaults",
",",
"old_pre_state",
",",
"pre_state",
")",
"return",
"assoc_in",
"(",
"filler",
",",
"[",
"test_name",
",",
"\"pre\"",
"]",
",",
"new_pre_state",
")"
] | Specify the state prior to the test execution. Multiple invocations don't override
the state but extend it instead.
In general, the elements of `state_definitions` are nested dictionaries of the following form:
.. code-block:: python
{
address: {
"nonce": <account nonce>,
"balance": <account balance>,
"code": <account code>,
"storage": {
<storage slot>: <storage value>
}
}
}
To avoid unnecessary nesting especially if only few fields per account are specified, the
following and similar formats are possible as well:
.. code-block:: python
(address, "balance", <account balance>)
(address, "storage", <storage slot>, <storage value>)
(address, "storage", {<storage slot>: <storage value>})
(address, {"balance", <account balance>}) | [
"Specify",
"the",
"state",
"prior",
"to",
"the",
"test",
"execution",
".",
"Multiple",
"invocations",
"don",
"t",
"override",
"the",
"state",
"but",
"extend",
"it",
"instead",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L141-L185 |
230,123 | ethereum/py-evm | eth/tools/fixtures/fillers/common.py | expect | def expect(post_state: Dict[str, Any]=None,
networks: Any=None,
transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]:
"""
Specify the expected result for the test.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``).
"""
return partial(_expect, post_state, networks, transaction) | python | def expect(post_state: Dict[str, Any]=None,
networks: Any=None,
transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]:
"""
Specify the expected result for the test.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``).
"""
return partial(_expect, post_state, networks, transaction) | [
"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.
For state tests, multiple expectations can be given, differing in the transaction data, gas
limit, and value, in the applicable networks, and as a result also in the post state. VM tests
support only a single expectation with no specified network and no transaction (here, its role
is played by :func:`~eth.tools.fixtures.fillers.execution`).
* ``post_state`` is a list of state definition in the same form as expected
by :func:`~eth.tools.fixtures.fillers.pre_state`. State items that are
not set explicitly default to their pre state.
* ``networks`` defines the forks under which the expectation is applicable. It should be a
sublist of the following identifiers (also available in `ALL_FORKS`):
* ``"Frontier"``
* ``"Homestead"``
* ``"EIP150"``
* ``"EIP158"``
* ``"Byzantium"``
* ``transaction`` is a dictionary coming in two variants. For the main shard:
+----------------+-------------------------------+
| key | description |
+================+===============================+
| ``"data"`` | the transaction data, |
+----------------+-------------------------------+
| ``"gasLimit"`` | the transaction gas limit, |
+----------------+-------------------------------+
| ``"gasPrice"`` | the gas price, |
+----------------+-------------------------------+
| ``"nonce"`` | the transaction nonce, |
+----------------+-------------------------------+
| ``"value"`` | the transaction value |
+----------------+-------------------------------+
In addition, one should specify either the signature itself (via keys ``"v"``, ``"r"``,
and ``"s"``) or a private key used for signing (via ``"secretKey"``). | [
"Specify",
"the",
"expected",
"result",
"for",
"the",
"test",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/fillers/common.py#L245-L289 |
230,124 | ethereum/py-evm | eth/vm/logic/context.py | calldataload | def calldataload(computation: BaseComputation) -> None:
"""
Load call data into memory.
"""
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')
computation.stack_push(normalized_value) | python | def calldataload(computation: BaseComputation) -> None:
"""
Load call data into memory.
"""
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')
computation.stack_push(normalized_value) | [
"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'",
")",
"computation",
".",
"stack_push",
"(",
"normalized_value",
")"
] | Load call data into memory. | [
"Load",
"call",
"data",
"into",
"memory",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/context.py#L39-L49 |
230,125 | ethereum/py-evm | eth/_utils/numeric.py | clamp | def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
"""
Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``.
"""
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclusive_upper_bound:
return inclusive_upper_bound
else:
return value | python | def clamp(inclusive_lower_bound: int,
inclusive_upper_bound: int,
value: int) -> int:
"""
Bound the given ``value`` between ``inclusive_lower_bound`` and
``inclusive_upper_bound``.
"""
if value <= inclusive_lower_bound:
return inclusive_lower_bound
elif value >= inclusive_upper_bound:
return inclusive_upper_bound
else:
return value | [
"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``. | [
"Bound",
"the",
"given",
"value",
"between",
"inclusive_lower_bound",
"and",
"inclusive_upper_bound",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/numeric.py#L90-L102 |
230,126 | ethereum/py-evm | eth/_utils/numeric.py | integer_squareroot | def integer_squareroot(value: int) -> int:
"""
Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer.
"""
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.localcontext() as ctx:
ctx.prec = 128
return int(decimal.Decimal(value).sqrt()) | python | def integer_squareroot(value: int) -> int:
"""
Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer.
"""
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.localcontext() as ctx:
ctx.prec = 128
return int(decimal.Decimal(value).sqrt()) | [
"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",
".",
"localcontext",
"(",
")",
"as",
"ctx",
":",
"ctx",
".",
"prec",
"=",
"128",
"return",
"int",
"(",
"decimal",
".",
"Decimal",
"(",
"value",
")",
".",
"sqrt",
"(",
")",
")"
] | Return the integer square root of ``value``.
Uses Python's decimal module to compute the square root of ``value`` with
a precision of 128-bits. The value 128 is chosen since the largest square
root of a 256-bit integer is a 128-bit integer. | [
"Return",
"the",
"integer",
"square",
"root",
"of",
"value",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/numeric.py#L105-L128 |
230,127 | ethereum/py-evm | eth/db/atomic.py | AtomicDBWriteBatch._commit_unless_raises | def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']:
"""
Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB.
"""
readable_write_batch = cls(write_target_db) # type: AtomicDBWriteBatch
try:
yield readable_write_batch
except Exception:
cls.logger.exception(
"Unexpected error in atomic db write, dropped partial writes: %r",
readable_write_batch._diff(),
)
raise
else:
readable_write_batch._commit()
finally:
# force a shutdown of this batch, to prevent out-of-context usage
readable_write_batch._track_diff = None
readable_write_batch._write_target_db = None | python | def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']:
"""
Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB.
"""
readable_write_batch = cls(write_target_db) # type: AtomicDBWriteBatch
try:
yield readable_write_batch
except Exception:
cls.logger.exception(
"Unexpected error in atomic db write, dropped partial writes: %r",
readable_write_batch._diff(),
)
raise
else:
readable_write_batch._commit()
finally:
# force a shutdown of this batch, to prevent out-of-context usage
readable_write_batch._track_diff = None
readable_write_batch._write_target_db = None | [
"def",
"_commit_unless_raises",
"(",
"cls",
",",
"write_target_db",
":",
"BaseDB",
")",
"->",
"Iterator",
"[",
"'AtomicDBWriteBatch'",
"]",
":",
"readable_write_batch",
"=",
"cls",
"(",
"write_target_db",
")",
"# type: AtomicDBWriteBatch",
"try",
":",
"yield",
"readable_write_batch",
"except",
"Exception",
":",
"cls",
".",
"logger",
".",
"exception",
"(",
"\"Unexpected error in atomic db write, dropped partial writes: %r\"",
",",
"readable_write_batch",
".",
"_diff",
"(",
")",
",",
")",
"raise",
"else",
":",
"readable_write_batch",
".",
"_commit",
"(",
")",
"finally",
":",
"# force a shutdown of this batch, to prevent out-of-context usage",
"readable_write_batch",
".",
"_track_diff",
"=",
"None",
"readable_write_batch",
".",
"_write_target_db",
"=",
"None"
] | Commit all writes inside the context, unless an exception was raised.
Although this is technically an external API, it (and this whole class) is only intended
to be used by AtomicDB. | [
"Commit",
"all",
"writes",
"inside",
"the",
"context",
"unless",
"an",
"exception",
"was",
"raised",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/atomic.py#L116-L137 |
230,128 | ethereum/py-evm | eth/vm/logic/comparison.py | slt | def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
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)) | python | def slt(computation: BaseComputation) -> None:
"""
Signed Lesser Comparison
"""
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)) | [
"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 | [
"Signed",
"Lesser",
"Comparison"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/logic/comparison.py#L39-L53 |
230,129 | ethereum/py-evm | eth/tools/builder/chain/builders.py | build | def build(obj: Any, *applicators: Callable[..., Any]) -> Any:
"""
Run the provided object through the series of applicator functions.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance.
"""
if isinstance(obj, BaseChain):
return pipe(obj, copy(), *applicators)
else:
return pipe(obj, *applicators) | python | def build(obj: Any, *applicators: Callable[..., Any]) -> Any:
"""
Run the provided object through the series of applicator functions.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance.
"""
if isinstance(obj, BaseChain):
return pipe(obj, copy(), *applicators)
else:
return pipe(obj, *applicators) | [
"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.
If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the
applicators will be run on a copy of the chain and thus will not mutate the
provided chain instance. | [
"Run",
"the",
"provided",
"object",
"through",
"the",
"series",
"of",
"applicator",
"functions",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L78-L89 |
230,130 | ethereum/py-evm | eth/tools/builder/chain/builders.py | name | def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Assign the given name to the chain class.
"""
return chain_class.configure(__name__=class_name) | python | def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Assign the given name to the chain class.
"""
return chain_class.configure(__name__=class_name) | [
"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. | [
"Assign",
"the",
"given",
"name",
"to",
"the",
"chain",
"class",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L96-L100 |
230,131 | ethereum/py-evm | eth/tools/builder/chain/builders.py | chain_id | def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``chain_id`` for the chain class.
"""
return chain_class.configure(chain_id=chain_id) | python | def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Set the ``chain_id`` for the chain class.
"""
return chain_class.configure(chain_id=chain_id) | [
"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. | [
"Set",
"the",
"chain_id",
"for",
"the",
"chain",
"class",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L104-L108 |
230,132 | ethereum/py-evm | eth/tools/builder/chain/builders.py | fork_at | def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at`
"""
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),)
validate_vm_configuration(vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | python | def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at`
"""
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),)
validate_vm_configuration(vm_configuration)
return chain_class.configure(vm_configuration=vm_configuration) | [
"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",
")",
",",
")",
"validate_vm_configuration",
"(",
"vm_configuration",
")",
"return",
"chain_class",
".",
"configure",
"(",
"vm_configuration",
"=",
"vm_configuration",
")"
] | Adds the ``vm_class`` to the chain's ``vm_configuration``.
.. code-block:: python
from eth.chains.base import MiningChain
from eth.tools.builder.chain import build, fork_at
FrontierOnlyChain = build(MiningChain, fork_at(FrontierVM, 0))
# these two classes are functionally equivalent.
class FrontierOnlyChain(MiningChain):
vm_configuration = (
(0, FrontierVM),
)
.. note:: This function is curriable.
The following pre-curried versions of this function are available as well,
one for each mainnet fork.
* :func:`~eth.tools.builder.chain.frontier_at`
* :func:`~eth.tools.builder.chain.homestead_at`
* :func:`~eth.tools.builder.chain.tangerine_whistle_at`
* :func:`~eth.tools.builder.chain.spurious_dragon_at`
* :func:`~eth.tools.builder.chain.byzantium_at`
* :func:`~eth.tools.builder.chain.constantinople_at` | [
"Adds",
"the",
"vm_class",
"to",
"the",
"chain",
"s",
"vm_configuration",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L112-L148 |
230,133 | ethereum/py-evm | eth/tools/builder/chain/builders.py | enable_pow_mining | def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms.
"""
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_configuration) | python | def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms.
"""
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_configuration) | [
"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_configuration",
")"
] | Inject on demand generation of the proof of work mining seal on newly
mined blocks into each of the chain's vms. | [
"Inject",
"on",
"demand",
"generation",
"of",
"the",
"proof",
"of",
"work",
"mining",
"seal",
"on",
"newly",
"mined",
"blocks",
"into",
"each",
"of",
"the",
"chain",
"s",
"vms",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L269-L278 |
230,134 | ethereum/py-evm | eth/tools/builder/chain/builders.py | disable_pow_check | def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
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.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
if issubclass(chain_class, NoChainSealValidationMixin):
# Seal validation already disabled, hence nothing to change
chain_class_without_seal_validation = chain_class
else:
chain_class_without_seal_validation = type(
chain_class.__name__,
(chain_class, NoChainSealValidationMixin),
{},
)
return chain_class_without_seal_validation.configure( # type: ignore
vm_configuration=_mix_in_disable_seal_validation(
chain_class_without_seal_validation.vm_configuration # type: ignore
),
) | python | def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]:
"""
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.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled.
"""
if not chain_class.vm_configuration:
raise ValidationError("Chain class has no vm_configuration")
if issubclass(chain_class, NoChainSealValidationMixin):
# Seal validation already disabled, hence nothing to change
chain_class_without_seal_validation = chain_class
else:
chain_class_without_seal_validation = type(
chain_class.__name__,
(chain_class, NoChainSealValidationMixin),
{},
)
return chain_class_without_seal_validation.configure( # type: ignore
vm_configuration=_mix_in_disable_seal_validation(
chain_class_without_seal_validation.vm_configuration # type: ignore
),
) | [
"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",
")",
":",
"# Seal validation already disabled, hence nothing to change",
"chain_class_without_seal_validation",
"=",
"chain_class",
"else",
":",
"chain_class_without_seal_validation",
"=",
"type",
"(",
"chain_class",
".",
"__name__",
",",
"(",
"chain_class",
",",
"NoChainSealValidationMixin",
")",
",",
"{",
"}",
",",
")",
"return",
"chain_class_without_seal_validation",
".",
"configure",
"(",
"# type: ignore",
"vm_configuration",
"=",
"_mix_in_disable_seal_validation",
"(",
"chain_class_without_seal_validation",
".",
"vm_configuration",
"# type: ignore",
")",
",",
")"
] | 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.
.. note::
blocks mined this way will not be importable on any chain that does not
have proof of work disabled. | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L309-L335 |
230,135 | ethereum/py-evm | eth/tools/builder/chain/builders.py | genesis | def genesis(chain_class: BaseChain,
db: BaseAtomicDB=None,
params: Dict[str, HeaderParams]=None,
state: GeneralState=None) -> BaseChain:
"""
Initialize the given chain class with the given genesis header parameters
and chain state.
"""
if state is None:
genesis_state = {} # type: AccountState
else:
genesis_state = _fill_and_normalize_state(state)
genesis_params_defaults = _get_default_genesis_params(genesis_state)
if params is None:
genesis_params = genesis_params_defaults
else:
genesis_params = merge(genesis_params_defaults, params)
if db is None:
base_db = AtomicDB() # type: BaseAtomicDB
else:
base_db = db
return chain_class.from_genesis(base_db, genesis_params, genesis_state) | python | def genesis(chain_class: BaseChain,
db: BaseAtomicDB=None,
params: Dict[str, HeaderParams]=None,
state: GeneralState=None) -> BaseChain:
"""
Initialize the given chain class with the given genesis header parameters
and chain state.
"""
if state is None:
genesis_state = {} # type: AccountState
else:
genesis_state = _fill_and_normalize_state(state)
genesis_params_defaults = _get_default_genesis_params(genesis_state)
if params is None:
genesis_params = genesis_params_defaults
else:
genesis_params = merge(genesis_params_defaults, params)
if db is None:
base_db = AtomicDB() # type: BaseAtomicDB
else:
base_db = db
return chain_class.from_genesis(base_db, genesis_params, genesis_state) | [
"def",
"genesis",
"(",
"chain_class",
":",
"BaseChain",
",",
"db",
":",
"BaseAtomicDB",
"=",
"None",
",",
"params",
":",
"Dict",
"[",
"str",
",",
"HeaderParams",
"]",
"=",
"None",
",",
"state",
":",
"GeneralState",
"=",
"None",
")",
"->",
"BaseChain",
":",
"if",
"state",
"is",
"None",
":",
"genesis_state",
"=",
"{",
"}",
"# type: AccountState",
"else",
":",
"genesis_state",
"=",
"_fill_and_normalize_state",
"(",
"state",
")",
"genesis_params_defaults",
"=",
"_get_default_genesis_params",
"(",
"genesis_state",
")",
"if",
"params",
"is",
"None",
":",
"genesis_params",
"=",
"genesis_params_defaults",
"else",
":",
"genesis_params",
"=",
"merge",
"(",
"genesis_params_defaults",
",",
"params",
")",
"if",
"db",
"is",
"None",
":",
"base_db",
"=",
"AtomicDB",
"(",
")",
"# type: BaseAtomicDB",
"else",
":",
"base_db",
"=",
"db",
"return",
"chain_class",
".",
"from_genesis",
"(",
"base_db",
",",
"genesis_params",
",",
"genesis_state",
")"
] | Initialize the given chain class with the given genesis header parameters
and chain state. | [
"Initialize",
"the",
"given",
"chain",
"class",
"with",
"the",
"given",
"genesis",
"header",
"parameters",
"and",
"chain",
"state",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L354-L379 |
230,136 | ethereum/py-evm | eth/tools/builder/chain/builders.py | mine_block | def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain:
"""
Mine a new block on the chain. Header parameters for the new block can be
overridden using keyword arguments.
"""
if not isinstance(chain, MiningChain):
raise ValidationError('`mine_block` may only be used on MiningChain instances')
chain.mine_block(**kwargs)
return chain | python | def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain:
"""
Mine a new block on the chain. Header parameters for the new block can be
overridden using keyword arguments.
"""
if not isinstance(chain, MiningChain):
raise ValidationError('`mine_block` may only be used on MiningChain instances')
chain.mine_block(**kwargs)
return chain | [
"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. | [
"Mine",
"a",
"new",
"block",
"on",
"the",
"chain",
".",
"Header",
"parameters",
"for",
"the",
"new",
"block",
"can",
"be",
"overridden",
"using",
"keyword",
"arguments",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L386-L395 |
230,137 | ethereum/py-evm | eth/tools/builder/chain/builders.py | import_block | def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain:
"""
Import the provided ``block`` into the chain.
"""
chain.import_block(block)
return chain | python | def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain:
"""
Import the provided ``block`` into the chain.
"""
chain.import_block(block)
return chain | [
"def",
"import_block",
"(",
"block",
":",
"BaseBlock",
",",
"chain",
":",
"BaseChain",
")",
"->",
"BaseChain",
":",
"chain",
".",
"import_block",
"(",
"block",
")",
"return",
"chain"
] | Import the provided ``block`` into the chain. | [
"Import",
"the",
"provided",
"block",
"into",
"the",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L411-L416 |
230,138 | ethereum/py-evm | eth/tools/builder/chain/builders.py | copy | def copy(chain: MiningChain) -> MiningChain:
"""
Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain.
"""
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(type(base_db)))
if isinstance(base_db.wrapped_db, MemoryDB):
db = AtomicDB(MemoryDB(base_db.wrapped_db.kv_store.copy()))
else:
raise ValidationError("Unsupported wrapped database: {0}".format(type(base_db.wrapped_db)))
chain_copy = type(chain)(db, chain.header)
return chain_copy | python | def copy(chain: MiningChain) -> MiningChain:
"""
Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain.
"""
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(type(base_db)))
if isinstance(base_db.wrapped_db, MemoryDB):
db = AtomicDB(MemoryDB(base_db.wrapped_db.kv_store.copy()))
else:
raise ValidationError("Unsupported wrapped database: {0}".format(type(base_db.wrapped_db)))
chain_copy = type(chain)(db, chain.header)
return chain_copy | [
"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",
"(",
"type",
"(",
"base_db",
")",
")",
")",
"if",
"isinstance",
"(",
"base_db",
".",
"wrapped_db",
",",
"MemoryDB",
")",
":",
"db",
"=",
"AtomicDB",
"(",
"MemoryDB",
"(",
"base_db",
".",
"wrapped_db",
".",
"kv_store",
".",
"copy",
"(",
")",
")",
")",
"else",
":",
"raise",
"ValidationError",
"(",
"\"Unsupported wrapped database: {0}\"",
".",
"format",
"(",
"type",
"(",
"base_db",
".",
"wrapped_db",
")",
")",
")",
"chain_copy",
"=",
"type",
"(",
"chain",
")",
"(",
"db",
",",
"chain",
".",
"header",
")",
"return",
"chain_copy"
] | Make a copy of the chain at the given state. Actions performed on the
resulting chain will not affect the original chain. | [
"Make",
"a",
"copy",
"of",
"the",
"chain",
"at",
"the",
"given",
"state",
".",
"Actions",
"performed",
"on",
"the",
"resulting",
"chain",
"will",
"not",
"affect",
"the",
"original",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L433-L450 |
230,139 | ethereum/py-evm | eth/tools/builder/chain/builders.py | chain_split | def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501
"""
Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
)
"""
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) -> Iterable[BaseChain]:
for split_fns in splits:
result = build(
chain,
*split_fns,
)
yield result
return _chain_split | python | def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501
"""
Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
)
"""
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) -> Iterable[BaseChain]:
for split_fns in splits:
result = build(
chain,
*split_fns,
)
yield result
return _chain_split | [
"def",
"chain_split",
"(",
"*",
"splits",
":",
"Iterable",
"[",
"Callable",
"[",
"...",
",",
"Any",
"]",
"]",
")",
"->",
"Callable",
"[",
"[",
"BaseChain",
"]",
",",
"Iterable",
"[",
"BaseChain",
"]",
"]",
":",
"# noqa: E501",
"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",
")",
"->",
"Iterable",
"[",
"BaseChain",
"]",
":",
"for",
"split_fns",
"in",
"splits",
":",
"result",
"=",
"build",
"(",
"chain",
",",
"*",
"split_fns",
",",
")",
"yield",
"result",
"return",
"_chain_split"
] | Construct and execute multiple concurrent forks of the chain.
Any number of forks may be executed. For each fork, provide an iterable of
commands.
Returns the resulting chain objects for each fork.
.. code-block:: python
chain_a, chain_b = build(
mining_chain,
chain_split(
(mine_block(extra_data=b'chain-a'), mine_block()),
(mine_block(extra_data=b'chain-b'), mine_block(), mine_block()),
),
) | [
"Construct",
"and",
"execute",
"multiple",
"concurrent",
"forks",
"of",
"the",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L453-L486 |
230,140 | ethereum/py-evm | eth/tools/builder/chain/builders.py | at_block_number | def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:
"""
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.
"""
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_block = type(chain)(db, chain.create_header_from_parent(at_block.header))
return chain_at_block | python | def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain:
"""
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.
"""
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_block = type(chain)(db, chain.create_header_from_parent(at_block.header))
return chain_at_block | [
"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_block",
"=",
"type",
"(",
"chain",
")",
"(",
"db",
",",
"chain",
".",
"create_header_from_parent",
"(",
"at_block",
".",
"header",
")",
")",
"return",
"chain_at_block"
] | 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. | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/builder/chain/builders.py#L490-L502 |
230,141 | ethereum/py-evm | eth/tools/fixtures/loading.py | load_json_fixture | def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | python | def load_json_fixture(fixture_path: str) -> Dict[str, Any]:
"""
Loads a fixture file, caching the most recent files it loaded.
"""
with open(fixture_path) as fixture_file:
file_fixtures = json.load(fixture_file)
return file_fixtures | [
"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. | [
"Loads",
"a",
"fixture",
"file",
"caching",
"the",
"most",
"recent",
"files",
"it",
"loaded",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/loading.py#L54-L60 |
230,142 | ethereum/py-evm | eth/tools/fixtures/loading.py | load_fixture | def load_fixture(fixture_path: str,
fixture_key: str,
normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]:
"""
Loads a specific fixture from a fixture file, optionally passing it through
a normalization function.
"""
file_fixtures = load_json_fixture(fixture_path)
fixture = normalize_fn(file_fixtures[fixture_key])
return fixture | python | def load_fixture(fixture_path: str,
fixture_key: str,
normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]:
"""
Loads a specific fixture from a fixture file, optionally passing it through
a normalization function.
"""
file_fixtures = load_json_fixture(fixture_path)
fixture = normalize_fn(file_fixtures[fixture_key])
return fixture | [
"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. | [
"Loads",
"a",
"specific",
"fixture",
"from",
"a",
"fixture",
"file",
"optionally",
"passing",
"it",
"through",
"a",
"normalization",
"function",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/loading.py#L63-L72 |
230,143 | ethereum/py-evm | eth/_utils/version.py | construct_evm_runtime_identifier | def construct_evm_runtime_identifier() -> str:
"""
Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5'
"""
return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format(
__version__,
platform=sys.platform,
v=sys.version_info,
# mypy Doesn't recognize the `sys` module as having an `implementation` attribute.
imp=sys.implementation,
) | python | def construct_evm_runtime_identifier() -> str:
"""
Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5'
"""
return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format(
__version__,
platform=sys.platform,
v=sys.version_info,
# mypy Doesn't recognize the `sys` module as having an `implementation` attribute.
imp=sys.implementation,
) | [
"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",
",",
"# mypy Doesn't recognize the `sys` module as having an `implementation` attribute.",
"imp",
"=",
"sys",
".",
"implementation",
",",
")"
] | Constructs the EVM runtime identifier string
e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5' | [
"Constructs",
"the",
"EVM",
"runtime",
"identifier",
"string"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/version.py#L6-L18 |
230,144 | ethereum/py-evm | eth/estimators/gas.py | binary_gas_search | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete
"""
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' parameter")
minimum_transaction = SpoofTransaction(
transaction,
gas=transaction.intrinsic_gas,
gas_price=0,
)
if _get_computation_error(state, minimum_transaction) is None:
return transaction.intrinsic_gas
maximum_transaction = SpoofTransaction(
transaction,
gas=state.gas_limit,
gas_price=0,
)
error = _get_computation_error(state, maximum_transaction)
if error is not None:
raise error
minimum_viable = state.gas_limit
maximum_out_of_gas = transaction.intrinsic_gas
while minimum_viable - maximum_out_of_gas > tolerance:
midpoint = (minimum_viable + maximum_out_of_gas) // 2
test_transaction = SpoofTransaction(transaction, gas=midpoint)
if _get_computation_error(state, test_transaction) is None:
minimum_viable = midpoint
else:
maximum_out_of_gas = midpoint
return minimum_viable | python | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete
"""
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' parameter")
minimum_transaction = SpoofTransaction(
transaction,
gas=transaction.intrinsic_gas,
gas_price=0,
)
if _get_computation_error(state, minimum_transaction) is None:
return transaction.intrinsic_gas
maximum_transaction = SpoofTransaction(
transaction,
gas=state.gas_limit,
gas_price=0,
)
error = _get_computation_error(state, maximum_transaction)
if error is not None:
raise error
minimum_viable = state.gas_limit
maximum_out_of_gas = transaction.intrinsic_gas
while minimum_viable - maximum_out_of_gas > tolerance:
midpoint = (minimum_viable + maximum_out_of_gas) // 2
test_transaction = SpoofTransaction(transaction, gas=midpoint)
if _get_computation_error(state, test_transaction) is None:
minimum_viable = midpoint
else:
maximum_out_of_gas = midpoint
return minimum_viable | [
"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' parameter\"",
")",
"minimum_transaction",
"=",
"SpoofTransaction",
"(",
"transaction",
",",
"gas",
"=",
"transaction",
".",
"intrinsic_gas",
",",
"gas_price",
"=",
"0",
",",
")",
"if",
"_get_computation_error",
"(",
"state",
",",
"minimum_transaction",
")",
"is",
"None",
":",
"return",
"transaction",
".",
"intrinsic_gas",
"maximum_transaction",
"=",
"SpoofTransaction",
"(",
"transaction",
",",
"gas",
"=",
"state",
".",
"gas_limit",
",",
"gas_price",
"=",
"0",
",",
")",
"error",
"=",
"_get_computation_error",
"(",
"state",
",",
"maximum_transaction",
")",
"if",
"error",
"is",
"not",
"None",
":",
"raise",
"error",
"minimum_viable",
"=",
"state",
".",
"gas_limit",
"maximum_out_of_gas",
"=",
"transaction",
".",
"intrinsic_gas",
"while",
"minimum_viable",
"-",
"maximum_out_of_gas",
">",
"tolerance",
":",
"midpoint",
"=",
"(",
"minimum_viable",
"+",
"maximum_out_of_gas",
")",
"//",
"2",
"test_transaction",
"=",
"SpoofTransaction",
"(",
"transaction",
",",
"gas",
"=",
"midpoint",
")",
"if",
"_get_computation_error",
"(",
"state",
",",
"test_transaction",
")",
"is",
"None",
":",
"minimum_viable",
"=",
"midpoint",
"else",
":",
"maximum_out_of_gas",
"=",
"midpoint",
"return",
"minimum_viable"
] | Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state.gas_limit].
After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, state.gas_limit].
After the first run not out of gas, the range is: (largest_limit_out_of_gas, smallest_success].
:param int tolerance: When the range of estimates is less than tolerance,
return the top of the range.
:returns int: The smallest confirmed gas to not throw an OutOfGas exception,
subject to tolerance. If OutOfGas is thrown at block limit, return block limit.
:raises VMError: if the computation fails even when given the block gas_limit to complete | [
"Run",
"the",
"transaction",
"with",
"various",
"gas",
"limits",
"progressively",
"approaching",
"the",
"minimum",
"needed",
"to",
"succeed",
"without",
"an",
"OutOfGas",
"exception",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/estimators/gas.py#L28-L78 |
230,145 | ethereum/py-evm | eth/db/storage.py | StorageLookup.commit_to | def commit_to(self, db: BaseDB) -> None:
"""
Trying to commit changes when nothing has been written will raise a
ValidationError
"""
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 commit."
)
self._trie_nodes_batch.commit_to(db, apply_deletes=False)
self._clear_changed_root() | python | def commit_to(self, db: BaseDB) -> None:
"""
Trying to commit changes when nothing has been written will raise a
ValidationError
"""
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 commit."
)
self._trie_nodes_batch.commit_to(db, apply_deletes=False)
self._clear_changed_root() | [
"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 commit.\"",
")",
"self",
".",
"_trie_nodes_batch",
".",
"commit_to",
"(",
"db",
",",
"apply_deletes",
"=",
"False",
")",
"self",
".",
"_clear_changed_root",
"(",
")"
] | Trying to commit changes when nothing has been written will raise a
ValidationError | [
"Trying",
"to",
"commit",
"changes",
"when",
"nothing",
"has",
"been",
"written",
"will",
"raise",
"a",
"ValidationError"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/storage.py#L131-L143 |
230,146 | ethereum/py-evm | eth/db/storage.py | AccountStorageDB._validate_flushed | def _validate_flushed(self) -> None:
"""
Will raise an exception if there are some changes made since the last persist.
"""
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
) | python | def _validate_flushed(self) -> None:
"""
Will raise an exception if there are some changes made since the last persist.
"""
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
) | [
"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. | [
"Will",
"raise",
"an",
"exception",
"if",
"there",
"are",
"some",
"changes",
"made",
"since",
"the",
"last",
"persist",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/storage.py#L243-L251 |
230,147 | ethereum/py-evm | eth/vm/memory.py | Memory.write | def write(self, start_position: int, size: int, value: bytes) -> None:
"""
Write `value` into memory.
"""
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):
self._bytes[start_position + idx] = v | python | def write(self, start_position: int, size: int, value: bytes) -> None:
"""
Write `value` into memory.
"""
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):
self._bytes[start_position + idx] = v | [
"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",
")",
":",
"self",
".",
"_bytes",
"[",
"start_position",
"+",
"idx",
"]",
"=",
"v"
] | Write `value` into memory. | [
"Write",
"value",
"into",
"memory",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/memory.py#L49-L61 |
230,148 | ethereum/py-evm | eth/vm/memory.py | Memory.read | def read(self, start_position: int, size: int) -> memoryview:
"""
Return a view into the memory
"""
return memoryview(self._bytes)[start_position:start_position + size] | python | def read(self, start_position: int, size: int) -> memoryview:
"""
Return a view into the memory
"""
return memoryview(self._bytes)[start_position:start_position + size] | [
"def",
"read",
"(",
"self",
",",
"start_position",
":",
"int",
",",
"size",
":",
"int",
")",
"->",
"memoryview",
":",
"return",
"memoryview",
"(",
"self",
".",
"_bytes",
")",
"[",
"start_position",
":",
"start_position",
"+",
"size",
"]"
] | Return a view into the memory | [
"Return",
"a",
"view",
"into",
"the",
"memory"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/memory.py#L63-L67 |
230,149 | ethereum/py-evm | eth/vm/memory.py | Memory.read_bytes | def read_bytes(self, start_position: int, size: int) -> bytes:
"""
Read a value from memory and return a fresh bytes instance
"""
return bytes(self._bytes[start_position:start_position + size]) | python | def read_bytes(self, start_position: int, size: int) -> bytes:
"""
Read a value from memory and return a fresh bytes instance
"""
return bytes(self._bytes[start_position:start_position + size]) | [
"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 | [
"Read",
"a",
"value",
"from",
"memory",
"and",
"return",
"a",
"fresh",
"bytes",
"instance"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/memory.py#L69-L73 |
230,150 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.extend_memory | def extend_memory(self, start_position: int, size: int) -> None:
"""
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.
"""
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(before_size)
after_cost = memory_gas_cost(after_size)
if self.logger.show_debug2:
self.logger.debug2(
"MEMORY: size (%s -> %s) | cost (%s -> %s)",
before_size,
after_size,
before_cost,
after_cost,
)
if size:
if before_cost < after_cost:
gas_fee = after_cost - before_cost
self._gas_meter.consume_gas(
gas_fee,
reason=" ".join((
"Expanding memory",
str(before_size),
"->",
str(after_size),
))
)
self._memory.extend(start_position, size) | python | def extend_memory(self, start_position: int, size: int) -> None:
"""
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.
"""
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(before_size)
after_cost = memory_gas_cost(after_size)
if self.logger.show_debug2:
self.logger.debug2(
"MEMORY: size (%s -> %s) | cost (%s -> %s)",
before_size,
after_size,
before_cost,
after_cost,
)
if size:
if before_cost < after_cost:
gas_fee = after_cost - before_cost
self._gas_meter.consume_gas(
gas_fee,
reason=" ".join((
"Expanding memory",
str(before_size),
"->",
str(after_size),
))
)
self._memory.extend(start_position, size) | [
"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",
"(",
"before_size",
")",
"after_cost",
"=",
"memory_gas_cost",
"(",
"after_size",
")",
"if",
"self",
".",
"logger",
".",
"show_debug2",
":",
"self",
".",
"logger",
".",
"debug2",
"(",
"\"MEMORY: size (%s -> %s) | cost (%s -> %s)\"",
",",
"before_size",
",",
"after_size",
",",
"before_cost",
",",
"after_cost",
",",
")",
"if",
"size",
":",
"if",
"before_cost",
"<",
"after_cost",
":",
"gas_fee",
"=",
"after_cost",
"-",
"before_cost",
"self",
".",
"_gas_meter",
".",
"consume_gas",
"(",
"gas_fee",
",",
"reason",
"=",
"\" \"",
".",
"join",
"(",
"(",
"\"Expanding memory\"",
",",
"str",
"(",
"before_size",
")",
",",
"\"->\"",
",",
"str",
"(",
"after_size",
")",
",",
")",
")",
")",
"self",
".",
"_memory",
".",
"extend",
"(",
"start_position",
",",
"size",
")"
] | 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. | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L205-L242 |
230,151 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.memory_read | def memory_read(self, start_position: int, size: int) -> memoryview:
"""
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read(start_position, size) | python | def memory_read(self, start_position: int, size: int) -> memoryview:
"""
Read and return a view of ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read(start_position, size) | [
"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``. | [
"Read",
"and",
"return",
"a",
"view",
"of",
"size",
"bytes",
"from",
"memory",
"starting",
"at",
"start_position",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L250-L254 |
230,152 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.memory_read_bytes | def memory_read_bytes(self, start_position: int, size: int) -> bytes:
"""
Read and return ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read_bytes(start_position, size) | python | def memory_read_bytes(self, start_position: int, size: int) -> bytes:
"""
Read and return ``size`` bytes from memory starting at ``start_position``.
"""
return self._memory.read_bytes(start_position, size) | [
"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``. | [
"Read",
"and",
"return",
"size",
"bytes",
"from",
"memory",
"starting",
"at",
"start_position",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L256-L260 |
230,153 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.consume_gas | def consume_gas(self, amount: int, reason: str) -> None:
"""
Consume ``amount`` of gas from the remaining gas.
Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining.
"""
return self._gas_meter.consume_gas(amount, reason) | python | def consume_gas(self, amount: int, reason: str) -> None:
"""
Consume ``amount`` of gas from the remaining gas.
Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining.
"""
return self._gas_meter.consume_gas(amount, reason) | [
"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. | [
"Consume",
"amount",
"of",
"gas",
"from",
"the",
"remaining",
"gas",
".",
"Raise",
"eth",
".",
"exceptions",
".",
"OutOfGas",
"if",
"there",
"is",
"not",
"enough",
"gas",
"remaining",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L268-L273 |
230,154 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.stack_pop | def stack_pop(self, num_items: int=1, type_hint: str=None) -> Any:
# TODO: Needs to be replaced with
# `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly
"""
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``.
Raise `eth.exceptions.InsufficientStack` if there are not enough items on
the stack.
"""
return self._stack.pop(num_items, type_hint) | python | def stack_pop(self, num_items: int=1, type_hint: str=None) -> Any:
# TODO: Needs to be replaced with
# `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly
"""
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``.
Raise `eth.exceptions.InsufficientStack` if there are not enough items on
the stack.
"""
return self._stack.pop(num_items, type_hint) | [
"def",
"stack_pop",
"(",
"self",
",",
"num_items",
":",
"int",
"=",
"1",
",",
"type_hint",
":",
"str",
"=",
"None",
")",
"->",
"Any",
":",
"# TODO: Needs to be replaced with",
"# `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly",
"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``.
Raise `eth.exceptions.InsufficientStack` if there are not enough items on
the stack. | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L311-L323 |
230,155 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.stack_push | def stack_push(self, value: Union[int, bytes]) -> None:
"""
Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full.
"""
return self._stack.push(value) | python | def stack_push(self, value: Union[int, bytes]) -> None:
"""
Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full.
"""
return self._stack.push(value) | [
"def",
"stack_push",
"(",
"self",
",",
"value",
":",
"Union",
"[",
"int",
",",
"bytes",
"]",
")",
"->",
"None",
":",
"return",
"self",
".",
"_stack",
".",
"push",
"(",
"value",
")"
] | Push ``value`` onto the stack.
Raise `eth.exceptions.StackDepthLimit` if the stack is full. | [
"Push",
"value",
"onto",
"the",
"stack",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L325-L331 |
230,156 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.prepare_child_message | def prepare_child_message(self,
gas: int,
to: Address,
value: int,
data: BytesOrView,
code: bytes,
**kwargs: Any) -> Message:
"""
Helper method for creating a child computation.
"""
kwargs.setdefault('sender', self.msg.storage_address)
child_message = Message(
gas=gas,
to=to,
value=value,
data=data,
code=code,
depth=self.msg.depth + 1,
**kwargs
)
return child_message | python | def prepare_child_message(self,
gas: int,
to: Address,
value: int,
data: BytesOrView,
code: bytes,
**kwargs: Any) -> Message:
"""
Helper method for creating a child computation.
"""
kwargs.setdefault('sender', self.msg.storage_address)
child_message = Message(
gas=gas,
to=to,
value=value,
data=data,
code=code,
depth=self.msg.depth + 1,
**kwargs
)
return child_message | [
"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",
".",
"depth",
"+",
"1",
",",
"*",
"*",
"kwargs",
")",
"return",
"child_message"
] | Helper method for creating a child computation. | [
"Helper",
"method",
"for",
"creating",
"a",
"child",
"computation",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L369-L390 |
230,157 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.apply_child_computation | def apply_child_computation(self, child_msg: Message) -> 'BaseComputation':
"""
Apply the vm message ``child_msg`` as a child computation.
"""
child_computation = self.generate_child_computation(child_msg)
self.add_child_computation(child_computation)
return child_computation | python | def apply_child_computation(self, child_msg: Message) -> 'BaseComputation':
"""
Apply the vm message ``child_msg`` as a child computation.
"""
child_computation = self.generate_child_computation(child_msg)
self.add_child_computation(child_computation)
return child_computation | [
"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. | [
"Apply",
"the",
"vm",
"message",
"child_msg",
"as",
"a",
"child",
"computation",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L392-L398 |
230,158 | ethereum/py-evm | eth/vm/computation.py | BaseComputation._get_log_entries | def _get_log_entries(self) -> List[Tuple[int, bytes, List[int], bytes]]:
"""
Return the log entries for this computation and its children.
They are sorted in the same order they were emitted during the transaction processing, and
include the sequential counter as the first element of the tuple representing every entry.
"""
if self.is_error:
return []
else:
return sorted(itertools.chain(
self._log_entries,
*(child._get_log_entries() for child in self.children)
)) | python | def _get_log_entries(self) -> List[Tuple[int, bytes, List[int], bytes]]:
"""
Return the log entries for this computation and its children.
They are sorted in the same order they were emitted during the transaction processing, and
include the sequential counter as the first element of the tuple representing every entry.
"""
if self.is_error:
return []
else:
return sorted(itertools.chain(
self._log_entries,
*(child._get_log_entries() for child in self.children)
)) | [
"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.
They are sorted in the same order they were emitted during the transaction processing, and
include the sequential counter as the first element of the tuple representing every entry. | [
"Return",
"the",
"log",
"entries",
"for",
"this",
"computation",
"and",
"its",
"children",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L463-L476 |
230,159 | ethereum/py-evm | eth/vm/computation.py | BaseComputation.apply_computation | def apply_computation(cls,
state: BaseState,
message: Message,
transaction_context: BaseTransactionContext) -> 'BaseComputation':
"""
Perform the computation that would be triggered by the VM message.
"""
with cls(state, message, transaction_context) as computation:
# Early exit on pre-compiles
if message.code_address in computation.precompiles:
computation.precompiles[message.code_address](computation)
return computation
show_debug2 = computation.logger.show_debug2
for opcode in computation.code:
opcode_fn = computation.get_opcode_fn(opcode)
if show_debug2:
computation.logger.debug2(
"OPCODE: 0x%x (%s) | pc: %s",
opcode,
opcode_fn.mnemonic,
max(0, computation.code.pc - 1),
)
try:
opcode_fn(computation=computation)
except Halt:
break
return computation | python | def apply_computation(cls,
state: BaseState,
message: Message,
transaction_context: BaseTransactionContext) -> 'BaseComputation':
"""
Perform the computation that would be triggered by the VM message.
"""
with cls(state, message, transaction_context) as computation:
# Early exit on pre-compiles
if message.code_address in computation.precompiles:
computation.precompiles[message.code_address](computation)
return computation
show_debug2 = computation.logger.show_debug2
for opcode in computation.code:
opcode_fn = computation.get_opcode_fn(opcode)
if show_debug2:
computation.logger.debug2(
"OPCODE: 0x%x (%s) | pc: %s",
opcode,
opcode_fn.mnemonic,
max(0, computation.code.pc - 1),
)
try:
opcode_fn(computation=computation)
except Halt:
break
return computation | [
"def",
"apply_computation",
"(",
"cls",
",",
"state",
":",
"BaseState",
",",
"message",
":",
"Message",
",",
"transaction_context",
":",
"BaseTransactionContext",
")",
"->",
"'BaseComputation'",
":",
"with",
"cls",
"(",
"state",
",",
"message",
",",
"transaction_context",
")",
"as",
"computation",
":",
"# Early exit on pre-compiles",
"if",
"message",
".",
"code_address",
"in",
"computation",
".",
"precompiles",
":",
"computation",
".",
"precompiles",
"[",
"message",
".",
"code_address",
"]",
"(",
"computation",
")",
"return",
"computation",
"show_debug2",
"=",
"computation",
".",
"logger",
".",
"show_debug2",
"for",
"opcode",
"in",
"computation",
".",
"code",
":",
"opcode_fn",
"=",
"computation",
".",
"get_opcode_fn",
"(",
"opcode",
")",
"if",
"show_debug2",
":",
"computation",
".",
"logger",
".",
"debug2",
"(",
"\"OPCODE: 0x%x (%s) | pc: %s\"",
",",
"opcode",
",",
"opcode_fn",
".",
"mnemonic",
",",
"max",
"(",
"0",
",",
"computation",
".",
"code",
".",
"pc",
"-",
"1",
")",
",",
")",
"try",
":",
"opcode_fn",
"(",
"computation",
"=",
"computation",
")",
"except",
"Halt",
":",
"break",
"return",
"computation"
] | Perform the computation that would be triggered by the VM message. | [
"Perform",
"the",
"computation",
"that",
"would",
"be",
"triggered",
"by",
"the",
"VM",
"message",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/computation.py#L562-L592 |
230,160 | ethereum/py-evm | eth/vm/forks/homestead/headers.py | compute_homestead_difficulty | def compute_homestead_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a homestead block based on the parent block.
"""
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_tstamp) // HOMESTEAD_DIFFICULTY_ADJUSTMENT_CUTOFF,
-99)
difficulty = int(max(
parent_header.difficulty + offset * sign,
min(parent_header.difficulty, DIFFICULTY_MINIMUM)))
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
return max(difficulty + 2**num_bomb_periods, DIFFICULTY_MINIMUM)
else:
return difficulty | python | def compute_homestead_difficulty(parent_header: BlockHeader, timestamp: int) -> int:
"""
Computes the difficulty for a homestead block based on the parent block.
"""
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_tstamp) // HOMESTEAD_DIFFICULTY_ADJUSTMENT_CUTOFF,
-99)
difficulty = int(max(
parent_header.difficulty + offset * sign,
min(parent_header.difficulty, DIFFICULTY_MINIMUM)))
num_bomb_periods = (
(parent_header.block_number + 1) // BOMB_EXPONENTIAL_PERIOD
) - BOMB_EXPONENTIAL_FREE_PERIODS
if num_bomb_periods >= 0:
return max(difficulty + 2**num_bomb_periods, DIFFICULTY_MINIMUM)
else:
return difficulty | [
"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_tstamp",
")",
"//",
"HOMESTEAD_DIFFICULTY_ADJUSTMENT_CUTOFF",
",",
"-",
"99",
")",
"difficulty",
"=",
"int",
"(",
"max",
"(",
"parent_header",
".",
"difficulty",
"+",
"offset",
"*",
"sign",
",",
"min",
"(",
"parent_header",
".",
"difficulty",
",",
"DIFFICULTY_MINIMUM",
")",
")",
")",
"num_bomb_periods",
"=",
"(",
"(",
"parent_header",
".",
"block_number",
"+",
"1",
")",
"//",
"BOMB_EXPONENTIAL_PERIOD",
")",
"-",
"BOMB_EXPONENTIAL_FREE_PERIODS",
"if",
"num_bomb_periods",
">=",
"0",
":",
"return",
"max",
"(",
"difficulty",
"+",
"2",
"**",
"num_bomb_periods",
",",
"DIFFICULTY_MINIMUM",
")",
"else",
":",
"return",
"difficulty"
] | Computes the difficulty for a homestead block based on the parent block. | [
"Computes",
"the",
"difficulty",
"for",
"a",
"homestead",
"block",
"based",
"on",
"the",
"parent",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/forks/homestead/headers.py#L39-L58 |
230,161 | ethereum/py-evm | eth/vm/state.py | BaseState.snapshot | def snapshot(self) -> Tuple[Hash32, UUID]:
"""
Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB.
"""
return self.state_root, self._account_db.record() | python | def snapshot(self) -> Tuple[Hash32, UUID]:
"""
Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB.
"""
return self.state_root, self._account_db.record() | [
"def",
"snapshot",
"(",
"self",
")",
"->",
"Tuple",
"[",
"Hash32",
",",
"UUID",
"]",
":",
"return",
"self",
".",
"state_root",
",",
"self",
".",
"_account_db",
".",
"record",
"(",
")"
] | Perform a full snapshot of the current state.
Snapshots are a combination of the :attr:`~state_root` at the time of the
snapshot and the id of the changeset from the journaled DB. | [
"Perform",
"a",
"full",
"snapshot",
"of",
"the",
"current",
"state",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L225-L232 |
230,162 | ethereum/py-evm | eth/vm/state.py | BaseState.revert | def revert(self, snapshot: Tuple[Hash32, UUID]) -> None:
"""
Revert the VM to the state at the snapshot
"""
state_root, account_snapshot = snapshot
# first revert the database state root.
self._account_db.state_root = state_root
# now roll the underlying database back
self._account_db.discard(account_snapshot) | python | def revert(self, snapshot: Tuple[Hash32, UUID]) -> None:
"""
Revert the VM to the state at the snapshot
"""
state_root, account_snapshot = snapshot
# first revert the database state root.
self._account_db.state_root = state_root
# now roll the underlying database back
self._account_db.discard(account_snapshot) | [
"def",
"revert",
"(",
"self",
",",
"snapshot",
":",
"Tuple",
"[",
"Hash32",
",",
"UUID",
"]",
")",
"->",
"None",
":",
"state_root",
",",
"account_snapshot",
"=",
"snapshot",
"# first revert the database state root.",
"self",
".",
"_account_db",
".",
"state_root",
"=",
"state_root",
"# now roll the underlying database back",
"self",
".",
"_account_db",
".",
"discard",
"(",
"account_snapshot",
")"
] | Revert the VM to the state at the snapshot | [
"Revert",
"the",
"VM",
"to",
"the",
"state",
"at",
"the",
"snapshot"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L234-L243 |
230,163 | ethereum/py-evm | eth/vm/state.py | BaseState.get_computation | def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
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_context)
return computation | python | def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
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_context)
return computation | [
"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_context",
")",
"return",
"computation"
] | Return a computation instance for the given `message` and `transaction_context` | [
"Return",
"a",
"computation",
"instance",
"for",
"the",
"given",
"message",
"and",
"transaction_context"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L283-L293 |
230,164 | ethereum/py-evm | eth/vm/state.py | BaseState.apply_transaction | def apply_transaction(
self,
transaction: BaseOrSpoofTransaction) -> 'BaseComputation':
"""
Apply transaction to the vm state
:param transaction: the transaction to apply
:return: the computation
"""
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) | python | def apply_transaction(
self,
transaction: BaseOrSpoofTransaction) -> 'BaseComputation':
"""
Apply transaction to the vm state
:param transaction: the transaction to apply
:return: the computation
"""
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) | [
"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
:param transaction: the transaction to apply
:return: the computation | [
"Apply",
"transaction",
"to",
"the",
"vm",
"state"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/state.py#L311-L323 |
230,165 | ethereum/py-evm | eth/_utils/env.py | get_env_value | def get_env_value(name: str, required: bool=False, default: Any=empty) -> str:
"""
Core function for extracting the environment variable.
Enforces mutual exclusivity between `required` and `default` keywords.
The `empty` sentinal value is used as the default `default` value to allow
other function to handle default/empty logic in the appropriate way.
"""
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 {0}".format(name)
)
else:
value = os.environ.get(name, default)
return value | python | def get_env_value(name: str, required: bool=False, default: Any=empty) -> str:
"""
Core function for extracting the environment variable.
Enforces mutual exclusivity between `required` and `default` keywords.
The `empty` sentinal value is used as the default `default` value to allow
other function to handle default/empty logic in the appropriate way.
"""
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 {0}".format(name)
)
else:
value = os.environ.get(name, default)
return value | [
"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 {0}\"",
".",
"format",
"(",
"name",
")",
")",
"else",
":",
"value",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"default",
")",
"return",
"value"
] | Core function for extracting the environment variable.
Enforces mutual exclusivity between `required` and `default` keywords.
The `empty` sentinal value is used as the default `default` value to allow
other function to handle default/empty logic in the appropriate way. | [
"Core",
"function",
"for",
"extracting",
"the",
"environment",
"variable",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/_utils/env.py#L36-L56 |
230,166 | ethereum/py-evm | eth/vm/base.py | BaseVM.make_receipt | def make_receipt(self,
base_header: BlockHeader,
transaction: BaseTransaction,
computation: BaseComputation,
state: BaseState) -> Receipt:
"""
Generate the receipt resulting from applying the transaction.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation: the result of running the transaction computation
:param state: the resulting state, after executing the computation
:return: receipt
"""
raise NotImplementedError("VM classes must implement this method") | python | def make_receipt(self,
base_header: BlockHeader,
transaction: BaseTransaction,
computation: BaseComputation,
state: BaseState) -> Receipt:
"""
Generate the receipt resulting from applying the transaction.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation: the result of running the transaction computation
:param state: the resulting state, after executing the computation
:return: receipt
"""
raise NotImplementedError("VM classes must implement this method") | [
"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.
:param base_header: the header of the block before the transaction was applied.
:param transaction: the transaction used to generate the receipt
:param computation: the result of running the transaction computation
:param state: the resulting state, after executing the computation
:return: receipt | [
"Generate",
"the",
"receipt",
"resulting",
"from",
"applying",
"the",
"transaction",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L155-L170 |
230,167 | ethereum/py-evm | eth/vm/base.py | VM.execute_bytecode | 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:
"""
Execute raw bytecode in the context of the current state of
the virtual machine.
"""
if origin is None:
origin = sender
# Construct a message
message = Message(
gas=gas,
to=to,
sender=sender,
value=value,
data=data,
code=code,
code_address=code_address,
)
# Construction a tx context
transaction_context = self.state.get_transaction_context_class()(
gas_price=gas_price,
origin=origin,
)
# Execute it in the VM
return self.state.get_computation(message, transaction_context).apply_computation(
self.state,
message,
transaction_context,
) | python | 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:
"""
Execute raw bytecode in the context of the current state of
the virtual machine.
"""
if origin is None:
origin = sender
# Construct a message
message = Message(
gas=gas,
to=to,
sender=sender,
value=value,
data=data,
code=code,
code_address=code_address,
)
# Construction a tx context
transaction_context = self.state.get_transaction_context_class()(
gas_price=gas_price,
origin=origin,
)
# Execute it in the VM
return self.state.get_computation(message, transaction_context).apply_computation(
self.state,
message,
transaction_context,
) | [
"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",
"# Construct a message",
"message",
"=",
"Message",
"(",
"gas",
"=",
"gas",
",",
"to",
"=",
"to",
",",
"sender",
"=",
"sender",
",",
"value",
"=",
"value",
",",
"data",
"=",
"data",
",",
"code",
"=",
"code",
",",
"code_address",
"=",
"code_address",
",",
")",
"# Construction a tx context",
"transaction_context",
"=",
"self",
".",
"state",
".",
"get_transaction_context_class",
"(",
")",
"(",
"gas_price",
"=",
"gas_price",
",",
"origin",
"=",
"origin",
",",
")",
"# Execute it in the VM",
"return",
"self",
".",
"state",
".",
"get_computation",
"(",
"message",
",",
"transaction_context",
")",
".",
"apply_computation",
"(",
"self",
".",
"state",
",",
"message",
",",
"transaction_context",
",",
")"
] | Execute raw bytecode in the context of the current state of
the virtual machine. | [
"Execute",
"raw",
"bytecode",
"in",
"the",
"context",
"of",
"the",
"current",
"state",
"of",
"the",
"virtual",
"machine",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L470-L510 |
230,168 | ethereum/py-evm | eth/vm/base.py | VM.import_block | def import_block(self, block: BaseBlock) -> BaseBlock:
"""
Import the given block to the chain.
"""
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.configure_header(
coinbase=block.header.coinbase,
gas_limit=block.header.gas_limit,
timestamp=block.header.timestamp,
extra_data=block.header.extra_data,
mix_hash=block.header.mix_hash,
nonce=block.header.nonce,
uncles_hash=keccak(rlp.encode(block.uncles)),
),
uncles=block.uncles,
)
# we need to re-initialize the `state` to update the execution context.
self._state = self.build_state(self.chaindb.db, self.header, self.previous_hashes)
# run all of the transactions.
new_header, receipts, _ = self.apply_all_transactions(block.transactions, self.header)
self.block = self.set_block_transactions(
self.block,
new_header,
block.transactions,
receipts,
)
return self.mine_block() | python | def import_block(self, block: BaseBlock) -> BaseBlock:
"""
Import the given block to the chain.
"""
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.configure_header(
coinbase=block.header.coinbase,
gas_limit=block.header.gas_limit,
timestamp=block.header.timestamp,
extra_data=block.header.extra_data,
mix_hash=block.header.mix_hash,
nonce=block.header.nonce,
uncles_hash=keccak(rlp.encode(block.uncles)),
),
uncles=block.uncles,
)
# we need to re-initialize the `state` to update the execution context.
self._state = self.build_state(self.chaindb.db, self.header, self.previous_hashes)
# run all of the transactions.
new_header, receipts, _ = self.apply_all_transactions(block.transactions, self.header)
self.block = self.set_block_transactions(
self.block,
new_header,
block.transactions,
receipts,
)
return self.mine_block() | [
"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",
".",
"configure_header",
"(",
"coinbase",
"=",
"block",
".",
"header",
".",
"coinbase",
",",
"gas_limit",
"=",
"block",
".",
"header",
".",
"gas_limit",
",",
"timestamp",
"=",
"block",
".",
"header",
".",
"timestamp",
",",
"extra_data",
"=",
"block",
".",
"header",
".",
"extra_data",
",",
"mix_hash",
"=",
"block",
".",
"header",
".",
"mix_hash",
",",
"nonce",
"=",
"block",
".",
"header",
".",
"nonce",
",",
"uncles_hash",
"=",
"keccak",
"(",
"rlp",
".",
"encode",
"(",
"block",
".",
"uncles",
")",
")",
",",
")",
",",
"uncles",
"=",
"block",
".",
"uncles",
",",
")",
"# we need to re-initialize the `state` to update the execution context.",
"self",
".",
"_state",
"=",
"self",
".",
"build_state",
"(",
"self",
".",
"chaindb",
".",
"db",
",",
"self",
".",
"header",
",",
"self",
".",
"previous_hashes",
")",
"# run all of the transactions.",
"new_header",
",",
"receipts",
",",
"_",
"=",
"self",
".",
"apply_all_transactions",
"(",
"block",
".",
"transactions",
",",
"self",
".",
"header",
")",
"self",
".",
"block",
"=",
"self",
".",
"set_block_transactions",
"(",
"self",
".",
"block",
",",
"new_header",
",",
"block",
".",
"transactions",
",",
"receipts",
",",
")",
"return",
"self",
".",
"mine_block",
"(",
")"
] | Import the given block to the chain. | [
"Import",
"the",
"given",
"block",
"to",
"the",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L557-L594 |
230,169 | ethereum/py-evm | eth/vm/base.py | VM.mine_block | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Mine the current block. Proxies to self.pack_block method.
"""
packed_block = self.pack_block(self.block, *args, **kwargs)
final_block = self.finalize_block(packed_block)
# Perform validation
self.validate_block(final_block)
return final_block | python | def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Mine the current block. Proxies to self.pack_block method.
"""
packed_block = self.pack_block(self.block, *args, **kwargs)
final_block = self.finalize_block(packed_block)
# Perform validation
self.validate_block(final_block)
return final_block | [
"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",
")",
"# Perform validation",
"self",
".",
"validate_block",
"(",
"final_block",
")",
"return",
"final_block"
] | Mine the current block. Proxies to self.pack_block method. | [
"Mine",
"the",
"current",
"block",
".",
"Proxies",
"to",
"self",
".",
"pack_block",
"method",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L596-L607 |
230,170 | ethereum/py-evm | eth/vm/base.py | VM.finalize_block | def finalize_block(self, block: BaseBlock) -> BaseBlock:
"""
Perform any finalization steps like awarding the block mining reward,
and persisting the final state root.
"""
if block.number > 0:
self._assign_block_rewards(block)
# We need to call `persist` here since the state db batches
# all writes until we tell it to write to the underlying db
self.state.persist()
return block.copy(header=block.header.copy(state_root=self.state.state_root)) | python | def finalize_block(self, block: BaseBlock) -> BaseBlock:
"""
Perform any finalization steps like awarding the block mining reward,
and persisting the final state root.
"""
if block.number > 0:
self._assign_block_rewards(block)
# We need to call `persist` here since the state db batches
# all writes until we tell it to write to the underlying db
self.state.persist()
return block.copy(header=block.header.copy(state_root=self.state.state_root)) | [
"def",
"finalize_block",
"(",
"self",
",",
"block",
":",
"BaseBlock",
")",
"->",
"BaseBlock",
":",
"if",
"block",
".",
"number",
">",
"0",
":",
"self",
".",
"_assign_block_rewards",
"(",
"block",
")",
"# We need to call `persist` here since the state db batches",
"# all writes until we tell it to write to the underlying db",
"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. | [
"Perform",
"any",
"finalization",
"steps",
"like",
"awarding",
"the",
"block",
"mining",
"reward",
"and",
"persisting",
"the",
"final",
"state",
"root",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L653-L665 |
230,171 | ethereum/py-evm | eth/vm/base.py | VM.pack_block | def pack_block(self, block: BaseBlock, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_root: 32 bytes
:param bytes receipt_root: 32 bytes
:param int bloom:
:param int gas_used:
:param bytes extra_data: 32 bytes
:param bytes mix_hash: 32 bytes
:param bytes nonce: 8 bytes
"""
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(BlockHeader._meta.field_names)
unknown_fields = provided_fields.difference(known_fields)
if unknown_fields:
raise AttributeError(
"Unable to set the field(s) {0} on the `BlockHeader` class. "
"Received the following unexpected fields: {1}.".format(
", ".join(known_fields),
", ".join(unknown_fields),
)
)
header = block.header.copy(**kwargs)
packed_block = block.copy(uncles=uncles, header=header)
return packed_block | python | def pack_block(self, block: BaseBlock, *args: Any, **kwargs: Any) -> BaseBlock:
"""
Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_root: 32 bytes
:param bytes receipt_root: 32 bytes
:param int bloom:
:param int gas_used:
:param bytes extra_data: 32 bytes
:param bytes mix_hash: 32 bytes
:param bytes nonce: 8 bytes
"""
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(BlockHeader._meta.field_names)
unknown_fields = provided_fields.difference(known_fields)
if unknown_fields:
raise AttributeError(
"Unable to set the field(s) {0} on the `BlockHeader` class. "
"Received the following unexpected fields: {1}.".format(
", ".join(known_fields),
", ".join(unknown_fields),
)
)
header = block.header.copy(**kwargs)
packed_block = block.copy(uncles=uncles, header=header)
return packed_block | [
"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",
"(",
"BlockHeader",
".",
"_meta",
".",
"field_names",
")",
"unknown_fields",
"=",
"provided_fields",
".",
"difference",
"(",
"known_fields",
")",
"if",
"unknown_fields",
":",
"raise",
"AttributeError",
"(",
"\"Unable to set the field(s) {0} on the `BlockHeader` class. \"",
"\"Received the following unexpected fields: {1}.\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"known_fields",
")",
",",
"\", \"",
".",
"join",
"(",
"unknown_fields",
")",
",",
")",
")",
"header",
"=",
"block",
".",
"header",
".",
"copy",
"(",
"*",
"*",
"kwargs",
")",
"packed_block",
"=",
"block",
".",
"copy",
"(",
"uncles",
"=",
"uncles",
",",
"header",
"=",
"header",
")",
"return",
"packed_block"
] | Pack block for mining.
:param bytes coinbase: 20-byte public address to receive block reward
:param bytes uncles_hash: 32 bytes
:param bytes state_root: 32 bytes
:param bytes transaction_root: 32 bytes
:param bytes receipt_root: 32 bytes
:param int bloom:
:param int gas_used:
:param bytes extra_data: 32 bytes
:param bytes mix_hash: 32 bytes
:param bytes nonce: 8 bytes | [
"Pack",
"block",
"for",
"mining",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L667-L704 |
230,172 | ethereum/py-evm | eth/vm/base.py | VM.generate_block_from_parent_header_and_coinbase | def generate_block_from_parent_header_and_coinbase(cls,
parent_header: BlockHeader,
coinbase: Address) -> BaseBlock:
"""
Generate block from parent header and coinbase.
"""
block_header = generate_header_from_parent_header(
cls.compute_difficulty,
parent_header,
coinbase,
timestamp=parent_header.timestamp + 1,
)
block = cls.get_block_class()(
block_header,
transactions=[],
uncles=[],
)
return block | python | def generate_block_from_parent_header_and_coinbase(cls,
parent_header: BlockHeader,
coinbase: Address) -> BaseBlock:
"""
Generate block from parent header and coinbase.
"""
block_header = generate_header_from_parent_header(
cls.compute_difficulty,
parent_header,
coinbase,
timestamp=parent_header.timestamp + 1,
)
block = cls.get_block_class()(
block_header,
transactions=[],
uncles=[],
)
return block | [
"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_header",
",",
"transactions",
"=",
"[",
"]",
",",
"uncles",
"=",
"[",
"]",
",",
")",
"return",
"block"
] | Generate block from parent header and coinbase. | [
"Generate",
"block",
"from",
"parent",
"header",
"and",
"coinbase",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L710-L727 |
230,173 | ethereum/py-evm | eth/vm/base.py | VM.previous_hashes | def previous_hashes(self) -> Optional[Iterable[Hash32]]:
"""
Convenience API for accessing the previous 255 block hashes.
"""
return self.get_prev_hashes(self.header.parent_hash, self.chaindb) | python | def previous_hashes(self) -> Optional[Iterable[Hash32]]:
"""
Convenience API for accessing the previous 255 block hashes.
"""
return self.get_prev_hashes(self.header.parent_hash, self.chaindb) | [
"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. | [
"Convenience",
"API",
"for",
"accessing",
"the",
"previous",
"255",
"block",
"hashes",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L756-L760 |
230,174 | ethereum/py-evm | eth/vm/base.py | VM.create_transaction | def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Proxy for instantiating a signed transaction for this VM.
"""
return self.get_transaction_class()(*args, **kwargs) | python | def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Proxy for instantiating a signed transaction for this VM.
"""
return self.get_transaction_class()(*args, **kwargs) | [
"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. | [
"Proxy",
"for",
"instantiating",
"a",
"signed",
"transaction",
"for",
"this",
"VM",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L765-L769 |
230,175 | ethereum/py-evm | eth/vm/base.py | VM.create_unsigned_transaction | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Proxy for instantiating an unsigned transaction for this VM.
"""
return cls.get_transaction_class().create_unsigned_transaction(
nonce=nonce,
gas_price=gas_price,
gas=gas,
to=to,
value=value,
data=data
) | python | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> 'BaseUnsignedTransaction':
"""
Proxy for instantiating an unsigned transaction for this VM.
"""
return cls.get_transaction_class().create_unsigned_transaction(
nonce=nonce,
gas_price=gas_price,
gas=gas,
to=to,
value=value,
data=data
) | [
"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",
"=",
"data",
")"
] | Proxy for instantiating an unsigned transaction for this VM. | [
"Proxy",
"for",
"instantiating",
"an",
"unsigned",
"transaction",
"for",
"this",
"VM",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L772-L790 |
230,176 | ethereum/py-evm | eth/vm/base.py | VM.validate_block | def validate_block(self, block: BaseBlock) -> None:
"""
Validate the the given block.
"""
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, title="BlockHeader.extra_data")
else:
parent_header = get_parent_header(block.header, self.chaindb)
self.validate_header(block.header, parent_header)
tx_root_hash, _ = make_trie_root_and_nodes(block.transactions)
if tx_root_hash != block.header.transaction_root:
raise ValidationError(
"Block's transaction_root ({0}) does not match expected value: {1}".format(
block.header.transaction_root, tx_root_hash))
if len(block.uncles) > MAX_UNCLES:
raise ValidationError(
"Blocks may have a maximum of {0} uncles. Found "
"{1}.".format(MAX_UNCLES, len(block.uncles))
)
if not self.chaindb.exists(block.header.state_root):
raise ValidationError(
"`state_root` was not found in the db.\n"
"- state_root: {0}".format(
block.header.state_root,
)
)
local_uncle_hash = keccak(rlp.encode(block.uncles))
if local_uncle_hash != block.header.uncles_hash:
raise ValidationError(
"`uncles_hash` and block `uncles` do not match.\n"
" - num_uncles : {0}\n"
" - block uncle_hash : {1}\n"
" - header uncle_hash: {2}".format(
len(block.uncles),
local_uncle_hash,
block.header.uncles_hash,
)
) | python | def validate_block(self, block: BaseBlock) -> None:
"""
Validate the the given block.
"""
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, title="BlockHeader.extra_data")
else:
parent_header = get_parent_header(block.header, self.chaindb)
self.validate_header(block.header, parent_header)
tx_root_hash, _ = make_trie_root_and_nodes(block.transactions)
if tx_root_hash != block.header.transaction_root:
raise ValidationError(
"Block's transaction_root ({0}) does not match expected value: {1}".format(
block.header.transaction_root, tx_root_hash))
if len(block.uncles) > MAX_UNCLES:
raise ValidationError(
"Blocks may have a maximum of {0} uncles. Found "
"{1}.".format(MAX_UNCLES, len(block.uncles))
)
if not self.chaindb.exists(block.header.state_root):
raise ValidationError(
"`state_root` was not found in the db.\n"
"- state_root: {0}".format(
block.header.state_root,
)
)
local_uncle_hash = keccak(rlp.encode(block.uncles))
if local_uncle_hash != block.header.uncles_hash:
raise ValidationError(
"`uncles_hash` and block `uncles` do not match.\n"
" - num_uncles : {0}\n"
" - block uncle_hash : {1}\n"
" - header uncle_hash: {2}".format(
len(block.uncles),
local_uncle_hash,
block.header.uncles_hash,
)
) | [
"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",
",",
"title",
"=",
"\"BlockHeader.extra_data\"",
")",
"else",
":",
"parent_header",
"=",
"get_parent_header",
"(",
"block",
".",
"header",
",",
"self",
".",
"chaindb",
")",
"self",
".",
"validate_header",
"(",
"block",
".",
"header",
",",
"parent_header",
")",
"tx_root_hash",
",",
"_",
"=",
"make_trie_root_and_nodes",
"(",
"block",
".",
"transactions",
")",
"if",
"tx_root_hash",
"!=",
"block",
".",
"header",
".",
"transaction_root",
":",
"raise",
"ValidationError",
"(",
"\"Block's transaction_root ({0}) does not match expected value: {1}\"",
".",
"format",
"(",
"block",
".",
"header",
".",
"transaction_root",
",",
"tx_root_hash",
")",
")",
"if",
"len",
"(",
"block",
".",
"uncles",
")",
">",
"MAX_UNCLES",
":",
"raise",
"ValidationError",
"(",
"\"Blocks may have a maximum of {0} uncles. Found \"",
"\"{1}.\"",
".",
"format",
"(",
"MAX_UNCLES",
",",
"len",
"(",
"block",
".",
"uncles",
")",
")",
")",
"if",
"not",
"self",
".",
"chaindb",
".",
"exists",
"(",
"block",
".",
"header",
".",
"state_root",
")",
":",
"raise",
"ValidationError",
"(",
"\"`state_root` was not found in the db.\\n\"",
"\"- state_root: {0}\"",
".",
"format",
"(",
"block",
".",
"header",
".",
"state_root",
",",
")",
")",
"local_uncle_hash",
"=",
"keccak",
"(",
"rlp",
".",
"encode",
"(",
"block",
".",
"uncles",
")",
")",
"if",
"local_uncle_hash",
"!=",
"block",
".",
"header",
".",
"uncles_hash",
":",
"raise",
"ValidationError",
"(",
"\"`uncles_hash` and block `uncles` do not match.\\n\"",
"\" - num_uncles : {0}\\n\"",
"\" - block uncle_hash : {1}\\n\"",
"\" - header uncle_hash: {2}\"",
".",
"format",
"(",
"len",
"(",
"block",
".",
"uncles",
")",
",",
"local_uncle_hash",
",",
"block",
".",
"header",
".",
"uncles_hash",
",",
")",
")"
] | Validate the the given block. | [
"Validate",
"the",
"the",
"given",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L828-L876 |
230,177 | ethereum/py-evm | eth/vm/base.py | VM.validate_uncle | def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None:
"""
Validate the given uncle in the context of the given block.
"""
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.block_number + 1:
raise ValidationError(
"Uncle number ({0}) is not one above ancestor's number ({1})".format(
uncle.block_number, uncle_parent.block_number))
if uncle.timestamp < uncle_parent.timestamp:
raise ValidationError(
"Uncle timestamp ({0}) is before ancestor's timestamp ({1})".format(
uncle.timestamp, uncle_parent.timestamp))
if uncle.gas_used > uncle.gas_limit:
raise ValidationError(
"Uncle's gas usage ({0}) is above the limit ({1})".format(
uncle.gas_used, uncle.gas_limit)) | python | def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None:
"""
Validate the given uncle in the context of the given block.
"""
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.block_number + 1:
raise ValidationError(
"Uncle number ({0}) is not one above ancestor's number ({1})".format(
uncle.block_number, uncle_parent.block_number))
if uncle.timestamp < uncle_parent.timestamp:
raise ValidationError(
"Uncle timestamp ({0}) is before ancestor's timestamp ({1})".format(
uncle.timestamp, uncle_parent.timestamp))
if uncle.gas_used > uncle.gas_limit:
raise ValidationError(
"Uncle's gas usage ({0}) is above the limit ({1})".format(
uncle.gas_used, uncle.gas_limit)) | [
"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",
".",
"block_number",
"+",
"1",
":",
"raise",
"ValidationError",
"(",
"\"Uncle number ({0}) is not one above ancestor's number ({1})\"",
".",
"format",
"(",
"uncle",
".",
"block_number",
",",
"uncle_parent",
".",
"block_number",
")",
")",
"if",
"uncle",
".",
"timestamp",
"<",
"uncle_parent",
".",
"timestamp",
":",
"raise",
"ValidationError",
"(",
"\"Uncle timestamp ({0}) is before ancestor's timestamp ({1})\"",
".",
"format",
"(",
"uncle",
".",
"timestamp",
",",
"uncle_parent",
".",
"timestamp",
")",
")",
"if",
"uncle",
".",
"gas_used",
">",
"uncle",
".",
"gas_limit",
":",
"raise",
"ValidationError",
"(",
"\"Uncle's gas usage ({0}) is above the limit ({1})\"",
".",
"format",
"(",
"uncle",
".",
"gas_used",
",",
"uncle",
".",
"gas_limit",
")",
")"
] | Validate the given uncle in the context of the given block. | [
"Validate",
"the",
"given",
"uncle",
"in",
"the",
"context",
"of",
"the",
"given",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/vm/base.py#L927-L947 |
230,178 | ethereum/py-evm | eth/tools/_utils/mappings.py | is_cleanly_mergable | def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
False
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"c": 3, {"b": {"bb": 4}})
True
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"b": {"ba": 4}})
False
"""
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(dicts[0][key], dicts[1][key]) for key in shared_keys)
else:
dict_combinations = itertools.combinations(dicts, 2)
return all(is_cleanly_mergable(*combination) for combination in dict_combinations) | python | def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool:
"""Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
False
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"c": 3, {"b": {"bb": 4}})
True
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"b": {"ba": 4}})
False
"""
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(dicts[0][key], dicts[1][key]) for key in shared_keys)
else:
dict_combinations = itertools.combinations(dicts, 2)
return all(is_cleanly_mergable(*combination) for combination in dict_combinations) | [
"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",
"(",
"dicts",
"[",
"0",
"]",
"[",
"key",
"]",
",",
"dicts",
"[",
"1",
"]",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"shared_keys",
")",
"else",
":",
"dict_combinations",
"=",
"itertools",
".",
"combinations",
"(",
"dicts",
",",
"2",
")",
"return",
"all",
"(",
"is_cleanly_mergable",
"(",
"*",
"combination",
")",
"for",
"combination",
"in",
"dict_combinations",
")"
] | Check that nothing will be overwritten when dictionaries are merged using `deep_merge`.
Examples:
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3})
True
>>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"a": 0, c": 3})
False
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"c": 3, {"b": {"bb": 4}})
True
>>> is_cleanly_mergable({"a": 1, "b": {"ba": 2}}, {"b": {"ba": 4}})
False | [
"Check",
"that",
"nothing",
"will",
"be",
"overwritten",
"when",
"dictionaries",
"are",
"merged",
"using",
"deep_merge",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/mappings.py#L24-L49 |
230,179 | ethereum/py-evm | eth/db/diff.py | DBDiff.deleted_keys | def deleted_keys(self) -> Iterable[bytes]:
"""
List all the keys that have been deleted.
"""
for key, value in self._changes.items():
if value is DELETED:
yield key | python | def deleted_keys(self) -> Iterable[bytes]:
"""
List all the keys that have been deleted.
"""
for key, value in self._changes.items():
if value is DELETED:
yield key | [
"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. | [
"List",
"all",
"the",
"keys",
"that",
"have",
"been",
"deleted",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/diff.py#L160-L166 |
230,180 | ethereum/py-evm | eth/db/diff.py | DBDiff.apply_to | def apply_to(self,
db: Union[BaseDB, ABC_Mutable_Mapping],
apply_deletes: bool = True) -> None:
"""
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pending deletes should be
applied to the database
"""
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 | python | def apply_to(self,
db: Union[BaseDB, ABC_Mutable_Mapping],
apply_deletes: bool = True) -> None:
"""
Apply the changes in this diff to the given database.
You may choose to opt out of deleting any underlying keys.
:param apply_deletes: whether the pending deletes should be
applied to the database
"""
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 | [
"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.
:param apply_deletes: whether the pending deletes should be
applied to the database | [
"Apply",
"the",
"changes",
"in",
"this",
"diff",
"to",
"the",
"given",
"database",
".",
"You",
"may",
"choose",
"to",
"opt",
"out",
"of",
"deleting",
"any",
"underlying",
"keys",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/diff.py#L188-L208 |
230,181 | ethereum/py-evm | eth/db/diff.py | DBDiff.join | def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
"""
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes.
"""
tracker = DBDiffTracker()
for diff in diffs:
diff.apply_to(tracker)
return tracker.diff() | python | def join(cls, diffs: Iterable['DBDiff']) -> 'DBDiff':
"""
Join several DBDiff objects into a single DBDiff object.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes.
"""
tracker = DBDiffTracker()
for diff in diffs:
diff.apply_to(tracker)
return tracker.diff() | [
"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.
In case of a conflict, changes in diffs that come later
in ``diffs`` will overwrite changes from earlier changes. | [
"Join",
"several",
"DBDiff",
"objects",
"into",
"a",
"single",
"DBDiff",
"object",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/diff.py#L211-L221 |
230,182 | ethereum/py-evm | eth/tools/_utils/hashing.py | hash_log_entries | def hash_log_entries(log_entries: Iterable[Tuple[bytes, List[int], bytes]]) -> Hash32:
"""
Helper function for computing the RLP hash of the logs from transaction
execution.
"""
logs = [Log(*entry) for entry in log_entries]
encoded_logs = rlp.encode(logs)
logs_hash = keccak(encoded_logs)
return logs_hash | python | def hash_log_entries(log_entries: Iterable[Tuple[bytes, List[int], bytes]]) -> Hash32:
"""
Helper function for computing the RLP hash of the logs from transaction
execution.
"""
logs = [Log(*entry) for entry in log_entries]
encoded_logs = rlp.encode(logs)
logs_hash = keccak(encoded_logs)
return logs_hash | [
"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. | [
"Helper",
"function",
"for",
"computing",
"the",
"RLP",
"hash",
"of",
"the",
"logs",
"from",
"transaction",
"execution",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/_utils/hashing.py#L18-L26 |
230,183 | ethereum/py-evm | eth/chains/base.py | BaseChain.get_vm_class_for_block_number | def get_vm_class_for_block_number(cls, block_number: BlockNumber) -> Type['BaseVM']:
"""
Returns the VM class for the given block number.
"""
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 block_number >= start_block:
return vm_class
else:
raise VMNotFound("No vm available for block #{0}".format(block_number)) | python | def get_vm_class_for_block_number(cls, block_number: BlockNumber) -> Type['BaseVM']:
"""
Returns the VM class for the given block number.
"""
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 block_number >= start_block:
return vm_class
else:
raise VMNotFound("No vm available for block #{0}".format(block_number)) | [
"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",
"block_number",
">=",
"start_block",
":",
"return",
"vm_class",
"else",
":",
"raise",
"VMNotFound",
"(",
"\"No vm available for block #{0}\"",
".",
"format",
"(",
"block_number",
")",
")"
] | Returns the VM class for the given block number. | [
"Returns",
"the",
"VM",
"class",
"for",
"the",
"given",
"block",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L182-L194 |
230,184 | ethereum/py-evm | eth/chains/base.py | BaseChain.validate_chain | def validate_chain(
cls,
root: BlockHeader,
descendants: Tuple[BlockHeader, ...],
seal_check_random_sample_rate: int = 1) -> None:
"""
Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal validity (Proof-of-Work on Ethereum 1.x mainnet) of all headers.
This can be expensive. Instead, check a random sample of seals using
seal_check_random_sample_rate.
"""
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_check_random_sample_rate
indices_to_check_seal = set(random.sample(all_indices, sample_size))
header_pairs = sliding_window(2, concatv([root], descendants))
for index, (parent, child) in enumerate(header_pairs):
if child.parent_hash != parent.hash:
raise ValidationError(
"Invalid header chain; {} has parent {}, but expected {}".format(
child, child.parent_hash, parent.hash))
should_check_seal = index in indices_to_check_seal
vm_class = cls.get_vm_class_for_block_number(child.block_number)
try:
vm_class.validate_header(child, parent, check_seal=should_check_seal)
except ValidationError as exc:
raise ValidationError(
"%s is not a valid child of %s: %s" % (
child,
parent,
exc,
)
) from exc | python | def validate_chain(
cls,
root: BlockHeader,
descendants: Tuple[BlockHeader, ...],
seal_check_random_sample_rate: int = 1) -> None:
"""
Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal validity (Proof-of-Work on Ethereum 1.x mainnet) of all headers.
This can be expensive. Instead, check a random sample of seals using
seal_check_random_sample_rate.
"""
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_check_random_sample_rate
indices_to_check_seal = set(random.sample(all_indices, sample_size))
header_pairs = sliding_window(2, concatv([root], descendants))
for index, (parent, child) in enumerate(header_pairs):
if child.parent_hash != parent.hash:
raise ValidationError(
"Invalid header chain; {} has parent {}, but expected {}".format(
child, child.parent_hash, parent.hash))
should_check_seal = index in indices_to_check_seal
vm_class = cls.get_vm_class_for_block_number(child.block_number)
try:
vm_class.validate_header(child, parent, check_seal=should_check_seal)
except ValidationError as exc:
raise ValidationError(
"%s is not a valid child of %s: %s" % (
child,
parent,
exc,
)
) from exc | [
"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_check_random_sample_rate",
"indices_to_check_seal",
"=",
"set",
"(",
"random",
".",
"sample",
"(",
"all_indices",
",",
"sample_size",
")",
")",
"header_pairs",
"=",
"sliding_window",
"(",
"2",
",",
"concatv",
"(",
"[",
"root",
"]",
",",
"descendants",
")",
")",
"for",
"index",
",",
"(",
"parent",
",",
"child",
")",
"in",
"enumerate",
"(",
"header_pairs",
")",
":",
"if",
"child",
".",
"parent_hash",
"!=",
"parent",
".",
"hash",
":",
"raise",
"ValidationError",
"(",
"\"Invalid header chain; {} has parent {}, but expected {}\"",
".",
"format",
"(",
"child",
",",
"child",
".",
"parent_hash",
",",
"parent",
".",
"hash",
")",
")",
"should_check_seal",
"=",
"index",
"in",
"indices_to_check_seal",
"vm_class",
"=",
"cls",
".",
"get_vm_class_for_block_number",
"(",
"child",
".",
"block_number",
")",
"try",
":",
"vm_class",
".",
"validate_header",
"(",
"child",
",",
"parent",
",",
"check_seal",
"=",
"should_check_seal",
")",
"except",
"ValidationError",
"as",
"exc",
":",
"raise",
"ValidationError",
"(",
"\"%s is not a valid child of %s: %s\"",
"%",
"(",
"child",
",",
"parent",
",",
"exc",
",",
")",
")",
"from",
"exc"
] | Validate that all of the descendents are valid, given that the root header is valid.
By default, check the seal validity (Proof-of-Work on Ethereum 1.x mainnet) of all headers.
This can be expensive. Instead, check a random sample of seals using
seal_check_random_sample_rate. | [
"Validate",
"that",
"all",
"of",
"the",
"descendents",
"are",
"valid",
"given",
"that",
"the",
"root",
"header",
"is",
"valid",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L326-L364 |
230,185 | ethereum/py-evm | eth/chains/base.py | Chain.from_genesis | def from_genesis(cls,
base_db: BaseAtomicDB,
genesis_params: Dict[str, HeaderParams],
genesis_state: AccountState=None) -> 'BaseChain':
"""
Initializes the Chain from a genesis state.
"""
genesis_vm_class = cls.get_vm_class_for_block_number(BlockNumber(0))
pre_genesis_header = BlockHeader(difficulty=0, block_number=-1, gas_limit=0)
state = genesis_vm_class.build_state(base_db, pre_genesis_header)
if genesis_state is None:
genesis_state = {}
# mutation
apply_state_dict(state, genesis_state)
state.persist()
if 'state_root' not in genesis_params:
# If the genesis state_root was not specified, use the value
# computed from the initialized state database.
genesis_params = assoc(genesis_params, 'state_root', state.state_root)
elif genesis_params['state_root'] != state.state_root:
# If the genesis state_root was specified, validate that it matches
# the computed state from the initialized state database.
raise ValidationError(
"The provided genesis state root does not match the computed "
"genesis state root. Got {0}. Expected {1}".format(
state.state_root,
genesis_params['state_root'],
)
)
genesis_header = BlockHeader(**genesis_params)
return cls.from_genesis_header(base_db, genesis_header) | python | def from_genesis(cls,
base_db: BaseAtomicDB,
genesis_params: Dict[str, HeaderParams],
genesis_state: AccountState=None) -> 'BaseChain':
"""
Initializes the Chain from a genesis state.
"""
genesis_vm_class = cls.get_vm_class_for_block_number(BlockNumber(0))
pre_genesis_header = BlockHeader(difficulty=0, block_number=-1, gas_limit=0)
state = genesis_vm_class.build_state(base_db, pre_genesis_header)
if genesis_state is None:
genesis_state = {}
# mutation
apply_state_dict(state, genesis_state)
state.persist()
if 'state_root' not in genesis_params:
# If the genesis state_root was not specified, use the value
# computed from the initialized state database.
genesis_params = assoc(genesis_params, 'state_root', state.state_root)
elif genesis_params['state_root'] != state.state_root:
# If the genesis state_root was specified, validate that it matches
# the computed state from the initialized state database.
raise ValidationError(
"The provided genesis state root does not match the computed "
"genesis state root. Got {0}. Expected {1}".format(
state.state_root,
genesis_params['state_root'],
)
)
genesis_header = BlockHeader(**genesis_params)
return cls.from_genesis_header(base_db, genesis_header) | [
"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",
")",
"state",
"=",
"genesis_vm_class",
".",
"build_state",
"(",
"base_db",
",",
"pre_genesis_header",
")",
"if",
"genesis_state",
"is",
"None",
":",
"genesis_state",
"=",
"{",
"}",
"# mutation",
"apply_state_dict",
"(",
"state",
",",
"genesis_state",
")",
"state",
".",
"persist",
"(",
")",
"if",
"'state_root'",
"not",
"in",
"genesis_params",
":",
"# If the genesis state_root was not specified, use the value",
"# computed from the initialized state database.",
"genesis_params",
"=",
"assoc",
"(",
"genesis_params",
",",
"'state_root'",
",",
"state",
".",
"state_root",
")",
"elif",
"genesis_params",
"[",
"'state_root'",
"]",
"!=",
"state",
".",
"state_root",
":",
"# If the genesis state_root was specified, validate that it matches",
"# the computed state from the initialized state database.",
"raise",
"ValidationError",
"(",
"\"The provided genesis state root does not match the computed \"",
"\"genesis state root. Got {0}. Expected {1}\"",
".",
"format",
"(",
"state",
".",
"state_root",
",",
"genesis_params",
"[",
"'state_root'",
"]",
",",
")",
")",
"genesis_header",
"=",
"BlockHeader",
"(",
"*",
"*",
"genesis_params",
")",
"return",
"cls",
".",
"from_genesis_header",
"(",
"base_db",
",",
"genesis_header",
")"
] | Initializes the Chain from a genesis state. | [
"Initializes",
"the",
"Chain",
"from",
"a",
"genesis",
"state",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L405-L440 |
230,186 | ethereum/py-evm | eth/chains/base.py | Chain.get_vm | def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
"""
Returns the VM instance for the given block number.
"""
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) | python | def get_vm(self, at_header: BlockHeader=None) -> 'BaseVM':
"""
Returns the VM instance for the given block number.
"""
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) | [
"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. | [
"Returns",
"the",
"VM",
"instance",
"for",
"the",
"given",
"block",
"number",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L456-L462 |
230,187 | ethereum/py-evm | eth/chains/base.py | Chain.create_header_from_parent | def create_header_from_parent(self,
parent_header: BlockHeader,
**header_params: HeaderParams) -> BlockHeader:
"""
Passthrough helper to the VM class of the block descending from the
given header.
"""
return self.get_vm_class_for_block_number(
block_number=parent_header.block_number + 1,
).create_header_from_parent(parent_header, **header_params) | python | def create_header_from_parent(self,
parent_header: BlockHeader,
**header_params: HeaderParams) -> BlockHeader:
"""
Passthrough helper to the VM class of the block descending from the
given header.
"""
return self.get_vm_class_for_block_number(
block_number=parent_header.block_number + 1,
).create_header_from_parent(parent_header, **header_params) | [
"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. | [
"Passthrough",
"helper",
"to",
"the",
"VM",
"class",
"of",
"the",
"block",
"descending",
"from",
"the",
"given",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L467-L476 |
230,188 | ethereum/py-evm | eth/chains/base.py | Chain.ensure_header | def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
"""
Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head.
"""
if header is None:
head = self.get_canonical_head()
return self.create_header_from_parent(head)
else:
return header | python | def ensure_header(self, header: BlockHeader=None) -> BlockHeader:
"""
Return ``header`` if it is not ``None``, otherwise return the header
of the canonical head.
"""
if header is None:
head = self.get_canonical_head()
return self.create_header_from_parent(head)
else:
return header | [
"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. | [
"Return",
"header",
"if",
"it",
"is",
"not",
"None",
"otherwise",
"return",
"the",
"header",
"of",
"the",
"canonical",
"head",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L503-L512 |
230,189 | ethereum/py-evm | eth/chains/base.py | Chain.get_ancestors | def get_ancestors(self, limit: int, header: BlockHeader) -> Tuple[BaseBlock, ...]:
"""
Return `limit` number of ancestor blocks from the current canonical head.
"""
ancestor_count = min(header.block_number, limit)
# We construct a temporary block object
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=[])
ancestor_generator = iterate(compose(
self.get_block_by_hash,
operator.attrgetter('parent_hash'),
operator.attrgetter('header'),
), block)
# we peel off the first element from the iterator which will be the
# temporary block object we constructed.
next(ancestor_generator)
return tuple(take(ancestor_count, ancestor_generator)) | python | def get_ancestors(self, limit: int, header: BlockHeader) -> Tuple[BaseBlock, ...]:
"""
Return `limit` number of ancestor blocks from the current canonical head.
"""
ancestor_count = min(header.block_number, limit)
# We construct a temporary block object
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=[])
ancestor_generator = iterate(compose(
self.get_block_by_hash,
operator.attrgetter('parent_hash'),
operator.attrgetter('header'),
), block)
# we peel off the first element from the iterator which will be the
# temporary block object we constructed.
next(ancestor_generator)
return tuple(take(ancestor_count, ancestor_generator)) | [
"def",
"get_ancestors",
"(",
"self",
",",
"limit",
":",
"int",
",",
"header",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"BaseBlock",
",",
"...",
"]",
":",
"ancestor_count",
"=",
"min",
"(",
"header",
".",
"block_number",
",",
"limit",
")",
"# We construct a temporary block object",
"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",
"=",
"[",
"]",
")",
"ancestor_generator",
"=",
"iterate",
"(",
"compose",
"(",
"self",
".",
"get_block_by_hash",
",",
"operator",
".",
"attrgetter",
"(",
"'parent_hash'",
")",
",",
"operator",
".",
"attrgetter",
"(",
"'header'",
")",
",",
")",
",",
"block",
")",
"# we peel off the first element from the iterator which will be the",
"# temporary block object we constructed.",
"next",
"(",
"ancestor_generator",
")",
"return",
"tuple",
"(",
"take",
"(",
"ancestor_count",
",",
"ancestor_generator",
")",
")"
] | Return `limit` number of ancestor blocks from the current canonical head. | [
"Return",
"limit",
"number",
"of",
"ancestor",
"blocks",
"from",
"the",
"current",
"canonical",
"head",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L517-L537 |
230,190 | ethereum/py-evm | eth/chains/base.py | Chain.get_block_by_hash | def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock:
"""
Returns the requested block as specified by block hash.
"""
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) | python | def get_block_by_hash(self, block_hash: Hash32) -> BaseBlock:
"""
Returns the requested block as specified by block hash.
"""
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) | [
"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. | [
"Returns",
"the",
"requested",
"block",
"as",
"specified",
"by",
"block",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L545-L551 |
230,191 | ethereum/py-evm | eth/chains/base.py | Chain.get_block_by_header | def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
"""
Returns the requested block as specified by the block header.
"""
vm = self.get_vm(block_header)
return vm.block | python | def get_block_by_header(self, block_header: BlockHeader) -> BaseBlock:
"""
Returns the requested block as specified by the block header.
"""
vm = self.get_vm(block_header)
return vm.block | [
"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. | [
"Returns",
"the",
"requested",
"block",
"as",
"specified",
"by",
"the",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L553-L558 |
230,192 | ethereum/py-evm | eth/chains/base.py | Chain.get_canonical_block_by_number | def get_canonical_block_by_number(self, block_number: BlockNumber) -> BaseBlock:
"""
Returns the block with the given number in the canonical chain.
Raises BlockNotFound if there's no block with the given number in the
canonical chain.
"""
validate_uint256(block_number, title="Block Number")
return self.get_block_by_hash(self.chaindb.get_canonical_block_hash(block_number)) | python | def get_canonical_block_by_number(self, block_number: BlockNumber) -> BaseBlock:
"""
Returns the block with the given number in the canonical chain.
Raises BlockNotFound if there's no block with the given number in the
canonical chain.
"""
validate_uint256(block_number, title="Block Number")
return self.get_block_by_hash(self.chaindb.get_canonical_block_hash(block_number)) | [
"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.
Raises BlockNotFound if there's no block with the given number in the
canonical chain. | [
"Returns",
"the",
"block",
"with",
"the",
"given",
"number",
"in",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L560-L568 |
230,193 | ethereum/py-evm | eth/chains/base.py | Chain.get_canonical_transaction | def get_canonical_transaction(self, transaction_hash: Hash32) -> BaseTransaction:
"""
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain.
"""
(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.get_transaction_class(),
)
if transaction.hash == transaction_hash:
return transaction
else:
raise TransactionNotFound("Found transaction {} instead of {} in block {} at {}".format(
encode_hex(transaction.hash),
encode_hex(transaction_hash),
block_num,
index,
)) | python | def get_canonical_transaction(self, transaction_hash: Hash32) -> BaseTransaction:
"""
Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain.
"""
(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.get_transaction_class(),
)
if transaction.hash == transaction_hash:
return transaction
else:
raise TransactionNotFound("Found transaction {} instead of {} in block {} at {}".format(
encode_hex(transaction.hash),
encode_hex(transaction_hash),
block_num,
index,
)) | [
"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",
".",
"get_transaction_class",
"(",
")",
",",
")",
"if",
"transaction",
".",
"hash",
"==",
"transaction_hash",
":",
"return",
"transaction",
"else",
":",
"raise",
"TransactionNotFound",
"(",
"\"Found transaction {} instead of {} in block {} at {}\"",
".",
"format",
"(",
"encode_hex",
"(",
"transaction",
".",
"hash",
")",
",",
"encode_hex",
"(",
"transaction_hash",
")",
",",
"block_num",
",",
"index",
",",
")",
")"
] | Returns the requested transaction as specified by the transaction hash
from the canonical chain.
Raises TransactionNotFound if no transaction with the specified hash is
found in the main chain. | [
"Returns",
"the",
"requested",
"transaction",
"as",
"specified",
"by",
"the",
"transaction",
"hash",
"from",
"the",
"canonical",
"chain",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L604-L629 |
230,194 | ethereum/py-evm | eth/chains/base.py | Chain.estimate_gas | def estimate_gas(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader=None) -> int:
"""
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.
"""
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) | python | def estimate_gas(
self,
transaction: BaseOrSpoofTransaction,
at_header: BlockHeader=None) -> int:
"""
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.
"""
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) | [
"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. | [
"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",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L685-L696 |
230,195 | ethereum/py-evm | eth/chains/base.py | Chain.import_block | def import_block(self,
block: BaseBlock,
perform_validation: bool=True
) -> Tuple[BaseBlock, Tuple[BaseBlock, ...], Tuple[BaseBlock, ...]]:
"""
Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of blocks which are now part of the canonical chain.
- a tuple of blocks which were canonical and now are no longer canonical.
"""
try:
parent_header = self.get_block_header_by_hash(block.header.parent_hash)
except HeaderNotFound:
raise ValidationError(
"Attempt to import block #{}. Cannot import block {} before importing "
"its parent block at {}".format(
block.number,
block.hash,
block.header.parent_hash,
)
)
base_header_for_import = self.create_header_from_parent(parent_header)
imported_block = self.get_vm(base_header_for_import).import_block(block)
# Validate the imported block.
if perform_validation:
validate_imported_block_unchanged(imported_block, block)
self.validate_block(imported_block)
(
new_canonical_hashes,
old_canonical_hashes,
) = self.chaindb.persist_block(imported_block)
self.logger.debug(
'IMPORTED_BLOCK: number %s | hash %s',
imported_block.number,
encode_hex(imported_block.hash),
)
new_canonical_blocks = tuple(
self.get_block_by_hash(header_hash)
for header_hash
in new_canonical_hashes
)
old_canonical_blocks = tuple(
self.get_block_by_hash(header_hash)
for header_hash
in old_canonical_hashes
)
return imported_block, new_canonical_blocks, old_canonical_blocks | python | def import_block(self,
block: BaseBlock,
perform_validation: bool=True
) -> Tuple[BaseBlock, Tuple[BaseBlock, ...], Tuple[BaseBlock, ...]]:
"""
Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of blocks which are now part of the canonical chain.
- a tuple of blocks which were canonical and now are no longer canonical.
"""
try:
parent_header = self.get_block_header_by_hash(block.header.parent_hash)
except HeaderNotFound:
raise ValidationError(
"Attempt to import block #{}. Cannot import block {} before importing "
"its parent block at {}".format(
block.number,
block.hash,
block.header.parent_hash,
)
)
base_header_for_import = self.create_header_from_parent(parent_header)
imported_block = self.get_vm(base_header_for_import).import_block(block)
# Validate the imported block.
if perform_validation:
validate_imported_block_unchanged(imported_block, block)
self.validate_block(imported_block)
(
new_canonical_hashes,
old_canonical_hashes,
) = self.chaindb.persist_block(imported_block)
self.logger.debug(
'IMPORTED_BLOCK: number %s | hash %s',
imported_block.number,
encode_hex(imported_block.hash),
)
new_canonical_blocks = tuple(
self.get_block_by_hash(header_hash)
for header_hash
in new_canonical_hashes
)
old_canonical_blocks = tuple(
self.get_block_by_hash(header_hash)
for header_hash
in old_canonical_hashes
)
return imported_block, new_canonical_blocks, old_canonical_blocks | [
"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 block #{}. Cannot import block {} before importing \"",
"\"its parent block at {}\"",
".",
"format",
"(",
"block",
".",
"number",
",",
"block",
".",
"hash",
",",
"block",
".",
"header",
".",
"parent_hash",
",",
")",
")",
"base_header_for_import",
"=",
"self",
".",
"create_header_from_parent",
"(",
"parent_header",
")",
"imported_block",
"=",
"self",
".",
"get_vm",
"(",
"base_header_for_import",
")",
".",
"import_block",
"(",
"block",
")",
"# Validate the imported block.",
"if",
"perform_validation",
":",
"validate_imported_block_unchanged",
"(",
"imported_block",
",",
"block",
")",
"self",
".",
"validate_block",
"(",
"imported_block",
")",
"(",
"new_canonical_hashes",
",",
"old_canonical_hashes",
",",
")",
"=",
"self",
".",
"chaindb",
".",
"persist_block",
"(",
"imported_block",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'IMPORTED_BLOCK: number %s | hash %s'",
",",
"imported_block",
".",
"number",
",",
"encode_hex",
"(",
"imported_block",
".",
"hash",
")",
",",
")",
"new_canonical_blocks",
"=",
"tuple",
"(",
"self",
".",
"get_block_by_hash",
"(",
"header_hash",
")",
"for",
"header_hash",
"in",
"new_canonical_hashes",
")",
"old_canonical_blocks",
"=",
"tuple",
"(",
"self",
".",
"get_block_by_hash",
"(",
"header_hash",
")",
"for",
"header_hash",
"in",
"old_canonical_hashes",
")",
"return",
"imported_block",
",",
"new_canonical_blocks",
",",
"old_canonical_blocks"
] | Imports a complete block and returns a 3-tuple
- the imported block
- a tuple of blocks which are now part of the canonical chain.
- a tuple of blocks which were canonical and now are no longer canonical. | [
"Imports",
"a",
"complete",
"block",
"and",
"returns",
"a",
"3",
"-",
"tuple"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L698-L752 |
230,196 | ethereum/py-evm | eth/chains/base.py | Chain.validate_block | def validate_block(self, block: BaseBlock) -> None:
"""
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
Cannot be used to validate genesis block.
"""
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.validate_header(block.header, parent_block.header, check_seal=True)
self.validate_uncles(block)
self.validate_gaslimit(block.header) | python | def validate_block(self, block: BaseBlock) -> None:
"""
Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
Cannot be used to validate genesis block.
"""
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.validate_header(block.header, parent_block.header, check_seal=True)
self.validate_uncles(block)
self.validate_gaslimit(block.header) | [
"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",
".",
"validate_header",
"(",
"block",
".",
"header",
",",
"parent_block",
".",
"header",
",",
"check_seal",
"=",
"True",
")",
"self",
".",
"validate_uncles",
"(",
"block",
")",
"self",
".",
"validate_gaslimit",
"(",
"block",
".",
"header",
")"
] | Performs validation on a block that is either being mined or imported.
Since block validation (specifically the uncle validation) must have
access to the ancestor blocks, this validation must occur at the Chain
level.
Cannot be used to validate genesis block. | [
"Performs",
"validation",
"on",
"a",
"block",
"that",
"is",
"either",
"being",
"mined",
"or",
"imported",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L761-L777 |
230,197 | ethereum/py-evm | eth/chains/base.py | Chain.validate_gaslimit | def validate_gaslimit(self, header: BlockHeader) -> None:
"""
Validate the gas limit on the given header.
"""
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 at least {2}".format(
encode_hex(header.hash), header.gas_limit, low_bound))
elif header.gas_limit > high_bound:
raise ValidationError(
"The gas limit on block {0} is too high: {1}. It must be at most {2}".format(
encode_hex(header.hash), header.gas_limit, high_bound)) | python | def validate_gaslimit(self, header: BlockHeader) -> None:
"""
Validate the gas limit on the given header.
"""
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 at least {2}".format(
encode_hex(header.hash), header.gas_limit, low_bound))
elif header.gas_limit > high_bound:
raise ValidationError(
"The gas limit on block {0} is too high: {1}. It must be at most {2}".format(
encode_hex(header.hash), header.gas_limit, high_bound)) | [
"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 at least {2}\"",
".",
"format",
"(",
"encode_hex",
"(",
"header",
".",
"hash",
")",
",",
"header",
".",
"gas_limit",
",",
"low_bound",
")",
")",
"elif",
"header",
".",
"gas_limit",
">",
"high_bound",
":",
"raise",
"ValidationError",
"(",
"\"The gas limit on block {0} is too high: {1}. It must be at most {2}\"",
".",
"format",
"(",
"encode_hex",
"(",
"header",
".",
"hash",
")",
",",
"header",
".",
"gas_limit",
",",
"high_bound",
")",
")"
] | Validate the gas limit on the given header. | [
"Validate",
"the",
"gas",
"limit",
"on",
"the",
"given",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L786-L799 |
230,198 | ethereum/py-evm | eth/chains/base.py | Chain.validate_uncles | def validate_uncles(self, block: BaseBlock) -> None:
"""
Validate the uncles for the given block.
"""
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:
# optimization to avoid loading ancestors from DB, since the block has no uncles
return
elif has_uncles and not should_have_uncles:
raise ValidationError("Block has uncles but header suggests uncles should be empty")
elif should_have_uncles and not has_uncles:
raise ValidationError("Header suggests block should have uncles but block has none")
# Check for duplicates
uncle_groups = groupby(operator.attrgetter('hash'), block.uncles)
duplicate_uncles = tuple(sorted(
hash for hash, twins in uncle_groups.items() if len(twins) > 1
))
if duplicate_uncles:
raise ValidationError(
"Block contains duplicate uncles:\n"
" - {0}".format(' - '.join(duplicate_uncles))
)
recent_ancestors = tuple(
ancestor
for ancestor
in self.get_ancestors(MAX_UNCLE_DEPTH + 1, header=block.header)
)
recent_ancestor_hashes = {ancestor.hash for ancestor in recent_ancestors}
recent_uncle_hashes = _extract_uncle_hashes(recent_ancestors)
for uncle in block.uncles:
if uncle.hash == block.hash:
raise ValidationError("Uncle has same hash as block")
# ensure the uncle has not already been included.
if uncle.hash in recent_uncle_hashes:
raise ValidationError(
"Duplicate uncle: {0}".format(encode_hex(uncle.hash))
)
# ensure that the uncle is not one of the canonical chain blocks.
if uncle.hash in recent_ancestor_hashes:
raise ValidationError(
"Uncle {0} cannot be an ancestor of {1}".format(
encode_hex(uncle.hash), encode_hex(block.hash)))
# ensure that the uncle was built off of one of the canonical chain
# blocks.
if uncle.parent_hash not in recent_ancestor_hashes or (
uncle.parent_hash == block.header.parent_hash):
raise ValidationError(
"Uncle's parent {0} is not an ancestor of {1}".format(
encode_hex(uncle.parent_hash), encode_hex(block.hash)))
# Now perform VM level validation of the uncle
self.validate_seal(uncle)
try:
uncle_parent = self.get_block_header_by_hash(uncle.parent_hash)
except HeaderNotFound:
raise ValidationError(
"Uncle ancestor not found: {0}".format(uncle.parent_hash)
)
uncle_vm_class = self.get_vm_class_for_block_number(uncle.block_number)
uncle_vm_class.validate_uncle(block, uncle, uncle_parent) | python | def validate_uncles(self, block: BaseBlock) -> None:
"""
Validate the uncles for the given block.
"""
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:
# optimization to avoid loading ancestors from DB, since the block has no uncles
return
elif has_uncles and not should_have_uncles:
raise ValidationError("Block has uncles but header suggests uncles should be empty")
elif should_have_uncles and not has_uncles:
raise ValidationError("Header suggests block should have uncles but block has none")
# Check for duplicates
uncle_groups = groupby(operator.attrgetter('hash'), block.uncles)
duplicate_uncles = tuple(sorted(
hash for hash, twins in uncle_groups.items() if len(twins) > 1
))
if duplicate_uncles:
raise ValidationError(
"Block contains duplicate uncles:\n"
" - {0}".format(' - '.join(duplicate_uncles))
)
recent_ancestors = tuple(
ancestor
for ancestor
in self.get_ancestors(MAX_UNCLE_DEPTH + 1, header=block.header)
)
recent_ancestor_hashes = {ancestor.hash for ancestor in recent_ancestors}
recent_uncle_hashes = _extract_uncle_hashes(recent_ancestors)
for uncle in block.uncles:
if uncle.hash == block.hash:
raise ValidationError("Uncle has same hash as block")
# ensure the uncle has not already been included.
if uncle.hash in recent_uncle_hashes:
raise ValidationError(
"Duplicate uncle: {0}".format(encode_hex(uncle.hash))
)
# ensure that the uncle is not one of the canonical chain blocks.
if uncle.hash in recent_ancestor_hashes:
raise ValidationError(
"Uncle {0} cannot be an ancestor of {1}".format(
encode_hex(uncle.hash), encode_hex(block.hash)))
# ensure that the uncle was built off of one of the canonical chain
# blocks.
if uncle.parent_hash not in recent_ancestor_hashes or (
uncle.parent_hash == block.header.parent_hash):
raise ValidationError(
"Uncle's parent {0} is not an ancestor of {1}".format(
encode_hex(uncle.parent_hash), encode_hex(block.hash)))
# Now perform VM level validation of the uncle
self.validate_seal(uncle)
try:
uncle_parent = self.get_block_header_by_hash(uncle.parent_hash)
except HeaderNotFound:
raise ValidationError(
"Uncle ancestor not found: {0}".format(uncle.parent_hash)
)
uncle_vm_class = self.get_vm_class_for_block_number(uncle.block_number)
uncle_vm_class.validate_uncle(block, uncle, uncle_parent) | [
"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",
":",
"# optimization to avoid loading ancestors from DB, since the block has no uncles",
"return",
"elif",
"has_uncles",
"and",
"not",
"should_have_uncles",
":",
"raise",
"ValidationError",
"(",
"\"Block has uncles but header suggests uncles should be empty\"",
")",
"elif",
"should_have_uncles",
"and",
"not",
"has_uncles",
":",
"raise",
"ValidationError",
"(",
"\"Header suggests block should have uncles but block has none\"",
")",
"# Check for duplicates",
"uncle_groups",
"=",
"groupby",
"(",
"operator",
".",
"attrgetter",
"(",
"'hash'",
")",
",",
"block",
".",
"uncles",
")",
"duplicate_uncles",
"=",
"tuple",
"(",
"sorted",
"(",
"hash",
"for",
"hash",
",",
"twins",
"in",
"uncle_groups",
".",
"items",
"(",
")",
"if",
"len",
"(",
"twins",
")",
">",
"1",
")",
")",
"if",
"duplicate_uncles",
":",
"raise",
"ValidationError",
"(",
"\"Block contains duplicate uncles:\\n\"",
"\" - {0}\"",
".",
"format",
"(",
"' - '",
".",
"join",
"(",
"duplicate_uncles",
")",
")",
")",
"recent_ancestors",
"=",
"tuple",
"(",
"ancestor",
"for",
"ancestor",
"in",
"self",
".",
"get_ancestors",
"(",
"MAX_UNCLE_DEPTH",
"+",
"1",
",",
"header",
"=",
"block",
".",
"header",
")",
")",
"recent_ancestor_hashes",
"=",
"{",
"ancestor",
".",
"hash",
"for",
"ancestor",
"in",
"recent_ancestors",
"}",
"recent_uncle_hashes",
"=",
"_extract_uncle_hashes",
"(",
"recent_ancestors",
")",
"for",
"uncle",
"in",
"block",
".",
"uncles",
":",
"if",
"uncle",
".",
"hash",
"==",
"block",
".",
"hash",
":",
"raise",
"ValidationError",
"(",
"\"Uncle has same hash as block\"",
")",
"# ensure the uncle has not already been included.",
"if",
"uncle",
".",
"hash",
"in",
"recent_uncle_hashes",
":",
"raise",
"ValidationError",
"(",
"\"Duplicate uncle: {0}\"",
".",
"format",
"(",
"encode_hex",
"(",
"uncle",
".",
"hash",
")",
")",
")",
"# ensure that the uncle is not one of the canonical chain blocks.",
"if",
"uncle",
".",
"hash",
"in",
"recent_ancestor_hashes",
":",
"raise",
"ValidationError",
"(",
"\"Uncle {0} cannot be an ancestor of {1}\"",
".",
"format",
"(",
"encode_hex",
"(",
"uncle",
".",
"hash",
")",
",",
"encode_hex",
"(",
"block",
".",
"hash",
")",
")",
")",
"# ensure that the uncle was built off of one of the canonical chain",
"# blocks.",
"if",
"uncle",
".",
"parent_hash",
"not",
"in",
"recent_ancestor_hashes",
"or",
"(",
"uncle",
".",
"parent_hash",
"==",
"block",
".",
"header",
".",
"parent_hash",
")",
":",
"raise",
"ValidationError",
"(",
"\"Uncle's parent {0} is not an ancestor of {1}\"",
".",
"format",
"(",
"encode_hex",
"(",
"uncle",
".",
"parent_hash",
")",
",",
"encode_hex",
"(",
"block",
".",
"hash",
")",
")",
")",
"# Now perform VM level validation of the uncle",
"self",
".",
"validate_seal",
"(",
"uncle",
")",
"try",
":",
"uncle_parent",
"=",
"self",
".",
"get_block_header_by_hash",
"(",
"uncle",
".",
"parent_hash",
")",
"except",
"HeaderNotFound",
":",
"raise",
"ValidationError",
"(",
"\"Uncle ancestor not found: {0}\"",
".",
"format",
"(",
"uncle",
".",
"parent_hash",
")",
")",
"uncle_vm_class",
"=",
"self",
".",
"get_vm_class_for_block_number",
"(",
"uncle",
".",
"block_number",
")",
"uncle_vm_class",
".",
"validate_uncle",
"(",
"block",
",",
"uncle",
",",
"uncle_parent",
")"
] | Validate the uncles for the given block. | [
"Validate",
"the",
"uncles",
"for",
"the",
"given",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L801-L870 |
230,199 | ethereum/py-evm | eth/chains/base.py | MiningChain.apply_transaction | def apply_transaction(self,
transaction: BaseTransaction
) -> Tuple[BaseBlock, Receipt, BaseComputation]:
"""
Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy and incurs significant performance overhead.
"""
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_block.header, receipt)
# since we are building the block locally, we have to persist all the incremental state
vm.state.persist()
new_header = header_with_receipt.copy(state_root=vm.state.state_root)
transactions = base_block.transactions + (transaction, )
receipts = base_block.get_receipts(self.chaindb) + (receipt, )
new_block = vm.set_block_transactions(base_block, new_header, transactions, receipts)
self.header = new_block.header
return new_block, receipt, computation | python | def apply_transaction(self,
transaction: BaseTransaction
) -> Tuple[BaseBlock, Receipt, BaseComputation]:
"""
Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy and incurs significant performance overhead.
"""
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_block.header, receipt)
# since we are building the block locally, we have to persist all the incremental state
vm.state.persist()
new_header = header_with_receipt.copy(state_root=vm.state.state_root)
transactions = base_block.transactions + (transaction, )
receipts = base_block.get_receipts(self.chaindb) + (receipt, )
new_block = vm.set_block_transactions(base_block, new_header, transactions, receipts)
self.header = new_block.header
return new_block, receipt, computation | [
"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_block",
".",
"header",
",",
"receipt",
")",
"# since we are building the block locally, we have to persist all the incremental state",
"vm",
".",
"state",
".",
"persist",
"(",
")",
"new_header",
"=",
"header_with_receipt",
".",
"copy",
"(",
"state_root",
"=",
"vm",
".",
"state",
".",
"state_root",
")",
"transactions",
"=",
"base_block",
".",
"transactions",
"+",
"(",
"transaction",
",",
")",
"receipts",
"=",
"base_block",
".",
"get_receipts",
"(",
"self",
".",
"chaindb",
")",
"+",
"(",
"receipt",
",",
")",
"new_block",
"=",
"vm",
".",
"set_block_transactions",
"(",
"base_block",
",",
"new_header",
",",
"transactions",
",",
"receipts",
")",
"self",
".",
"header",
"=",
"new_block",
".",
"header",
"return",
"new_block",
",",
"receipt",
",",
"computation"
] | Applies the transaction to the current tip block.
WARNING: Receipt and Transaction trie generation is computationally
heavy and incurs significant performance overhead. | [
"Applies",
"the",
"transaction",
"to",
"the",
"current",
"tip",
"block",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/base.py#L887-L913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.