This repository was archived by the owner on Aug 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathshasta_rules.rs
More file actions
872 lines (795 loc) · 30.7 KB
/
Copy pathshasta_rules.rs
File metadata and controls
872 lines (795 loc) · 30.7 KB
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
use core::cmp::{max, min};
use reth_evm_ethereum::taiko::ANCHOR_V4_GAS_LIMIT;
use reth_primitives::revm_primitives::SpecId;
use reth_primitives::{Block, Header};
use std::cmp::max as std_max;
use tracing::{info, warn};
use crate::consts::ForkCondition;
use crate::input::{BlockProposedFork, GuestBatchInput, GuestInput};
use crate::manifest::{DerivationSourceManifest, ProtocolBlockManifest, PROPOSAL_MAX_BLOCKS};
#[cfg(not(feature = "std"))]
use crate::no_std::*;
pub const BOND_PROCESSING_DELAY: usize = 6;
/// Maximum anchor block number offset for Hoodi and non-mainnet chains.
pub const ANCHOR_MAX_OFFSET: usize = 128;
/// Maximum anchor block number offset for Taiko mainnet.
pub const MAINNET_ANCHOR_MAX_OFFSET: usize = 512;
/// Returns the maximum anchor block number offset for the given chain ID.
/// Mainnet and Transition use 512; Hoodi and other chains use 128.
pub fn anchor_max_offset_for_chain(chain_id: u64) -> usize {
if is_mainnet_like_chain(chain_id) {
MAINNET_ANCHOR_MAX_OFFSET
} else {
ANCHOR_MAX_OFFSET
}
}
/// Decode Shasta `extra_data` layout (per `Derivation.md`):
/// - byte[0] => basefeeSharingPctg (uint8)
/// - byte[1..6] => proposalId (uint48, big-endian)
fn decode_shasta_extra_data(extra_data: &[u8]) -> Option<(u8, u64)> {
if extra_data.len() < 7 {
warn!(
"invalid shasta extra_data length: {} (need at least 7 bytes)",
extra_data.len()
);
return None;
}
let basefee_sharing_pctg = extra_data[0];
let proposal_id = u64::from_be_bytes([
0,
0,
extra_data[1],
extra_data[2],
extra_data[3],
extra_data[4],
extra_data[5],
extra_data[6],
]);
Some((basefee_sharing_pctg, proposal_id))
}
/// Validate Shasta `extra_data` for all blocks in this proposal batch.
///
/// Enforced in guests (ZKVM programs) by calling from `calculate_batch_blocks_final_header`,
/// so the proof itself rejects malformed `extra_data` even if host-side preflight is bypassed.
pub fn validate_shasta_extra_data_for_batch(input: &GuestBatchInput) -> bool {
let BlockProposedFork::Shasta(event_data) = &input.taiko.batch_proposed else {
return true;
};
if input.inputs.is_empty() {
warn!("empty shasta batch input");
return false;
}
let expected_basefee_sharing_pctg = event_data.proposal.basefeeSharingPctg;
let expected_proposal_id = input.taiko.batch_id;
for guest_input in input.inputs.iter() {
let header = &guest_input.block.header;
let Some((basefee_sharing_pctg, proposal_id)) =
decode_shasta_extra_data(header.extra_data.as_ref())
else {
warn!(
"failed to decode shasta extra_data for block {}",
header.number
);
return false;
};
if basefee_sharing_pctg != expected_basefee_sharing_pctg {
warn!(
"shasta extra_data basefeeSharingPctg mismatch for block {}: got {}, expected {}",
header.number, basefee_sharing_pctg, expected_basefee_sharing_pctg
);
return false;
}
if proposal_id != expected_proposal_id {
warn!(
"shasta extra_data proposalId mismatch for block {}: got {}, expected {}",
header.number, proposal_id, expected_proposal_id
);
return false;
}
}
// Optional: the parent of the 1st block should belong to the previous proposal.
if expected_proposal_id > 0 {
let parent_header = &input.inputs[0].parent_header;
let Some((_parent_pctg, parent_proposal_id)) =
decode_shasta_extra_data(parent_header.extra_data.as_ref())
else {
warn!(
"failed to decode shasta extra_data for parent of first block {} (parent {})",
input.inputs[0].block.header.number, parent_header.number
);
return false;
};
if parent_proposal_id != expected_proposal_id - 1 {
warn!(
"shasta parent extra_data proposalId mismatch for parent {}: got {}, expected {}",
parent_header.number,
parent_proposal_id,
expected_proposal_id - 1
);
return false;
}
}
true
}
pub(crate) fn valid_anchor_in_normal_proposal(
blocks: &[ProtocolBlockManifest],
last_anchor_block_number: u64,
l1_origin_block_number: u64,
anchor_max_offset: u64,
) -> bool {
// Check if anchor is within valid range [l1_header_number - anchor_max_offset, l1_header_number]
// Use saturating_sub to avoid underflow when l1_header_number is small
let min_anchor = l1_origin_block_number.saturating_sub(anchor_max_offset);
let max_anchor = l1_origin_block_number;
// Perform all checks in a single loop:
// 1. No anchor should regress below last_anchor_block_number
// 2. At least one anchor should be greater than last_anchor_block_number
// 3. Anchors should be in order (non-decreasing)
// 4. All anchors should be within valid range
let mut has_anchor_grow = false;
let mut prev_anchor = None;
for block in blocks.iter() {
let anchor = block.anchor_block_number;
// Check 1: no anchor should regress below last_anchor_block_number
if anchor < last_anchor_block_number {
warn!(
"anchor {} is below last_anchor_block_number {}",
anchor, last_anchor_block_number
);
return false;
}
// Check 2: at least one anchor should > last_anchor_block_number
if anchor > last_anchor_block_number {
has_anchor_grow = true;
}
// Check 3: anchors should be in order (non-decreasing)
if let Some(prev) = prev_anchor {
if anchor < prev {
warn!("anchor is not in order, blocks: {:?}", blocks);
return false;
}
}
prev_anchor = Some(anchor);
// Check 4: anchor should be within valid range
if anchor < min_anchor || anchor > max_anchor {
warn!(
"anchor {} is not in range, [{}, {}]",
anchor, min_anchor, max_anchor
);
return false;
}
}
if !has_anchor_grow {
warn!(
"anchor is not growing, last_anchor_block_number: {}",
last_anchor_block_number,
);
}
has_anchor_grow
}
pub(crate) fn validate_normal_proposal_manifest(
input: &GuestBatchInput,
manifest: &DerivationSourceManifest,
last_anchor_block_number: u64,
) -> bool {
let manifest_block_number = manifest.blocks.len();
if manifest_block_number > PROPOSAL_MAX_BLOCKS {
warn!(
"manifest_block_number {} > PROPOSAL_MAX_BLOCKS {}",
manifest_block_number, PROPOSAL_MAX_BLOCKS
);
return false;
}
let chain_id = input.taiko.chain_spec.chain_id();
let anchor_max_offset = anchor_max_offset_for_chain(chain_id) as u64;
if !valid_anchor_in_normal_proposal(
&manifest.blocks,
last_anchor_block_number,
input.taiko.batch_proposed.proposal_block_number() - 1,
anchor_max_offset,
) {
warn!(
"valid_anchor_in_proposal failed, last_anchor_block_number: {}",
last_anchor_block_number
);
return false;
}
if !validate_shasta_block_gas_limit(&manifest.blocks, &input.inputs) {
warn!("validate_shasta_block_gas_limit failed");
return false;
}
if !validate_shasta_manifest_block_timesatmp(&manifest.blocks, input) {
warn!("validate_shasta_block_timesatmp failed");
return false;
}
true
}
pub(crate) fn validate_force_inc_proposal_manifest(manifest: &DerivationSourceManifest) -> bool {
if manifest.blocks.len() != 1 {
warn!(
"validate_force_inc_proposal_manifest failed, manifest: {:?}",
manifest
);
return false;
}
true
}
pub(crate) fn validate_input_block_param(
manifest_block: &ProtocolBlockManifest,
input_block: &Block,
) -> bool {
if manifest_block.timestamp != input_block.header.timestamp {
warn!(
"manifest_block.timestamp != input_block.header.timestamp, manifest_block.timestamp: {}, input_block.header.timestamp: {}",
manifest_block.timestamp, input_block.header.timestamp
);
return false;
}
if manifest_block.coinbase != input_block.header.beneficiary {
warn!(
"manifest_block.coinbase != input_block.header.coinbase, manifest_block.coinbase: {}, input_block.header.coinbase: {}",
manifest_block.coinbase, input_block.header.beneficiary
);
return false;
}
if manifest_block.gas_limit + ANCHOR_V4_GAS_LIMIT != input_block.header.gas_limit {
warn!(
"manifest_block.gas_limit != input_block.header.gas_limit, manifest_block.gas_limit: {}, input_block.header.gas_limit: {}",
manifest_block.gas_limit, input_block.header.gas_limit
);
return false;
}
true
}
const BLOCK_GAS_LIMIT_MAX_CHANGE: u64 = 200;
const GAS_LIMIT_DENOMINATOR: u64 = 1_000_000;
const MAX_BLOCK_GAS_LIMIT: u64 = 45_000_000;
const MIN_BLOCK_GAS_LIMIT: u64 = 10_000_000;
/// validate gas limit for each block
pub fn validate_shasta_block_gas_limit(
manifest_blocks: &[ProtocolBlockManifest],
block_guest_inputs: &[GuestInput],
) -> bool {
let mut parent_gas_limit = if block_guest_inputs[0].parent_header.number == 0 {
block_guest_inputs[0].parent_header.gas_limit
} else {
block_guest_inputs[0].parent_header.gas_limit - ANCHOR_V4_GAS_LIMIT
};
for manifest_block in manifest_blocks.iter() {
let block_gas_limit: u64 = manifest_block.gas_limit;
let upper_limit: u64 = min(
MAX_BLOCK_GAS_LIMIT,
parent_gas_limit * (GAS_LIMIT_DENOMINATOR + BLOCK_GAS_LIMIT_MAX_CHANGE)
/ GAS_LIMIT_DENOMINATOR,
);
let lower_limit = min(
max(
MIN_BLOCK_GAS_LIMIT,
parent_gas_limit * (GAS_LIMIT_DENOMINATOR - BLOCK_GAS_LIMIT_MAX_CHANGE)
/ GAS_LIMIT_DENOMINATOR,
),
upper_limit,
);
if block_gas_limit < lower_limit || block_gas_limit > upper_limit {
info!("validate_shasta_block_gas_limit, parent_gas_limit: {}, block_gas_limit: {}, upper_limit: {}, lower_limit: {}", parent_gas_limit, block_gas_limit, upper_limit, lower_limit);
warn!("block gas limit is out of bounds, block_gas_limit: {}, lower_limit: {}, upper_limit: {}", block_gas_limit, lower_limit, upper_limit);
return false;
}
parent_gas_limit = block_gas_limit;
}
true
}
/// Timestamp max offset for Hoodi and non-mainnet (12 * 128).
const HOODI_TIMESTAMP_MAX_OFFSET: u64 = 12 * 128;
/// Timestamp max offset for Taiko mainnet (12 * 512).
const MAINNET_TIMESTAMP_MAX_OFFSET: u64 = 12 * 512;
/// Returns the maximum timestamp offset from proposal origin for the given chain ID.
/// Mainnet and Transition use 6144; Hoodi and other chains use 1536.
pub fn timestamp_max_offset_for_chain(chain_id: u64) -> u64 {
if is_mainnet_like_chain(chain_id) {
MAINNET_TIMESTAMP_MAX_OFFSET
} else {
HOODI_TIMESTAMP_MAX_OFFSET
}
}
/// validate timestamp for each block
// #### `timestamp` Validation
// Validates that block timestamps conform to the protocol rules. The 3rd party should set correct values
// according to these rules before calling this function:
// 1. **Upper bound validation**: `block.timestamp <= proposal.timestamp` must hold
// 2. **Lower bound calculation**: `lowerBound = max(parent.timestamp + 1, proposal.timestamp - TIMESTAMP_MAX_OFFSET)`
// 3. **Lower bound validation**: `block.timestamp >= lowerBound` must hold
pub fn validate_shasta_manifest_block_timesatmp(
blocks: &[ProtocolBlockManifest],
batch_guest_inputs: &GuestBatchInput,
) -> bool {
let block_guest_inputs = &batch_guest_inputs.inputs;
let proposal_timestamp = batch_guest_inputs.taiko.batch_proposed.proposal_timestamp();
let timestamp_max_offset =
timestamp_max_offset_for_chain(batch_guest_inputs.taiko.chain_spec.chain_id());
let shasta_fork_timestamp = match batch_guest_inputs
.taiko
.chain_spec
.hard_forks
.get(&SpecId::SHASTA)
{
Some(ForkCondition::Timestamp(timestamp)) => *timestamp,
_ => 0,
};
let mut parent_timestamp = block_guest_inputs[0].parent_header.timestamp;
for manifest_block in blocks.iter() {
let block_timestamp = manifest_block.timestamp;
// Upper bound validation: block.timestamp <= proposal.timestamp
if block_timestamp > proposal_timestamp {
warn!(
"Block timestamp {} exceeds proposal timestamp {}",
block_timestamp, proposal_timestamp
);
return false;
}
// Lower bound validation:
// Calculate lowerBound = max(parent.timestamp + 1, proposal.timestamp - timestamp_max_offset)
// Then validate: block.timestamp >= lowerBound
let lower_bound = std_max(
std_max(
parent_timestamp + 1,
proposal_timestamp.saturating_sub(timestamp_max_offset),
),
shasta_fork_timestamp,
);
if block_timestamp < lower_bound {
warn!(
"Block timestamp {} is less than calculated lower bound {}",
block_timestamp, lower_bound
);
return false;
}
parent_timestamp = block_timestamp;
}
true
}
pub(crate) fn clamp_timestamp_lower_bound(
parent_block_ts: u64,
proposal_ts: u64,
shasta_fork_timestamp: u64,
timestamp_max_offset: u64,
) -> u64 {
tracing::info!("clamp_timestamp_lower_bound, parent_block_ts: {}, proposal_ts: {}, shasta_fork_timestamp: {}, timestamp_max_offset: {}", parent_block_ts, proposal_ts, shasta_fork_timestamp, timestamp_max_offset);
let lower_bound = std_max(
parent_block_ts + 1,
proposal_ts.saturating_sub(timestamp_max_offset),
);
if lower_bound < shasta_fork_timestamp {
shasta_fork_timestamp
} else {
lower_bound
}
}
/// Block time target for EIP-4396 base fee calculation (2 seconds)
const BLOCK_TIME_TARGET: u64 = 2;
/// Maximum gas target percentage (95%)
const MAX_GAS_TARGET_TARGET_PERCENTAGE: u64 = 95;
/// Calculates the next base fee for Shasta blocks according to EIP-4396 logic.
/// Returns the next base fee given the parent block gas/fee parameters and protocol config.
/// The calculated value is clamped using the chain-specific minimum (see `min_base_fee_for_shasta_chain`).
fn calc_next_shasta_base_fee(
parent_gas_limit: u64,
parent_gas_used: u64,
parent_base_fee: u64,
parent_block_time: u64,
elasticity_multiplier: u64,
base_fee_change_denominator: u64,
min_base_fee: u64,
) -> u64 {
// Calculate parentGasTarget = parent.GasLimit / elasticity_multiplier
let parent_gas_target = parent_gas_limit / elasticity_multiplier;
// Calculate parentAdjustedGasTarget = min(
// parentGasTarget * parentBlockTime / blockTimeTarget,
// parent.GasLimit * maxGasTargetTargetPercentage / 100
// )
let adjusted_target_1 = parent_gas_target
.saturating_mul(parent_block_time)
.checked_div(BLOCK_TIME_TARGET)
.unwrap_or(0);
let adjusted_target_2 = parent_gas_limit
.saturating_mul(MAX_GAS_TARGET_TARGET_PERCENTAGE)
.checked_div(100)
.unwrap_or(0);
let parent_adjusted_gas_target = min(adjusted_target_1, adjusted_target_2);
// If the parent gasUsed is the same as the adjusted target, the baseFee remains unchanged.
if parent_gas_used == parent_adjusted_gas_target {
return clamp_shasta_base_fee_with_min(parent_base_fee, min_base_fee);
}
if parent_gas_used > parent_adjusted_gas_target {
// If the parent block used more gas than its target, the baseFee should increase.
// max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
let gas_used_delta = parent_gas_used - parent_adjusted_gas_target;
let adjustment = parent_base_fee
.saturating_mul(gas_used_delta)
.checked_div(parent_gas_target)
.unwrap_or(0)
.checked_div(base_fee_change_denominator)
.unwrap_or(0);
if adjustment < 1 {
return clamp_shasta_base_fee_with_min(parent_base_fee.saturating_add(1), min_base_fee);
}
clamp_shasta_base_fee_with_min(parent_base_fee.saturating_add(adjustment), min_base_fee)
} else {
// Otherwise if the parent block used less gas than its target, the baseFee should decrease.
// max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
let gas_used_delta = parent_adjusted_gas_target - parent_gas_used;
let adjustment = parent_base_fee
.saturating_mul(gas_used_delta)
.checked_div(parent_gas_target)
.unwrap_or(0)
.checked_div(base_fee_change_denominator)
.unwrap_or(0);
let base_fee = parent_base_fee.saturating_sub(adjustment);
// If baseFee < 0, set it to 0 (handled by saturating_sub, but we check explicitly)
let base_fee = if base_fee > parent_base_fee {
0
} else {
base_fee
};
clamp_shasta_base_fee_with_min(base_fee, min_base_fee)
}
}
/// Minimum allowed base fee for Shasta blocks on non-mainnet chains (0.005 Gwei)
pub const MIN_BASE_FEE_SHASTA: u64 = 5_000_000;
/// Minimum allowed base fee for Shasta blocks on Taiko mainnet (0.01 Gwei)
pub const MAINNET_MIN_BASE_FEE_SHASTA: u64 = 10_000_000;
/// Maximum allowed base fee for Shasta blocks (1 Gwei)
pub const MAX_BASE_FEE_SHASTA: u64 = 1_000_000_000;
/// Taiko mainnet chain ID (EIP-4396 min base fee uses MAINNET_MIN_BASE_FEE_SHASTA)
pub const TAIKO_MAINNET_CHAIN_ID: u64 = 167000;
/// Taiko transition network chain ID (uses mainnet-like parameters)
pub const TAIKO_TRANSITION_CHAIN_ID: u64 = 167014;
/// Returns true if the chain uses mainnet-like parameters (anchor offset 512, timestamp offset 6144, min base fee 0.01 gwei).
fn is_mainnet_like_chain(chain_id: u64) -> bool {
chain_id == TAIKO_MAINNET_CHAIN_ID || chain_id == TAIKO_TRANSITION_CHAIN_ID
}
/// Returns the minimum base fee (inclusive) for Shasta blocks for the given chain ID.
/// Mainnet and Transition use 0.01 gwei; all other chains use 0.005 gwei.
pub fn min_base_fee_for_shasta_chain(chain_id: u64) -> u64 {
if is_mainnet_like_chain(chain_id) {
MAINNET_MIN_BASE_FEE_SHASTA
} else {
MIN_BASE_FEE_SHASTA
}
}
/// Clamp the provided base fee to the given minimum and max allowed for Shasta blocks.
fn clamp_shasta_base_fee_with_min(base_fee: u64, min_base_fee: u64) -> u64 {
let effective_min = min(min_base_fee, MAX_BASE_FEE_SHASTA);
base_fee.clamp(effective_min, MAX_BASE_FEE_SHASTA)
}
/// Bounds the amount the base fee can change between blocks.
pub const DEFAULT_BASE_FEE_CHANGE_DENOMINATOR: u64 = 8;
/// Bounds the maximum gas limit an EIP-1559 block may have.
pub const DEFAULT_ELASTICITY_MULTIPLIER: u64 = 2;
/// Initial base fee for EIP-1559 blocks.
pub const INITIAL_BASE_FEE: u64 = 1_000_000_000;
/// CHANGE(taiko): add ShastaInitialBaseFee for Shasta fork.
pub const SHASTA_INITIAL_BASE_FEE: u64 = 25_000_000;
fn parent_block_time_from_grandparent(
parent: &Header,
l2_grandparent_header: Option<&Header>,
) -> Option<u64> {
if parent.number == 0 {
return Some(BLOCK_TIME_TARGET);
}
let Some(grandparent) = l2_grandparent_header else {
warn!(
"missing L2 grandparent header for parent block {}",
parent.number
);
return None;
};
if grandparent.number + 1 != parent.number {
warn!(
"L2 grandparent number mismatch: grandparent {}, parent {}",
grandparent.number, parent.number
);
return None;
}
let grandparent_hash = grandparent.hash_slow();
if grandparent_hash != parent.parent_hash {
warn!(
"L2 grandparent hash mismatch: expected {}, found {}",
parent.parent_hash, grandparent_hash
);
return None;
}
Some(parent.timestamp.saturating_sub(grandparent.timestamp))
}
pub fn validate_shasta_block_base_fee(
block_guest_inputs: &[GuestInput],
use_init_base_fee: bool,
l2_grandparent_header: Option<&Header>,
min_base_fee: u64,
) -> bool {
if use_init_base_fee {
if block_guest_inputs[0].block.header.base_fee_per_gas != Some(SHASTA_INITIAL_BASE_FEE) {
tracing::warn!(
"shasta block base fee is invalid, expected: {}, found: {}",
SHASTA_INITIAL_BASE_FEE,
block_guest_inputs[0].block.header.base_fee_per_gas.unwrap()
);
return false;
}
} else {
// Calculate parent_block_time = parent.timestamp - grandparent.timestamp
// According to EIP-4396, we need the time between parent and grandparent
let Some(parent_block_time) = parent_block_time_from_grandparent(
&block_guest_inputs[0].parent_header,
l2_grandparent_header,
) else {
return false;
};
let first_block_base_fee = calc_next_shasta_base_fee(
block_guest_inputs[0].parent_header.gas_limit,
block_guest_inputs[0].parent_header.gas_used,
block_guest_inputs[0]
.parent_header
.base_fee_per_gas
.unwrap(),
parent_block_time,
DEFAULT_ELASTICITY_MULTIPLIER,
DEFAULT_BASE_FEE_CHANGE_DENOMINATOR,
min_base_fee,
);
if first_block_base_fee != block_guest_inputs[0].block.header.base_fee_per_gas.unwrap() {
warn!(
"first_block_base_fee mismatch: expected {}, found {}",
first_block_base_fee,
block_guest_inputs[0].block.header.base_fee_per_gas.unwrap()
);
return false;
}
}
// Check that each block's base fee matches the calculated next base fee
for i in 1..block_guest_inputs.len() {
let block = &block_guest_inputs[i].block;
let actual_base_fee = block.header.base_fee_per_gas.unwrap();
// Determine the base fee used for the calculation
let prev_base_fee = block_guest_inputs[i - 1]
.block
.header
.base_fee_per_gas
.unwrap();
// Calculate parent_block_time for this block
// parent = block[i-1], parent's parent = block[i-1].parent_header
// parent_block_time = parent.timestamp - parent(parent).timestamp
let parent_block_time = block_guest_inputs[i - 1]
.block
.header
.timestamp
.saturating_sub(block_guest_inputs[i - 1].parent_header.timestamp);
// Use the canonical calculator function for base fee
let expected_base_fee = calc_next_shasta_base_fee(
block_guest_inputs[i - 1].block.header.gas_limit,
block_guest_inputs[i - 1].block.header.gas_used,
prev_base_fee,
parent_block_time,
DEFAULT_ELASTICITY_MULTIPLIER,
DEFAULT_BASE_FEE_CHANGE_DENOMINATOR,
min_base_fee,
);
if expected_base_fee != actual_base_fee {
warn!(
"Block basefee mismatch at idx {}: expected {}, found {}",
i, expected_base_fee, actual_base_fee
);
return false;
}
}
true
}
#[cfg(test)]
mod tests {
use super::{
valid_anchor_in_normal_proposal, validate_force_inc_proposal_manifest,
validate_shasta_manifest_block_timesatmp,
};
use crate::consts::{ChainSpec, ForkCondition};
use crate::input::{
shasta::{BlobSlice, DerivationSource, Proposal, ShastaEventData},
BlockProposedFork, GuestBatchInput, GuestInput, TaikoGuestBatchInput,
};
use crate::manifest::{DerivationSourceManifest, ProtocolBlockManifest};
use alloy_primitives::B256;
use reth_primitives::revm_primitives::SpecId;
use reth_primitives::Header;
use std::collections::BTreeMap;
use super::calc_next_shasta_base_fee;
fn base_fee_guest_input(parent_header: Header, block_base_fee: u64) -> GuestInput {
let mut input = GuestInput {
parent_header,
..Default::default()
};
input.block.header.base_fee_per_gas = Some(block_base_fee);
input
}
#[test]
fn test_calc_next_shasta_base_fee() {
let parent_gas_limit = 16_000_000;
let parent_gas_used = 15_956_512;
let parent_base_fee = 5_000_000;
let parent_block_time = 240;
let elasticity_multiplier = 2;
let base_fee_change_denominator = 8;
let result = calc_next_shasta_base_fee(
parent_gas_limit,
parent_gas_used,
parent_base_fee,
parent_block_time,
elasticity_multiplier,
base_fee_change_denominator,
super::MIN_BASE_FEE_SHASTA,
);
// Verify the result is within valid bounds
assert!(
result >= super::MIN_BASE_FEE_SHASTA,
"Result {} is below minimum base fee {}",
result,
super::MIN_BASE_FEE_SHASTA
);
assert!(
result <= super::MAX_BASE_FEE_SHASTA,
"Result {} exceeds maximum base fee {}",
result,
super::MAX_BASE_FEE_SHASTA
);
assert_eq!(result, 5_059_102);
}
#[test]
fn test_base_fee_rejects_missing_grandparent_for_non_genesis_parent() {
let parent_header = Header {
number: 10,
timestamp: 100,
gas_limit: 16_000_000,
gas_used: 15_000_000,
base_fee_per_gas: Some(5_000_000),
..Default::default()
};
let default_time_base_fee = calc_next_shasta_base_fee(
parent_header.gas_limit,
parent_header.gas_used,
parent_header.base_fee_per_gas.unwrap(),
super::BLOCK_TIME_TARGET,
super::DEFAULT_ELASTICITY_MULTIPLIER,
super::DEFAULT_BASE_FEE_CHANGE_DENOMINATOR,
super::MIN_BASE_FEE_SHASTA,
);
let input = base_fee_guest_input(parent_header, default_time_base_fee);
assert!(!super::validate_shasta_block_base_fee(
&[input],
false,
None,
super::MIN_BASE_FEE_SHASTA,
));
}
#[test]
fn test_base_fee_rejects_unlinked_grandparent() {
let grandparent = Header {
number: 9,
timestamp: 98,
..Default::default()
};
let parent_header = Header {
number: 10,
timestamp: 100,
gas_limit: 16_000_000,
gas_used: 15_000_000,
base_fee_per_gas: Some(5_000_000),
parent_hash: B256::repeat_byte(0x42),
..Default::default()
};
let grandparent_time_base_fee = calc_next_shasta_base_fee(
parent_header.gas_limit,
parent_header.gas_used,
parent_header.base_fee_per_gas.unwrap(),
parent_header.timestamp - grandparent.timestamp,
super::DEFAULT_ELASTICITY_MULTIPLIER,
super::DEFAULT_BASE_FEE_CHANGE_DENOMINATOR,
super::MIN_BASE_FEE_SHASTA,
);
let input = base_fee_guest_input(parent_header, grandparent_time_base_fee);
assert!(!super::validate_shasta_block_base_fee(
&[input],
false,
Some(&grandparent),
super::MIN_BASE_FEE_SHASTA,
));
}
#[test]
fn test_anchor_range_includes_max_offset() {
let l1_header_number = 1000u64;
let last_anchor_block_number = 871u64; // min_anchor - 1
let blocks = vec![ProtocolBlockManifest {
anchor_block_number: 872u64, // 1000 - 128
..Default::default()
}];
assert!(valid_anchor_in_normal_proposal(
&blocks,
last_anchor_block_number,
l1_header_number,
super::ANCHOR_MAX_OFFSET as u64,
));
}
#[test]
fn test_anchor_regression_is_invalid() {
let l1_header_number = 1000u64;
let last_anchor_block_number = 900u64;
let blocks = vec![ProtocolBlockManifest {
anchor_block_number: 899u64,
..Default::default()
}];
assert!(!valid_anchor_in_normal_proposal(
&blocks,
last_anchor_block_number,
l1_header_number,
super::ANCHOR_MAX_OFFSET as u64,
));
}
#[test]
fn test_force_inclusion_manifest_accepts_non_zero_fields() {
let manifest = DerivationSourceManifest {
blocks: vec![ProtocolBlockManifest {
timestamp: 123,
coinbase: Default::default(),
anchor_block_number: 456,
gas_limit: 789,
transactions: vec![],
}],
};
assert!(validate_force_inc_proposal_manifest(&manifest));
}
#[test]
fn test_timestamp_validation_enforces_shasta_fork_time() {
let mut chain_spec = ChainSpec::new_single(
"test".to_string(),
1u64.into(),
SpecId::SHASTA,
Default::default(),
true,
);
chain_spec.hard_forks = BTreeMap::from([(SpecId::SHASTA, ForkCondition::Timestamp(150))]);
let proposal = Proposal {
timestamp: 200,
originBlockNumber: 100,
sources: vec![DerivationSource {
isForcedInclusion: false,
blobSlice: BlobSlice {
blobHashes: vec![B256::ZERO],
offset: 0,
timestamp: 0,
},
}],
..Default::default()
};
let event_data = ShastaEventData { proposal };
let guest_input = GuestInput {
parent_header: Header {
timestamp: 90,
..Default::default()
},
..Default::default()
};
let batch_input = GuestBatchInput {
inputs: vec![guest_input],
taiko: TaikoGuestBatchInput {
batch_proposed: BlockProposedFork::Shasta(event_data),
chain_spec,
..Default::default()
},
};
let blocks = vec![ProtocolBlockManifest {
timestamp: 120, // above parent+1 but below SHASTA fork time
..Default::default()
}];
assert!(!validate_shasta_manifest_block_timesatmp(
&blocks,
&batch_input
));
}
}