forked from ethereum-optimism/optimism
-
Notifications
You must be signed in to change notification settings - Fork 4
/
FaultDisputeGameN.sol
1251 lines (1058 loc) · 57.8 KB
/
FaultDisputeGameN.sol
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
import { FixedPointMathLib } from "@solady/utils/FixedPointMathLib.sol";
import { IDelayedWETH } from "src/dispute/interfaces/IDelayedWETH.sol";
import { IDisputeGame } from "src/dispute/interfaces/IDisputeGame.sol";
import { IFaultDisputeGame } from "src/dispute/interfaces/IFaultDisputeGame.sol";
import { IInitializable } from "src/dispute/interfaces/IInitializable.sol";
import { IBigStepper, IPreimageOracle } from "src/dispute/interfaces/IBigStepper.sol";
import { IAnchorStateRegistry } from "src/dispute/interfaces/IAnchorStateRegistry.sol";
import { Clone } from "@solady/utils/Clone.sol";
import { Types } from "src/libraries/Types.sol";
import { ISemver } from "src/universal/ISemver.sol";
import { Types } from "src/libraries/Types.sol";
import { Hashing } from "src/libraries/Hashing.sol";
import { RLPReader } from "src/libraries/rlp/RLPReader.sol";
import "src/dispute/lib/Types.sol";
import "src/dispute/lib/Errors.sol";
import "src/dispute/lib/LibDA.sol";
/// @notice Thrown when an attempt is made to submit an incorrect position
error InvalidPosition();
/// @notice Thrown when an attempt is made to call a method that is no longer supported
error NotSupported();
/// @title FaultDisputeGame
/// @notice An implementation of the `IFaultDisputeGame` interface.
contract FaultDisputeGame is IFaultDisputeGame, Clone, ISemver {
////////////////////////////////////////////////////////////////
// State Vars //
////////////////////////////////////////////////////////////////
/// @notice The absolute prestate of the instruction trace. This is a constant that is defined
/// by the program that is being used to execute the trace.
Claim internal immutable ABSOLUTE_PRESTATE;
/// @notice The max depth of the game.
uint256 internal immutable MAX_GAME_DEPTH;
/// @notice The max depth of the output bisection portion of the position tree. Immediately beneath
/// this depth, execution trace bisection begins.
uint256 internal immutable SPLIT_DEPTH;
/// @notice The maximum duration that may accumulate on a team's chess clock before they may no longer respond.
Duration internal immutable MAX_CLOCK_DURATION;
/// @notice An onchain VM that performs single instruction steps on a fault proof program trace.
IBigStepper internal immutable VM;
/// @notice The game type ID.
GameType internal immutable GAME_TYPE;
/// @notice WETH contract for holding ETH.
IDelayedWETH internal immutable WETH;
/// @notice The anchor state registry.
IAnchorStateRegistry internal immutable ANCHOR_STATE_REGISTRY;
/// @notice The chain ID of the L2 network this contract argues about.
uint256 internal immutable L2_CHAIN_ID;
/// @notice The duration of the clock extension. Will be doubled if the grandchild is the root claim of an execution
/// trace bisection subgame.
Duration internal immutable CLOCK_EXTENSION;
/// @notice The global root claim's position is always at gindex 1.
Position internal constant ROOT_POSITION = Position.wrap(1);
/// @notice The index of the block number in the RLP-encoded block header.
/// @dev Consensus encoding reference:
/// https://github.com/paradigmxyz/reth/blob/5f82993c23164ce8ccdc7bf3ae5085205383a5c8/crates/primitives/src/header.rs#L368
uint256 internal constant HEADER_BLOCK_NUMBER_INDEX = 8;
/// @notice Semantic version.
/// @custom:semver 1.2.0
string public constant version = "1.2.0";
/// @notice The starting timestamp of the game
Timestamp public createdAt;
/// @notice The timestamp of the game's global resolution.
Timestamp public resolvedAt;
/// @inheritdoc IDisputeGame
GameStatus public status;
/// @notice Flag for the `initialize` function to prevent re-initialization.
bool internal initialized;
/// @notice Bits of N-ary search
uint256 public immutable N_BITS;
/// @notice Bits of N-ary search
uint256 public immutable MAX_ATTACK_BRANCH;
/// @notice Flag for whether or not the L2 block number claim has been invalidated via `challengeRootL2Block`.
bool public l2BlockNumberChallenged;
/// @notice The challenger of the L2 block number claim. Should always be `address(0)` if `l2BlockNumberChallenged`
/// is `false`. Should be the address of the challenger if `l2BlockNumberChallenged` is `true`.
address public l2BlockNumberChallenger;
/// @notice An append-only array of all claims made during the dispute game.
ClaimData[] public claimData;
/// @notice Credited balances for winning participants.
mapping(address => uint256) public credit;
/// @notice A mapping to allow for constant-time lookups of existing claims.
mapping(Hash => bool) public claims;
/// @notice A mapping of subgames rooted at a claim index to other claim indices in the subgame.
mapping(uint256 => uint256[]) public subgames;
/// @notice A mapping of resolved subgames rooted at a claim index.
mapping(uint256 => bool) public resolvedSubgames;
/// @notice A mapping of claim indices to resolution checkpoints.
mapping(uint256 => ResolutionCheckpoint) public resolutionCheckpoints;
/// @notice The latest finalized output root, serving as the anchor for output bisection.
OutputRoot public startingOutputRoot;
/// @param _gameType The type ID of the game.
/// @param _absolutePrestate The absolute prestate of the instruction trace.
/// @param _maxGameDepth The maximum depth of bisection.
/// @param _splitDepth The final depth of the output bisection portion of the game.
/// @param _clockExtension The clock extension to perform when the remaining duration is less than the extension.
/// @param _maxClockDuration The maximum amount of time that may accumulate on a team's chess clock.
/// @param _vm An onchain VM that performs single instruction steps on an FPP trace.
/// @param _weth WETH contract for holding ETH.
/// @param _anchorStateRegistry The contract that stores the anchor state for each game type.
/// @param _l2ChainId Chain ID of the L2 network this contract argues about.
constructor(
GameType _gameType,
Claim _absolutePrestate,
uint256 _maxGameDepth,
uint256 _splitDepth,
Duration _clockExtension,
Duration _maxClockDuration,
IBigStepper _vm,
IDelayedWETH _weth,
IAnchorStateRegistry _anchorStateRegistry,
uint256 _l2ChainId
) {
// The max game depth may not be greater than `LibPosition.MAX_POSITION_BITLEN - 1`.
if (_maxGameDepth > LibPosition.MAX_POSITION_BITLEN - 1) revert MaxDepthTooLarge();
// The split depth cannot be greater than or equal to the max game depth.
if (_splitDepth >= _maxGameDepth) revert InvalidSplitDepth();
// The clock extension may not be greater than the max clock duration.
if (_clockExtension.raw() > _maxClockDuration.raw()) revert InvalidClockExtension();
GAME_TYPE = _gameType;
ABSOLUTE_PRESTATE = _absolutePrestate;
MAX_GAME_DEPTH = _maxGameDepth;
SPLIT_DEPTH = _splitDepth;
CLOCK_EXTENSION = _clockExtension;
MAX_CLOCK_DURATION = _maxClockDuration;
VM = _vm;
WETH = _weth;
ANCHOR_STATE_REGISTRY = _anchorStateRegistry;
L2_CHAIN_ID = _l2ChainId;
// N_BITS ** 2 = N-ary
N_BITS = 2;
MAX_ATTACK_BRANCH = (1 << N_BITS) - 1;
}
/// @inheritdoc IInitializable
function initialize() public payable virtual {
// SAFETY: Any revert in this function will bubble up to the DisputeGameFactory and
// prevent the game from being created.
//
// Implicit assumptions:
// - The `gameStatus` state variable defaults to 0, which is `GameStatus.IN_PROGRESS`
// - The dispute game factory will enforce the required bond to initialize the game.
//
// Explicit checks:
// - The game must not have already been initialized.
// - An output root cannot be proposed at or before the starting block number.
// INVARIANT: The game must not have already been initialized.
if (initialized) revert AlreadyInitialized();
// Grab the latest anchor root.
(Hash root, uint256 rootBlockNumber) = ANCHOR_STATE_REGISTRY.anchors(GAME_TYPE);
// Should only happen if this is a new game type that hasn't been set up yet.
if (root.raw() == bytes32(0)) revert AnchorRootNotFound();
// Set the starting output root.
startingOutputRoot = OutputRoot({ l2BlockNumber: rootBlockNumber, root: root });
// Revert if the calldata size is not the expected length.
//
// This is to prevent adding extra or omitting bytes from to `extraData` that result in a different game UUID
// in the factory, but are not used by the game, which would allow for multiple dispute games for the same
// output proposal to be created.
//
// Expected length: 0x7A
// - 0x04 selector
// - 0x14 creator address
// - 0x20 root claim
// - 0x20 l1 head
// - 0x20 extraData
// - 0x02 CWIA bytes
assembly {
if iszero(eq(calldatasize(), 0x7A)) {
// Store the selector for `BadExtraData()` & revert
mstore(0x00, 0x9824bdab)
revert(0x1C, 0x04)
}
}
// Do not allow the game to be initialized if the root claim corresponds to a block at or before the
// configured starting block number.
if (l2BlockNumber() <= rootBlockNumber) revert UnexpectedRootClaim(rootClaim());
// Set the root claim
claimData.push(
ClaimData({
parentIndex: type(uint32).max,
counteredBy: address(0),
claimant: gameCreator(),
bond: uint128(msg.value),
claim: rootClaim(),
position: ROOT_POSITION,
clock: LibClock.wrap(Duration.wrap(0), Timestamp.wrap(uint64(block.timestamp)))
})
);
// Set the game as initialized.
initialized = true;
require(
SPLIT_DEPTH % N_BITS == 0 && MAX_GAME_DEPTH % N_BITS == 0,
"SPLIT_DEPTH and MAX_GAME_DEPTH must be multiples of N_BITS"
);
// Deposit the bond.
WETH.deposit{ value: msg.value }();
// Set the game's starting timestamp
createdAt = Timestamp.wrap(uint64(block.timestamp));
}
////////////////////////////////////////////////////////////////
// `IFaultDisputeGame` impl //
////////////////////////////////////////////////////////////////
/// @notice Represents the proofs to verify preState/postState and transition in stepV2().
/// @custom:field preStateItem preState with its proof from DA.
/// @custom:field postStateItem postState with its proof from DA.
/// @custom:field vmProof Proof for VM step.
struct StepProof {
LibDA.DAItem preStateItem;
LibDA.DAItem postStateItem;
bytes vmProof;
}
function stepV2(
uint256 _claimIndex,
uint256 _attackBranch,
bytes calldata _stateData,
StepProof calldata _proof
)
public
virtual
{
require(_attackBranch <= MAX_ATTACK_BRANCH);
// INVARIANT: Steps cannot be made unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
// Get the parent. If it does not exist, the call will revert with OOB.
ClaimData storage parent = claimData[_claimIndex];
// Pull the parent position out of storage.
Position parentPos = parent.position;
// INVARIANT: A step cannot be made unless the move position is 1 below the `MAX_GAME_DEPTH`
if (parentPos.depth() != MAX_GAME_DEPTH) revert InvalidParent();
// Determine the expected pre & post states of the step.
Claim preStateClaim;
Claim postStateClaim;
Position postStatePos;
if (MAX_ATTACK_BRANCH != _attackBranch) {
uint256 claimIndex = _claimIndex;
Position preStatePos;
// If the step position's index at depth is 0, the prestate is the absolute
// prestate.
// If the step is an attack at a trace index > 0, the prestate exists elsewhere in
// the game state.
// NOTE: We localize the `indexAtDepth` for the current execution trace subgame by finding
// the remainder of the index at depth divided by 2 ** (MAX_GAME_DEPTH - SPLIT_DEPTH),
// which is the number of leaves in each execution trace subgame. This is so that we can
// determine whether or not the step position is represents the `ABSOLUTE_PRESTATE`.
// Determine the position of the step.
Position stepPos = parentPos.moveN(N_BITS, uint128(_attackBranch));
if (stepPos.indexAtDepth() % (1 << (MAX_GAME_DEPTH - SPLIT_DEPTH)) == 0) {
preStateClaim = ABSOLUTE_PRESTATE;
} else {
(preStateClaim, preStatePos) = _findTraceAncestorV2(
Position.wrap(parentPos.raw() - 1 + uint128(_attackBranch)), claimIndex, false, _proof.preStateItem
);
}
// For all attacks, the poststate is the parent claim.
postStatePos = Position.wrap(parent.position.raw() + uint128(_attackBranch));
postStateClaim = getClaim(parent.claim.raw(), postStatePos, _proof.postStateItem);
} else {
uint256 claimIndex = _claimIndex;
Position preStatePos;
// If the step is a defense, the poststate exists elsewhere in the game state,
// and the parent claim is the expected pre-state.
preStatePos = Position.wrap(parent.position.raw() + uint128(_attackBranch) - 1);
preStateClaim = getClaim(parent.claim.raw(), preStatePos, _proof.preStateItem);
(postStateClaim, postStatePos) =
_findExecTraceAncestor(Position.wrap(parentPos.raw() + uint128(_attackBranch)), claimIndex, _proof.postStateItem);
}
// INVARIANT: The prestate is always invalid if the passed `_stateData` is not the
// preimage of the prestate claim hash.
// We ignore the highest order byte of the digest because it is used to
// indicate the VM Status and is added after the digest is computed.
if (keccak256(_stateData) << 8 != preStateClaim.raw() << 8) revert InvalidPrestate();
// Compute the local preimage context for the step.
Hash uuid = _findLocalContext(_claimIndex);
// INVARIANT: If a step is an attack, the poststate is valid if the step produces
// the same poststate hash as the parent claim's value.
// If a step is a defense:
// 1. If the parent claim and the found post state agree with each other
// (depth diff % 2 == 0), the step is valid if it produces the same
// state hash as the post state's claim.
// 2. If the parent claim and the found post state disagree with each other
// (depth diff % 2 != 0), the parent cannot be countered unless the step
// produces the same state hash as `postState.claim`.
// SAFETY: While the `attack` path does not need an extra check for the post
// state's depth in relation to the parent, we don't need another
// branch because (n - n) % 2 == 0.
bool validStep = VM.step(_stateData, _proof.vmProof, uuid.raw()) == postStateClaim.raw();
bool parentPostAgree = ((parentPos.depth() - postStatePos.depth()) / N_BITS) % 2 == 0;
if (parentPostAgree == validStep) revert ValidStep();
// INVARIANT: A step cannot be made against a claim for a second time.
if (parent.counteredBy != address(0)) revert DuplicateStep();
// Set the parent claim as countered. We do not need to append a new claim to the game;
// instead, we can just set the existing parent as countered.
parent.counteredBy = msg.sender;
}
function moveV2(Claim _disputed, uint256 _challengeIndex, Claim _claim, uint256 _attackBranch) internal {
// For N = 4 (bisec),
// 1. _attackBranch == 0 (attack)
// 2. _attackBranch == 1 (attack)
// 3. _attackBranch == 2 (attack)
// 4. _attackBranch == 3 (defend)
require(_attackBranch <= MAX_ATTACK_BRANCH);
// INVARIANT: Moves cannot be made unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
// Get the parent. If it does not exist, the call will revert with OOB.
ClaimData memory parent = claimData[_challengeIndex];
// INVARIANT: The claim at the _challengeIndex must be the disputed claim.
if (Claim.unwrap(parent.claim) != Claim.unwrap(_disputed)) revert InvalidDisputedClaimIndex();
// Compute the position that the claim commits to. Because the parent's position is already
// known, we can compute the next position by moving left or right depending on whether
// or not the move is an attack or defense.
Position parentPos = parent.position;
Position nextPosition = parentPos.moveN(N_BITS, _attackBranch);
uint256 nextPositionDepth = nextPosition.depth();
// INVARIANT: A defense can never be made against the root claim of either the output root game or any
// of the execution trace bisection subgames. This is because the root claim commits to the
// entire state. Therefore, the only valid defense is to do nothing if it is agreed with.
if ((_challengeIndex == 0 || nextPositionDepth == SPLIT_DEPTH + 2 * N_BITS) && 0 != _attackBranch) {
revert CannotDefendRootClaim();
}
// INVARIANT: No moves against the root claim can be made after it has been challenged with
// `challengeRootL2Block`.`
if (l2BlockNumberChallenged && _challengeIndex == 0) revert L2BlockNumberChallenged();
// INVARIANT: A move can never surpass the `MAX_GAME_DEPTH`. The only option to counter a
// claim at this depth is to perform a single instruction step on-chain via
// the `step` function to prove that the state transition produces an unexpected
// post-state.
if (nextPositionDepth > MAX_GAME_DEPTH) revert GameDepthExceeded();
// When the next position surpasses the split depth (i.e., it is the root claim of an execution
// trace bisection sub-game), we need to perform some extra verification steps.
if (nextPositionDepth == SPLIT_DEPTH + N_BITS) {
_verifyExecMultisectionRoot(_claim, _challengeIndex, parentPos, _attackBranch);
}
// INVARIANT: The `msg.value` must exactly equal the required bond.
if (getRequiredBond(nextPosition) != msg.value) revert IncorrectBondAmount();
// Compute the duration of the next clock. This is done by adding the duration of the
// grandparent claim to the difference between the current block timestamp and the
// parent's clock timestamp.
Duration nextDuration = getChallengerDuration(_challengeIndex);
// INVARIANT: A move can never be made once its clock has exceeded `MAX_CLOCK_DURATION`
// seconds of time.
if (nextDuration.raw() == MAX_CLOCK_DURATION.raw()) revert ClockTimeExceeded();
// If the remaining clock time has less than `CLOCK_EXTENSION` seconds remaining, grant the potential
// grandchild's clock `CLOCK_EXTENSION` seconds. This is to ensure that, even if a player has to inherit another
// team's clock to counter a freeloader claim, they will always have enough time to to respond. This extension
// is bounded by the depth of the tree. If the potential grandchild is an execution trace bisection root, the
// clock extension is doubled. This is to allow for extra time for the off-chain challenge agent to generate
// the initial instruction trace on the native FPVM.
if (nextDuration.raw() > MAX_CLOCK_DURATION.raw() - CLOCK_EXTENSION.raw()) {
// If the potential grandchild is an execution trace bisection root, double the clock extension.
uint64 extensionPeriod =
nextPositionDepth == SPLIT_DEPTH - N_BITS ? CLOCK_EXTENSION.raw() * 2 : CLOCK_EXTENSION.raw();
nextDuration = Duration.wrap(MAX_CLOCK_DURATION.raw() - extensionPeriod);
}
// Construct the next clock with the new duration and the current block timestamp.
Clock nextClock = LibClock.wrap(nextDuration, Timestamp.wrap(uint64(block.timestamp)));
// INVARIANT: There cannot be multiple identical claims with identical moves on the same challengeIndex. Multiple
// claims at the same position may dispute the same challengeIndex. However, they must have different
// values.
Hash claimHash = _claim.hashClaimPos(nextPosition, _challengeIndex);
if (claims[claimHash]) revert ClaimAlreadyExists();
claims[claimHash] = true;
// Create the new claim.
claimData.push(
ClaimData({
parentIndex: uint32(_challengeIndex),
// This is updated during subgame resolution
counteredBy: address(0),
claimant: msg.sender,
bond: uint128(msg.value),
claim: _claim,
position: nextPosition,
clock: nextClock
})
);
// Update the subgame rooted at the parent claim.
subgames[_challengeIndex].push(claimData.length - 1);
// Deposit the bond.
WETH.deposit{ value: msg.value }();
// Emit the appropriate event for the attack or defense.
emit Move(_challengeIndex, _claim, msg.sender);
}
/// @inheritdoc IFaultDisputeGame
function attack(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
revert NotSupported();
//move(_disputed, _parentIndex, _claim, true);
}
/// @inheritdoc IFaultDisputeGame
function defend(Claim _disputed, uint256 _parentIndex, Claim _claim) external payable {
revert NotSupported();
//move(_disputed, _parentIndex, _claim, false);
}
/// @inheritdoc IFaultDisputeGame
function addLocalData(uint256 _ident, uint256 _execLeafIdx, uint256 _partOffset) external {
revert NotSupported();
}
function addLocalData(
uint256 _ident,
uint256 _execLeafIdx,
uint256 _partOffset,
LibDA.DAItem memory _daItem
)
external
returns (Hash uuid_, bytes32 value_)
{
// INVARIANT: Local data can only be added if the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
(Claim startingRoot, Position startingPos, Claim disputedRoot, Position disputedPos) =
_findStartingAndDisputedOutputRoots(_execLeafIdx);
uuid_ = _computeLocalContext(startingRoot, startingPos, disputedRoot, disputedPos);
IPreimageOracle oracle = VM.oracle();
if (_ident == LocalPreimageKey.L1_HEAD_HASH) {
// Load the L1 head hash
oracle.loadLocalData(_ident, uuid_.raw(), l1Head().raw(), 32, _partOffset);
value_ = l1Head().raw();
} else if (_ident == LocalPreimageKey.STARTING_OUTPUT_ROOT) {
// Load the starting proposal's output root.
Claim starting;
// If the pos is 0, then the root itself is the output hash.
if (startingPos.raw() == 0) {
starting = startingRoot;
} else {
starting = getClaim(startingRoot.raw(), startingPos, _daItem);
}
oracle.loadLocalData(_ident, uuid_.raw(), starting.raw(), 32, _partOffset);
value_ = starting.raw();
} else if (_ident == LocalPreimageKey.DISPUTED_OUTPUT_ROOT) {
// Load the disputed proposal's output root
Claim disputed;
// If the pos is 1, then the rootclaim itself is the output hash.
if (disputedPos.raw() == 1) {
disputed = disputedRoot;
} else {
disputed = getClaim(disputedRoot.raw(), disputedPos, _daItem);
}
oracle.loadLocalData(_ident, uuid_.raw(), disputed.raw(), 32, _partOffset);
value_ = disputed.raw();
} else if (_ident == LocalPreimageKey.DISPUTED_L2_BLOCK_NUMBER) {
// Load the disputed proposal's L2 block number as a big-endian uint64 in the
// high order 8 bytes of the word.
// We add the index at depth + 1 to the starting block number to get the disputed L2
// block number.
uint256 l2Number = startingOutputRoot.l2BlockNumber + disputedPos.traceIndex(SPLIT_DEPTH) + 1;
oracle.loadLocalData(_ident, uuid_.raw(), bytes32(l2Number << 0xC0), 8, _partOffset);
value_ = bytes32(l2Number << 0xC0);
} else if (_ident == LocalPreimageKey.CHAIN_ID) {
// Load the chain ID as a big-endian uint64 in the high order 8 bytes of the word.
oracle.loadLocalData(_ident, uuid_.raw(), bytes32(L2_CHAIN_ID << 0xC0), 8, _partOffset);
value_ = bytes32(L2_CHAIN_ID << 0xC0);
} else {
revert InvalidLocalIdent();
}
}
/// @inheritdoc IFaultDisputeGame
function getNumToResolve(uint256 _claimIndex) public view returns (uint256 numRemainingChildren_) {
ResolutionCheckpoint storage checkpoint = resolutionCheckpoints[_claimIndex];
uint256[] storage challengeIndices = subgames[_claimIndex];
uint256 challengeIndicesLen = challengeIndices.length;
numRemainingChildren_ = challengeIndicesLen - checkpoint.subgameIndex;
}
/// @inheritdoc IFaultDisputeGame
function l2BlockNumber() public pure returns (uint256 l2BlockNumber_) {
l2BlockNumber_ = _getArgUint256(0x54);
}
/// @inheritdoc IFaultDisputeGame
function startingBlockNumber() external view returns (uint256 startingBlockNumber_) {
startingBlockNumber_ = startingOutputRoot.l2BlockNumber;
}
/// @inheritdoc IFaultDisputeGame
function startingRootHash() external view returns (Hash startingRootHash_) {
startingRootHash_ = startingOutputRoot.root;
}
/// @notice Challenges the root L2 block number by providing the preimage of the output root and the L2 block header
/// and showing that the committed L2 block number is incorrect relative to the claimed L2 block number.
/// @param _outputRootProof The output root proof.
/// @param _headerRLP The RLP-encoded L2 block header.
function challengeRootL2Block(
Types.OutputRootProof calldata _outputRootProof,
bytes calldata _headerRLP
)
external
{
// INVARIANT: Moves cannot be made unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
// The root L2 block claim can only be challenged once.
if (l2BlockNumberChallenged) revert L2BlockNumberChallenged();
// Verify the output root preimage.
if (Hashing.hashOutputRootProof(_outputRootProof) != rootClaim().raw()) revert InvalidOutputRootProof();
// Verify the block hash preimage.
if (keccak256(_headerRLP) != _outputRootProof.latestBlockhash) revert InvalidHeaderRLP();
// Decode the header RLP to find the number of the block. In the consensus encoding, the timestamp
// is the 9th element in the list that represents the block header.
RLPReader.RLPItem[] memory headerContents = RLPReader.readList(RLPReader.toRLPItem(_headerRLP));
bytes memory rawBlockNumber = RLPReader.readBytes(headerContents[HEADER_BLOCK_NUMBER_INDEX]);
// Sanity check the block number string length.
if (rawBlockNumber.length > 32) revert InvalidHeaderRLP();
// Convert the raw, left-aligned block number to a uint256 by aligning it as a big-endian
// number in the low-order bytes of a 32-byte word.
//
// SAFETY: The length of `rawBlockNumber` is checked above to ensure it is at most 32 bytes.
uint256 blockNumber;
assembly {
blockNumber := shr(shl(0x03, sub(0x20, mload(rawBlockNumber))), mload(add(rawBlockNumber, 0x20)))
}
// Ensure the block number does not match the block number claimed in the dispute game.
if (blockNumber == l2BlockNumber()) revert BlockNumberMatches();
// Issue a special counter to the root claim. This counter will always win the root claim subgame, and receive
// the bond from the root claimant.
l2BlockNumberChallenger = msg.sender;
l2BlockNumberChallenged = true;
}
////////////////////////////////////////////////////////////////
// `IDisputeGame` impl //
////////////////////////////////////////////////////////////////
/// @inheritdoc IDisputeGame
function resolve() external returns (GameStatus status_) {
// INVARIANT: Resolution cannot occur unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
// INVARIANT: Resolution cannot occur unless the absolute root subgame has been resolved.
if (!resolvedSubgames[0]) revert OutOfOrderResolution();
// Update the global game status; The dispute has concluded.
status_ = claimData[0].counteredBy == address(0) ? GameStatus.DEFENDER_WINS : GameStatus.CHALLENGER_WINS;
resolvedAt = Timestamp.wrap(uint64(block.timestamp));
// Update the status and emit the resolved event, note that we're performing an assignment here.
emit Resolved(status = status_);
// Try to update the anchor state, this should not revert.
ANCHOR_STATE_REGISTRY.tryUpdateAnchorState();
}
/// @inheritdoc IFaultDisputeGame
function resolveClaim(uint256 _claimIndex, uint256 _numToResolve) external {
// INVARIANT: Resolution cannot occur unless the game is currently in progress.
if (status != GameStatus.IN_PROGRESS) revert GameNotInProgress();
ClaimData storage subgameRootClaim = claimData[_claimIndex];
Duration challengeClockDuration = getChallengerDuration(_claimIndex);
// INVARIANT: Cannot resolve a subgame unless the clock of its would-be counter has expired
// INVARIANT: Assuming ordered subgame resolution, challengeClockDuration is always >= MAX_CLOCK_DURATION if all
// descendant subgames are resolved
if (challengeClockDuration.raw() < MAX_CLOCK_DURATION.raw()) revert ClockNotExpired();
// INVARIANT: Cannot resolve a subgame twice.
if (resolvedSubgames[_claimIndex]) revert ClaimAlreadyResolved();
uint256[] storage challengeIndices = subgames[_claimIndex];
uint256 challengeIndicesLen = challengeIndices.length;
// Uncontested claims are resolved implicitly unless they are the root claim. Pay out the bond to the claimant
// and return early.
if (challengeIndicesLen == 0 && _claimIndex != 0) {
// In the event that the parent claim is at the max depth, there will always be 0 subgames. If the
// `counteredBy` field is set and there are no subgames, this implies that the parent claim was successfully
// stepped against. In this case, we pay out the bond to the party that stepped against the parent claim.
// Otherwise, the parent claim is uncontested, and the bond is returned to the claimant.
address counteredBy = subgameRootClaim.counteredBy;
address recipient = counteredBy == address(0) ? subgameRootClaim.claimant : counteredBy;
_distributeBond(recipient, subgameRootClaim);
resolvedSubgames[_claimIndex] = true;
return;
}
// Fetch the resolution checkpoint from storage.
ResolutionCheckpoint memory checkpoint = resolutionCheckpoints[_claimIndex];
// If the checkpoint does not currently exist, initialize the current left most position as max u128.
if (!checkpoint.initialCheckpointComplete) {
checkpoint.leftmostPosition = Position.wrap(type(uint128).max);
checkpoint.initialCheckpointComplete = true;
// If `_numToResolve == 0`, assume that we can check all child subgames in this one callframe.
if (_numToResolve == 0) _numToResolve = challengeIndicesLen;
}
// Assume parent is honest until proven otherwise
uint256 lastToResolve = checkpoint.subgameIndex + _numToResolve;
uint256 finalCursor = lastToResolve > challengeIndicesLen ? challengeIndicesLen : lastToResolve;
for (uint256 i = checkpoint.subgameIndex; i < finalCursor; i++) {
uint256 challengeIndex = challengeIndices[i];
// INVARIANT: Cannot resolve a subgame containing an unresolved claim
if (!resolvedSubgames[challengeIndex]) revert OutOfOrderResolution();
ClaimData storage claim = claimData[challengeIndex];
// If the child subgame is uncountered and further left than the current left-most counter,
// update the parent subgame's `countered` address and the current `leftmostCounter`.
// The left-most correct counter is preferred in bond payouts in order to discourage attackers
// from countering invalid subgame roots via an invalid defense position. As such positions
// cannot be correctly countered.
// Note that correctly positioned defense, but invalid claimes can still be successfully countered.
if (claim.counteredBy == address(0) && checkpoint.leftmostPosition.raw() > claim.position.raw()) {
checkpoint.counteredBy = claim.claimant;
checkpoint.leftmostPosition = claim.position;
}
}
// Increase the checkpoint's cursor position by the number of children that were checked.
checkpoint.subgameIndex = uint32(finalCursor);
// Persist the checkpoint and allow for continuing in a separate transaction, if resolution is not already
// complete.
resolutionCheckpoints[_claimIndex] = checkpoint;
// If all children have been traversed in the above loop, the subgame may be resolved. Otherwise, persist the
// checkpoint and allow for continuation in a separate transaction.
if (checkpoint.subgameIndex == challengeIndicesLen) {
address countered = checkpoint.counteredBy;
// Mark the subgame as resolved.
resolvedSubgames[_claimIndex] = true;
// Distribute the bond to the appropriate party.
if (_claimIndex == 0 && l2BlockNumberChallenged) {
// Special case: If the root claim has been challenged with the `challengeRootL2Block` function,
// the bond is always paid out to the issuer of that challenge.
address challenger = l2BlockNumberChallenger;
_distributeBond(challenger, subgameRootClaim);
subgameRootClaim.counteredBy = challenger;
} else {
// If the parent was not successfully countered, pay out the parent's bond to the claimant.
// If the parent was successfully countered, pay out the parent's bond to the challenger.
_distributeBond(countered == address(0) ? subgameRootClaim.claimant : countered, subgameRootClaim);
// Once a subgame is resolved, we percolate the result up the DAG so subsequent calls to
// resolveClaim will not need to traverse this subgame.
subgameRootClaim.counteredBy = countered;
}
}
}
/// @inheritdoc IDisputeGame
function gameType() public view override returns (GameType gameType_) {
gameType_ = GAME_TYPE;
}
/// @inheritdoc IDisputeGame
function gameCreator() public pure returns (address creator_) {
creator_ = _getArgAddress(0x00);
}
/// @inheritdoc IDisputeGame
function rootClaim() public pure returns (Claim rootClaim_) {
rootClaim_ = Claim.wrap(_getArgBytes32(0x14));
}
/// @inheritdoc IDisputeGame
function l1Head() public pure returns (Hash l1Head_) {
l1Head_ = Hash.wrap(_getArgBytes32(0x34));
}
/// @inheritdoc IDisputeGame
function extraData() public pure returns (bytes memory extraData_) {
// The extra data starts at the second word within the cwia calldata and
// is 32 bytes long.
extraData_ = _getArgBytes(0x54, 0x20);
}
/// @inheritdoc IDisputeGame
function gameData() external view returns (GameType gameType_, Claim rootClaim_, bytes memory extraData_) {
gameType_ = gameType();
rootClaim_ = rootClaim();
extraData_ = extraData();
}
////////////////////////////////////////////////////////////////
// MISC EXTERNAL //
////////////////////////////////////////////////////////////////
/// @notice Returns the required bond for a given move kind.
/// @param _position The position of the bonded interaction.
/// @return requiredBond_ The required ETH bond for the given move, in wei.
function getRequiredBond(Position _position) public view returns (uint256 requiredBond_) {
uint256 depth = uint256(_position.depth());
if (depth > MAX_GAME_DEPTH) revert GameDepthExceeded();
// Values taken from Big Bonds v1.5 (TM) spec.
uint256 assumedBaseFee = 200 gwei;
uint256 baseGasCharged = 400_000;
uint256 highGasCharged = 300_000_000;
// Goal here is to compute the fixed multiplier that will be applied to the base gas
// charged to get the required gas amount for the given depth. We apply this multiplier
// some `n` times where `n` is the depth of the position. We are looking for some number
// that, when multiplied by itself `MAX_GAME_DEPTH` times and then multiplied by the base
// gas charged, will give us the maximum gas that we want to charge.
// We want to solve for (highGasCharged/baseGasCharged) ** (1/MAX_GAME_DEPTH).
// We know that a ** (b/c) is equal to e ** (ln(a) * (b/c)).
// We can compute e ** (ln(a) * (b/c)) quite easily with FixedPointMathLib.
// Set up a, b, and c.
uint256 a = highGasCharged / baseGasCharged;
uint256 b = FixedPointMathLib.WAD;
uint256 c = MAX_GAME_DEPTH * FixedPointMathLib.WAD;
// Compute ln(a).
// slither-disable-next-line divide-before-multiply
uint256 lnA = uint256(FixedPointMathLib.lnWad(int256(a * FixedPointMathLib.WAD)));
// Computes (b / c) with full precision using WAD = 1e18.
uint256 bOverC = FixedPointMathLib.divWad(b, c);
// Compute e ** (ln(a) * (b/c))
// sMulWad can be used here since WAD = 1e18 maintains the same precision.
uint256 numerator = FixedPointMathLib.mulWad(lnA, bOverC);
int256 base = FixedPointMathLib.expWad(int256(numerator));
// Compute the required gas amount.
int256 rawGas = FixedPointMathLib.powWad(base, int256(depth * FixedPointMathLib.WAD));
uint256 requiredGas = FixedPointMathLib.mulWad(baseGasCharged, uint256(rawGas));
// Compute the required bond.
requiredBond_ = assumedBaseFee * requiredGas;
}
/// @notice Claim the credit belonging to the recipient address.
/// @param _recipient The owner and recipient of the credit.
function claimCredit(address _recipient) external {
// Remove the credit from the recipient prior to performing the external call.
uint256 recipientCredit = credit[_recipient];
credit[_recipient] = 0;
// Revert if the recipient has no credit to claim.
if (recipientCredit == 0) revert NoCreditToClaim();
// Try to withdraw the WETH amount so it can be used here.
WETH.withdraw(_recipient, recipientCredit);
// Transfer the credit to the recipient.
(bool success,) = _recipient.call{ value: recipientCredit }(hex"");
if (!success) revert BondTransferFailed();
}
/// @notice Returns the amount of time elapsed on the potential challenger to `_claimIndex`'s chess clock. Maxes
/// out at `MAX_CLOCK_DURATION`.
/// @param _claimIndex The index of the subgame root claim.
/// @return duration_ The time elapsed on the potential challenger to `_claimIndex`'s chess clock.
function getChallengerDuration(uint256 _claimIndex) public view returns (Duration duration_) {
// INVARIANT: The game must be in progress to query the remaining time to respond to a given claim.
if (status != GameStatus.IN_PROGRESS) {
revert GameNotInProgress();
}
// Fetch the subgame root claim.
ClaimData storage subgameRootClaim = claimData[_claimIndex];
// Fetch the parent of the subgame root's clock, if it exists.
Clock parentClock;
if (subgameRootClaim.parentIndex != type(uint32).max) {
parentClock = claimData[subgameRootClaim.parentIndex].clock;
}
// Compute the duration elapsed of the potential challenger's clock.
uint64 challengeDuration =
uint64(parentClock.duration().raw() + (block.timestamp - subgameRootClaim.clock.timestamp().raw()));
duration_ = challengeDuration > MAX_CLOCK_DURATION.raw() ? MAX_CLOCK_DURATION : Duration.wrap(challengeDuration);
}
/// @notice Returns the length of the `claimData` array.
function claimDataLen() external view returns (uint256 len_) {
len_ = claimData.length;
}
////////////////////////////////////////////////////////////////
// IMMUTABLE GETTERS //
////////////////////////////////////////////////////////////////
/// @notice Returns the absolute prestate of the instruction trace.
function absolutePrestate() external view returns (Claim absolutePrestate_) {
absolutePrestate_ = ABSOLUTE_PRESTATE;
}
/// @notice Returns the max game depth.
function maxGameDepth() external view returns (uint256 maxGameDepth_) {
maxGameDepth_ = MAX_GAME_DEPTH;
}
/// @notice Returns the split depth.
function splitDepth() external view returns (uint256 splitDepth_) {
splitDepth_ = SPLIT_DEPTH;
}
/// @notice Returns the max clock duration.
function maxClockDuration() external view returns (Duration maxClockDuration_) {
maxClockDuration_ = MAX_CLOCK_DURATION;
}
/// @notice Returns the clock extension constant.
function clockExtension() external view returns (Duration clockExtension_) {
clockExtension_ = CLOCK_EXTENSION;
}
/// @notice Returns the address of the VM.
function vm() external view returns (IBigStepper vm_) {
vm_ = VM;
}
/// @notice Returns the WETH contract for holding ETH.
function weth() external view returns (IDelayedWETH weth_) {
weth_ = WETH;
}
/// @notice Returns the anchor state registry contract.
function anchorStateRegistry() external view returns (IAnchorStateRegistry registry_) {
registry_ = ANCHOR_STATE_REGISTRY;
}
/// @notice Returns the chain ID of the L2 network this contract argues about.
function l2ChainId() external view returns (uint256 l2ChainId_) {
l2ChainId_ = L2_CHAIN_ID;
}
/// @notice Returns n-bits
function nBits() external view returns (uint256 nBits_) {
nBits_ = N_BITS;
}
/// @notice Returns n-bits
function maxAttackBranch() external view returns (uint256 maxAttackBranch_) {
maxAttackBranch_ = MAX_ATTACK_BRANCH;
}
////////////////////////////////////////////////////////////////
// HELPERS //
////////////////////////////////////////////////////////////////
/// @notice Pays out the bond of a claim to a given recipient.
/// @param _recipient The recipient of the bond.
/// @param _bonded The claim to pay out the bond of.
function _distributeBond(address _recipient, ClaimData storage _bonded) internal {
// Set all bits in the bond value to indicate that the bond has been paid out.
uint256 bond = _bonded.bond;
// Increase the recipient's credit.
credit[_recipient] += bond;
// Unlock the bond.
WETH.unlock(_recipient, bond);
}
/// @notice Verifies the integrity of an execution bisection subgame's root claim. Reverts if the claim
/// is invalid.
/// @param _rootClaim The root claim of the execution bisection subgame.
function _verifyExecMultisectionRoot(
Claim _rootClaim,
uint256 _parentIdx,
Position _parentPos,
uint256 _attackBranch
)
internal
view
{
// The root claim of an execution trace bisection sub-game must:
// 1. Signal that the VM panicked or resulted in an invalid transition if the disputed output root
// was made by the opposing party.
// 2. Signal that the VM resulted in a valid transition if the disputed output root was made by the same party.
// If the move is a defense, the disputed output could have been made by either party. In this case, we
// need to search for the parent output to determine what the expected status byte should be.
Position disputedLeafPos = Position.wrap(_parentPos.raw() + uint128(_attackBranch));
(, Position disputedPos) = _findTraceAncestorRoot({ _pos: disputedLeafPos, _start: _parentIdx, _global: true });
uint8 vmStatus = uint8(_rootClaim.raw()[0]);
if ((MAX_ATTACK_BRANCH != _attackBranch) || (disputedPos.depth() / N_BITS) % 2 == (SPLIT_DEPTH / N_BITS) % 2) {
// If the move is an attack, the parent output is always deemed to be disputed. In this case, we only need
// to check that the root claim signals that the VM panicked or resulted in an invalid transition.
// If the move is a defense, and the disputed output and creator of the execution trace subgame disagree,
// the root claim should also signal that the VM panicked or resulted in an invalid transition.
if (!(vmStatus == VMStatuses.INVALID.raw() || vmStatus == VMStatuses.PANIC.raw())) {
revert UnexpectedRootClaim(_rootClaim);
}
} else if (vmStatus != VMStatuses.VALID.raw()) {
// The disputed output and the creator of the execution trace subgame agree. The status byte should
// have signaled that the VM succeeded.
revert UnexpectedRootClaim(_rootClaim);
}
}
/// @notice Finds the trace ancestor of a given position within the DAG.
/// @param _pos The position to find the trace ancestor claim of.
/// @param _start The index to start searching from.
/// @param _global Whether or not to search the entire dag or just within an execution trace subgame. If set to
/// `true`, and `_pos` is at or above the split depth, this function will revert.
/// @return ancestor_ The ancestor claim that commits to the same trace index as `_pos`.
function _findTraceAncestor(
Position _pos,
uint256 _start,
bool _global
)
internal
view
returns (ClaimData storage ancestor_)
{