Skip to content

Commit 1335026

Browse files
feat: Add Ethereum-style timestamp validation and PoW hash check
1 parent 9419fdb commit 1335026

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

minichain/chain.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import json
77
import os
88
import sys
9+
import time
910

1011
logger = logging.getLogger(__name__)
1112

@@ -25,6 +26,17 @@ def validate_block_link_and_hash(previous_block, block):
2526
if block.hash != expected_hash:
2627
raise ValueError(f"invalid hash {block.hash}")
2728

29+
target = "0" * (block.difficulty or 1)
30+
if not block.hash.startswith(target):
31+
raise ValueError(f"invalid Proof of Work: hash {block.hash} does not satisfy difficulty {block.difficulty}")
32+
33+
if block.timestamp <= previous_block.timestamp:
34+
raise ValueError(f"invalid timestamp: {block.timestamp} is not strictly greater than previous block timestamp {previous_block.timestamp}")
35+
36+
max_allowed_time = int(time.time() * 1000) + 15000
37+
if block.timestamp > max_allowed_time:
38+
raise ValueError(f"invalid timestamp: {block.timestamp} is too far in the future (max allowed: {max_allowed_time})")
39+
2840

2941
class Blockchain:
3042
"""

tests/test_persistence.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def _chain_with_tx(self):
5454
state_root=temp_state.state_root(),
5555
receipt_root=calculate_receipt_root([receipt]),
5656
receipts=[receipt],
57-
timestamp=int(time.time()),
57+
timestamp=bc.last_block.timestamp + 1000,
5858
)
5959
mine_block(block)
6060
bc.add_block(block)
@@ -249,7 +249,7 @@ def test_loaded_chain_can_add_new_block(self):
249249
state_root=temp_state.state_root(),
250250
receipt_root=calculate_receipt_root([receipt2]),
251251
receipts=[receipt2],
252-
timestamp=int(time.time()),
252+
timestamp=restored.last_block.timestamp + 1000,
253253
)
254254
mine_block(block2)
255255

0 commit comments

Comments
 (0)