-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathbase.py
708 lines (612 loc) · 24.1 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
import contextlib
import itertools
import logging
from typing import (
Any,
ClassVar,
Iterable,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
)
from cached_property import cached_property
from eth_hash.auto import keccak
from eth_typing import (
Address,
Hash32,
)
from eth_utils import (
ValidationError,
)
import rlp
from eth.abc import (
AtomicDatabaseAPI,
BlockAPI,
BlockAndMetaWitness,
BlockHeaderAPI,
ChainContextAPI,
ChainDatabaseAPI,
ComputationAPI,
ConsensusAPI,
ConsensusContextAPI,
ExecutionContextAPI,
ReceiptAPI,
ReceiptBuilderAPI,
SignedTransactionAPI,
StateAPI,
TransactionBuilderAPI,
UnsignedTransactionAPI,
VirtualMachineAPI,
)
from eth.consensus.pow import (
PowConsensus,
)
from eth.constants import (
GENESIS_PARENT_HASH,
MAX_PREV_HEADER_DEPTH,
MAX_UNCLES,
)
from eth.db.trie import make_trie_root_and_nodes
from eth.exceptions import (
HeaderNotFound,
)
from eth.rlp.headers import (
BlockHeader,
)
from eth.rlp.sedes import (
uint32,
)
from eth._utils.datatypes import (
Configurable,
)
from eth._utils.db import (
get_parent_header,
get_block_header_by_hash,
)
from eth.validation import (
validate_length_lte,
validate_gas_limit,
)
from eth.vm.execution_context import (
ExecutionContext,
)
from eth.vm.interrupt import (
EVMMissingData,
)
from eth.vm.message import (
Message,
)
class VM(Configurable, VirtualMachineAPI):
block_class: Type[BlockAPI] = None
consensus_class: Type[ConsensusAPI] = PowConsensus
extra_data_max_bytes: ClassVar[int] = 32
fork: str = None # noqa: E701 # flake8 bug that's fixed in 3.6.0+
chaindb: ChainDatabaseAPI = None
_state_class: Type[StateAPI] = None
_state = None
_block = None
cls_logger = logging.getLogger('eth.vm.base.VM')
def __init__(self,
header: BlockHeaderAPI,
chaindb: ChainDatabaseAPI,
chain_context: ChainContextAPI,
consensus_context: ConsensusContextAPI) -> None:
self.chaindb = chaindb
self.chain_context = chain_context
self.consensus_context = consensus_context
self._initial_header = header
def get_header(self) -> BlockHeaderAPI:
if self._block is None:
return self._initial_header
else:
return self._block.header
def get_block(self) -> BlockAPI:
if self._block is None:
block_class = self.get_block_class()
self._block = block_class.from_header(header=self._initial_header, chaindb=self.chaindb)
return self._block
@property
def state(self) -> StateAPI:
if self._state is None:
self._state = self.build_state(self.chaindb.db,
self.get_header(),
self.chain_context,
self.previous_hashes)
return self._state
@classmethod
def build_state(cls,
db: AtomicDatabaseAPI,
header: BlockHeaderAPI,
chain_context: ChainContextAPI,
previous_hashes: Iterable[Hash32] = (),
) -> StateAPI:
execution_context = cls.create_execution_context(header, previous_hashes, chain_context)
return cls.get_state_class()(db, execution_context, header.state_root)
@cached_property
def _consensus(self) -> ConsensusAPI:
return self.consensus_class(self.consensus_context)
#
# Logging
#
@property
def logger(self) -> logging.Logger:
return logging.getLogger(f'eth.vm.base.VM.{self.__class__.__name__}')
#
# Execution
#
def apply_transaction(self,
header: BlockHeaderAPI,
transaction: SignedTransactionAPI
) -> Tuple[ReceiptAPI, ComputationAPI]:
self.validate_transaction_against_header(header, transaction)
# Mark current state as un-revertable, since new transaction is starting...
self.state.lock_changes()
computation = self.state.apply_transaction(transaction)
receipt = self.make_receipt(header, transaction, computation, self.state)
self.validate_receipt(receipt)
return receipt, computation
@classmethod
def create_execution_context(cls,
header: BlockHeaderAPI,
prev_hashes: Iterable[Hash32],
chain_context: ChainContextAPI) -> ExecutionContextAPI:
fee_recipient = cls.consensus_class.get_fee_recipient(header)
try:
base_fee = header.base_fee_per_gas
except AttributeError:
return ExecutionContext(
coinbase=fee_recipient,
timestamp=header.timestamp,
block_number=header.block_number,
difficulty=header.difficulty,
gas_limit=header.gas_limit,
prev_hashes=prev_hashes,
chain_id=chain_context.chain_id,
)
else:
return ExecutionContext(
coinbase=fee_recipient,
timestamp=header.timestamp,
block_number=header.block_number,
difficulty=header.difficulty,
gas_limit=header.gas_limit,
prev_hashes=prev_hashes,
chain_id=chain_context.chain_id,
base_fee_per_gas=base_fee,
)
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,
) -> ComputationAPI:
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.computation_class.apply_computation(
self.state,
message,
transaction_context,
)
def apply_all_transactions(
self,
transactions: Sequence[SignedTransactionAPI],
base_header: BlockHeaderAPI
) -> Tuple[BlockHeaderAPI, Tuple[ReceiptAPI, ...], Tuple[ComputationAPI, ...]]:
vm_header = self.get_header()
if base_header.block_number != vm_header.block_number:
raise ValidationError(
f"This VM instance must only work on block #{self.get_header().block_number}, "
f"but the target header has block #{base_header.block_number}"
)
receipts = []
computations = []
previous_header = base_header
result_header = base_header
for transaction_index, transaction in enumerate(transactions):
try:
snapshot = self.state.snapshot()
receipt, computation = self.apply_transaction(
previous_header,
transaction,
)
except EVMMissingData:
self.state.revert(snapshot)
raise
result_header = self.add_receipt_to_header(previous_header, receipt)
previous_header = result_header
receipts.append(receipt)
computations.append(computation)
self.transaction_applied_hook(
transaction_index,
transactions,
vm_header,
result_header,
computation,
receipt,
)
receipts_tuple = tuple(receipts)
computations_tuple = tuple(computations)
return result_header, receipts_tuple, computations_tuple
#
# Mining
#
def import_block(self, block: BlockAPI) -> BlockAndMetaWitness:
if self.get_block().number != block.number:
raise ValidationError(
f"This VM can only import blocks at number #{self.get_block().number},"
f" the attempted block was #{block.number}"
)
self._block = self.get_block().copy(
header=self.configure_header(
coinbase=block.header.coinbase,
difficulty=block.header.difficulty,
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,
)
execution_context = self.create_execution_context(
block.header, self.previous_hashes, self.chain_context)
# Zero out the gas_used before applying transactions. Each applied transaction will
# increase the gas used in the final new_header.
header = self.get_header().copy(gas_used=0)
# we need to re-initialize the `state` to update the execution context.
self._state = self.get_state_class()(self.chaindb.db, execution_context, header.state_root)
# run all of the transactions.
new_header, receipts, _ = self.apply_all_transactions(block.transactions, header)
block_with_transactions = self.set_block_transactions(
self.get_block(),
new_header,
block.transactions,
receipts,
)
return self.mine_block(block_with_transactions)
def mine_block(self, block: BlockAPI, *args: Any, **kwargs: Any) -> BlockAndMetaWitness:
packed_block = self.pack_block(block, *args, **kwargs)
block_result = self.finalize_block(packed_block)
# Perform validation
self.validate_block(block_result.block)
return block_result
def set_block_transactions(self,
base_block: BlockAPI,
new_header: BlockHeaderAPI,
transactions: Sequence[SignedTransactionAPI],
receipts: Sequence[ReceiptAPI]) -> BlockAPI:
tx_root_hash, tx_kv_nodes = make_trie_root_and_nodes(transactions)
self.chaindb.persist_trie_data_dict(tx_kv_nodes)
receipt_root_hash, receipt_kv_nodes = make_trie_root_and_nodes(receipts)
self.chaindb.persist_trie_data_dict(receipt_kv_nodes)
return base_block.copy(
transactions=transactions,
header=new_header.copy(
transaction_root=tx_root_hash,
receipt_root=receipt_root_hash,
),
)
#
# Finalization
#
def _assign_block_rewards(self, block: BlockAPI) -> None:
block_reward = self.get_block_reward() + (
len(block.uncles) * self.get_nephew_reward()
)
if block_reward != 0:
self.state.delta_balance(block.header.coinbase, block_reward)
self.logger.debug(
"BLOCK REWARD: %s -> %s",
block_reward,
block.header.coinbase,
)
else:
self.logger.debug("No block reward given to %s", block.header.coinbase)
for uncle in block.uncles:
uncle_reward = self.get_uncle_reward(block.number, uncle)
if uncle_reward != 0:
self.state.delta_balance(uncle.coinbase, uncle_reward)
self.logger.debug(
"UNCLE REWARD REWARD: %s -> %s",
uncle_reward,
uncle.coinbase,
)
else:
self.logger.debug("No uncle reward given to %s", uncle.coinbase)
def finalize_block(self, block: BlockAPI) -> BlockAndMetaWitness:
if block.number > 0:
snapshot = self.state.snapshot()
try:
self._assign_block_rewards(block)
except EVMMissingData:
self.state.revert(snapshot)
raise
else:
self.state.commit(snapshot)
# We need to call `persist` here since the state db batches
# all writes until we tell it to write to the underlying db
meta_witness = self.state.persist()
final_block = block.copy(header=block.header.copy(state_root=self.state.state_root))
self.logger.debug(
"%s reads %d unique node hashes, %d addresses, %d bytecodes, and %d storage slots",
final_block,
len(meta_witness.hashes),
len(meta_witness.accounts_queried),
len(meta_witness.account_bytecodes_queried),
meta_witness.total_slots_queried,
)
return BlockAndMetaWitness(final_block, meta_witness)
def pack_block(self, block: BlockAPI, *args: Any, **kwargs: Any) -> BlockAPI:
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(
f"Unable to set the field(s) {', '.join(known_fields)} "
"on the `BlockHeader` class. "
f"Received the following unexpected fields: {', '.join(unknown_fields)}."
)
header: BlockHeaderAPI = block.header.copy(**kwargs)
packed_block = block.copy(uncles=uncles, header=header)
return packed_block
#
# Blocks
#
@classmethod
def generate_block_from_parent_header_and_coinbase(cls,
parent_header: BlockHeaderAPI,
coinbase: Address) -> BlockAPI:
block_header = cls.create_header_from_parent(parent_header, coinbase=coinbase)
block = cls.get_block_class()(
block_header,
transactions=[],
uncles=[],
)
return block
@classmethod
def create_genesis_header(cls, **genesis_params: Any) -> BlockHeaderAPI:
# Create genesis header by setting the parent to None
return cls.create_header_from_parent(None, **genesis_params)
@classmethod
def get_block_class(cls) -> Type[BlockAPI]:
if cls.block_class is None:
raise AttributeError("No `block_class` has been set for this VM")
else:
return cls.block_class
@classmethod
def get_prev_hashes(cls,
last_block_hash: Hash32,
chaindb: ChainDatabaseAPI) -> Optional[Iterable[Hash32]]:
if last_block_hash == GENESIS_PARENT_HASH:
return
block_header = get_block_header_by_hash(last_block_hash, chaindb)
for _ in range(MAX_PREV_HEADER_DEPTH):
yield block_header.hash
try:
block_header = get_parent_header(block_header, chaindb)
except (IndexError, HeaderNotFound):
break
@property
def previous_hashes(self) -> Optional[Iterable[Hash32]]:
return self.get_prev_hashes(self.get_header().parent_hash, self.chaindb)
#
# Transactions
#
def create_transaction(self, *args: Any, **kwargs: Any) -> SignedTransactionAPI:
return self.get_transaction_builder().new_transaction(*args, **kwargs)
@classmethod
def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
data: bytes) -> UnsignedTransactionAPI:
return cls.get_transaction_builder().create_unsigned_transaction(
nonce=nonce,
gas_price=gas_price,
gas=gas,
to=to,
value=value,
data=data
)
@classmethod
def get_transaction_builder(cls) -> Type[TransactionBuilderAPI]:
return cls.get_block_class().get_transaction_builder()
@classmethod
def get_receipt_builder(cls) -> Type[ReceiptBuilderAPI]:
return cls.get_block_class().get_receipt_builder()
#
# Validate
#
@classmethod
def validate_receipt(cls, receipt: ReceiptAPI) -> None:
already_checked: Set[Union[Address, int]] = set()
for log_idx, log in enumerate(receipt.logs):
if log.address in already_checked:
continue
elif log.address not in receipt.bloom_filter:
raise ValidationError(
f"The address from the log entry at position {log_idx} is not "
"present in the provided bloom filter."
)
already_checked.add(log.address)
for log_idx, log in enumerate(receipt.logs):
for topic_idx, topic in enumerate(log.topics):
if topic in already_checked:
continue
elif uint32.serialize(topic) not in receipt.bloom_filter:
raise ValidationError(
f"The topic at position {topic_idx} from the log entry at "
f"position {log_idx} is not present in the provided bloom filter."
)
already_checked.add(topic)
def validate_block(self, block: BlockAPI) -> None:
if not isinstance(block, self.get_block_class()):
raise ValidationError(
f"This vm ({self!r}) is not equipped to validate a block of type {block!r}"
)
if block.is_genesis:
validate_length_lte(
block.header.extra_data,
self.extra_data_max_bytes,
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(
f"Block's transaction_root ({block.header.transaction_root!r}) "
f"does not match expected value: {tx_root_hash!r}"
)
if len(block.uncles) > MAX_UNCLES:
raise ValidationError(
f"Blocks may have a maximum of {MAX_UNCLES} uncles. "
f"Found {len(block.uncles)}."
)
if not self.chaindb.exists(block.header.state_root):
raise ValidationError(
"`state_root` was not found in the db.\n"
f"- state_root: {block.header.state_root!r}"
)
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"
f" - num_uncles : {len(block.uncles)}\n"
f" - block uncle_hash : {local_uncle_hash!r}\n"
f" - header uncle_hash: {block.header.uncles_hash!r}"
)
@classmethod
def validate_header(cls,
header: BlockHeaderAPI,
parent_header: BlockHeaderAPI) -> None:
if parent_header is None:
# to validate genesis header, check if it equals canonical header at block number 0
raise ValidationError("Must have access to parent header to validate current header")
else:
validate_length_lte(
header.extra_data, cls.extra_data_max_bytes, title="BlockHeader.extra_data")
cls.validate_gas(header, parent_header)
if header.block_number != parent_header.block_number + 1:
raise ValidationError(
"Blocks must be numbered consecutively. "
f"Block number #{header.block_number} "
f"has parent #{parent_header.block_number}"
)
# timestamp
if header.timestamp <= parent_header.timestamp:
raise ValidationError(
"timestamp must be strictly later than parent, "
f"but is {parent_header.timestamp - header.timestamp} seconds before.\n"
f"- child : {header.timestamp}\n"
f"- parent : {parent_header.timestamp}. "
)
@classmethod
def validate_gas(
cls,
header: BlockHeaderAPI,
parent_header: BlockHeaderAPI) -> None:
validate_gas_limit(header.gas_limit, parent_header.gas_limit)
def validate_seal(self, header: BlockHeaderAPI) -> None:
try:
self._consensus.validate_seal(header)
except ValidationError as exc:
self.cls_logger.debug(
"Failed to validate seal on header: %r. Error: %s",
header.as_dict(),
exc,
)
raise
def validate_seal_extension(self,
header: BlockHeaderAPI,
parents: Iterable[BlockHeaderAPI]) -> None:
self._consensus.validate_seal_extension(header, parents)
@classmethod
def validate_uncle(cls,
block: BlockAPI,
uncle: BlockHeaderAPI,
uncle_parent: BlockHeaderAPI) -> None:
if uncle.block_number >= block.number:
raise ValidationError(
f"Uncle number ({uncle.block_number}) is higher than "
f"block number ({block.number})"
)
if uncle.block_number != uncle_parent.block_number + 1:
raise ValidationError(
f"Uncle number ({uncle.block_number}) is not one above "
f"ancestor's number ({uncle_parent.block_number})"
)
if uncle.timestamp <= uncle_parent.timestamp:
raise ValidationError(
f"Uncle timestamp ({uncle.timestamp}) is not newer than its "
f"parent's timestamp ({uncle_parent.timestamp})"
)
if uncle.gas_used > uncle.gas_limit:
raise ValidationError(
f"Uncle's gas usage ({uncle.gas_used}) is above "
f"the limit ({uncle.gas_limit})"
)
uncle_parent_gas_limit = uncle_parent.gas_limit
if not hasattr(uncle_parent, 'base_fee_per_gas') and hasattr(uncle, 'base_fee_per_gas'):
# if Berlin -> London transition, double the parent limit for validation
uncle_parent_gas_limit *= 2
validate_gas_limit(uncle.gas_limit, uncle_parent_gas_limit)
#
# State
#
@classmethod
def get_state_class(cls) -> Type[StateAPI]:
if cls._state_class is None:
raise AttributeError("No `_state_class` has been set for this VM")
return cls._state_class
@contextlib.contextmanager
def in_costless_state(self) -> Iterator[StateAPI]:
header = self.get_header()
temp_block = self.generate_block_from_parent_header_and_coinbase(header, header.coinbase)
prev_hashes = itertools.chain((header.hash,), self.previous_hashes)
if hasattr(temp_block.header, 'base_fee_per_gas'):
free_header = temp_block.header.copy(base_fee_per_gas=0)
else:
free_header = temp_block.header
state = self.build_state(self.chaindb.db,
free_header,
self.chain_context,
prev_hashes)
snapshot = state.snapshot()
yield state
state.revert(snapshot)