From 4ff5eebe1459b06ccbf4dfcd0781b8a926ea1062 Mon Sep 17 00:00:00 2001 From: Mahsa Moosavi Date: Fri, 22 Dec 2023 12:55:06 -0500 Subject: [PATCH 1/4] Add ValidatorWalletTest.sol --- contracts/hardhat.config.ts | 13 +- contracts/scripts/boldUpgradeFunctions.ts | 8 +- contracts/scripts/common.ts | 2 +- contracts/scripts/files/localConfig.json | 4 +- .../scripts/files/localDeployedContracts.json | 3 +- contracts/scripts/prepareBoldUpgrade.ts | 6 +- contracts/scripts/testLocalPrepareTestNode.ts | 4 +- contracts/src/bridge/IOutbox.sol | 2 +- contracts/src/bridge/Inbox.sol | 1 - .../src/challenge/OldChallengeManager.sol | 16 +- .../src/challengeV2/EdgeChallengeManager.sol | 113 +- contracts/src/challengeV2/IAssertionChain.sol | 6 + .../challengeV2/libraries/ArrayUtilsLib.sol | 24 +- .../libraries/ChallengeEdgeLib.sol | 141 +- .../challengeV2/libraries/ChallengeErrors.sol | 6 +- .../libraries/EdgeChallengeManagerLib.sol | 230 ++- .../challengeV2/libraries/MerkleTreeLib.sol | 49 +- .../challengeV2/libraries/UintUtilsLib.sol | 4 +- contracts/src/mocks/BridgeStub.sol | 3 +- contracts/src/mocks/ExecutionManager.sol | 5 +- contracts/src/mocks/MerkleTreeAccess.sol | 40 +- .../src/mocks/SimpleOneStepProofEntry.sol | 8 +- contracts/src/osp/OneStepProofEntry.sol | 13 +- contracts/src/rollup/Assertion.sol | 9 +- contracts/src/rollup/BOLDUpgradeAction.sol | 129 +- contracts/src/rollup/IRollupAdmin.sol | 3 +- contracts/src/rollup/IRollupCore.sol | 17 +- contracts/src/rollup/IRollupLogic.sol | 3 +- contracts/src/rollup/RollupAdminLogic.sol | 19 +- contracts/src/rollup/RollupCore.sol | 88 +- contracts/src/rollup/RollupCreator.sol | 64 +- contracts/src/rollup/RollupLib.sol | 24 +- contracts/src/rollup/RollupProxy.sol | 6 +- contracts/src/rollup/RollupUserLogic.sol | 92 +- contracts/src/rollup/ValidatorWallet.sol | 4 +- contracts/test/ERC20Mock.sol | 2 +- contracts/test/MockAssertionChain.sol | 44 +- contracts/test/Rollup.t.sol | 292 +++- contracts/test/RollupMock.sol | 15 + contracts/test/ValidatorWalletTest.t.sol | 179 +++ .../test/challengeV2/ArrayUtilsLib.t.sol | 4 +- .../test/challengeV2/ChallengeEdgeLib.t.sol | 211 ++- .../challengeV2/EdgeChallengeManager.t.sol | 1429 ++++++++++++----- .../challengeV2/EdgeChallengeManagerLib.t.sol | 1242 ++++++++++---- .../test/challengeV2/MerkleTreeLib.t.sol | 106 +- contracts/test/challengeV2/StateTools.sol | 10 +- contracts/test/challengeV2/UintUtilsLib.t.sol | 10 +- contracts/test/challengeV2/Utils.sol | 24 +- .../test/contract/common/challengeLib.ts | 5 +- .../stakingPool/AssertionStakingPool.t.sol | 48 +- contracts/test/util/TestUtil.sol | 12 + 51 files changed, 3599 insertions(+), 1193 deletions(-) create mode 100644 contracts/test/RollupMock.sol create mode 100644 contracts/test/ValidatorWalletTest.t.sol create mode 100644 contracts/test/util/TestUtil.sol diff --git a/contracts/hardhat.config.ts b/contracts/hardhat.config.ts index bd88f9580..9b7af4ce7 100644 --- a/contracts/hardhat.config.ts +++ b/contracts/hardhat.config.ts @@ -18,6 +18,15 @@ const solidity = { }, }, }, + { + version: '0.8.0', + settings: { + optimizer: { + enabled: true, + runs: 2000, + }, + }, + }, ], overrides: { 'src/challengeV2/EdgeChallengeManager.sol': { @@ -176,6 +185,6 @@ module.exports = { target: 'ethers-v5', }, contractSizer: { - strict: process.env.STRICT ? true : false - } + strict: process.env.STRICT ? true : false, + }, } diff --git a/contracts/scripts/boldUpgradeFunctions.ts b/contracts/scripts/boldUpgradeFunctions.ts index 53dcf67df..a464aa4fe 100644 --- a/contracts/scripts/boldUpgradeFunctions.ts +++ b/contracts/scripts/boldUpgradeFunctions.ts @@ -27,7 +27,7 @@ import { export const deployDependencies = async ( signer: Signer, maxDataSize: number, - log: boolean = false, + log: boolean = false ): Promise< Omit > => { @@ -147,7 +147,11 @@ export const deployBoldUpgrade = async ( config: Config, log: boolean = false ): Promise => { - const deployed = await deployDependencies(wallet, config.settings.maxDataSize, log) + const deployed = await deployDependencies( + wallet, + config.settings.maxDataSize, + log + ) const fac = new BOLDUpgradeAction__factory(wallet) const boldUpgradeAction = await fac.deploy( diff --git a/contracts/scripts/common.ts b/contracts/scripts/common.ts index bc2a83289..1985df1f5 100644 --- a/contracts/scripts/common.ts +++ b/contracts/scripts/common.ts @@ -51,7 +51,7 @@ export interface Config { seqInbox: string } settings: { - challengeGracePeriodBlocks: number, + challengeGracePeriodBlocks: number confirmPeriodBlocks: number challengePeriodBlocks: number stakeToken: string diff --git a/contracts/scripts/files/localConfig.json b/contracts/scripts/files/localConfig.json index b9eab041e..29691b719 100644 --- a/contracts/scripts/files/localConfig.json +++ b/contracts/scripts/files/localConfig.json @@ -30,7 +30,5 @@ "numBigStepLevel": 4, "maxDataSize": 117964 }, - "validators": [ - "0xf10EF80c6eF4930A62C5F9661c91339Df4dBB173" - ] + "validators": ["0xf10EF80c6eF4930A62C5F9661c91339Df4dBB173"] } diff --git a/contracts/scripts/files/localDeployedContracts.json b/contracts/scripts/files/localDeployedContracts.json index 7a73a41bf..0967ef424 100644 --- a/contracts/scripts/files/localDeployedContracts.json +++ b/contracts/scripts/files/localDeployedContracts.json @@ -1,2 +1 @@ -{ -} \ No newline at end of file +{} diff --git a/contracts/scripts/prepareBoldUpgrade.ts b/contracts/scripts/prepareBoldUpgrade.ts index 51171d63d..b8aa96386 100644 --- a/contracts/scripts/prepareBoldUpgrade.ts +++ b/contracts/scripts/prepareBoldUpgrade.ts @@ -1,10 +1,6 @@ import { ethers, Wallet } from 'ethers' import fs from 'fs' -import { - DeployedContracts, - getConfig, - getJsonFile, -} from './common' +import { DeployedContracts, getConfig, getJsonFile } from './common' import { deployBoldUpgrade } from './boldUpgradeFunctions' import dotenv from 'dotenv' diff --git a/contracts/scripts/testLocalPrepareTestNode.ts b/contracts/scripts/testLocalPrepareTestNode.ts index 16c4d6109..2660cc664 100644 --- a/contracts/scripts/testLocalPrepareTestNode.ts +++ b/contracts/scripts/testLocalPrepareTestNode.ts @@ -23,7 +23,7 @@ dotenv.config() const transferToUpgradeExec = async ( rollupAdmin: Wallet, - rollupAddress: string, + rollupAddress: string ) => { const upgradeExecutorImpl = await new ContractFactory( UpgradeExecutorAbi, @@ -32,7 +32,7 @@ const transferToUpgradeExec = async ( ).deploy() await upgradeExecutorImpl.deployed() - const proxyAdminAddress = "0xa4884de60AEef09b1b35fa255F56ee37198A80B3" + const proxyAdminAddress = '0xa4884de60AEef09b1b35fa255F56ee37198A80B3' const upExecProxy = await new TransparentUpgradeableProxy__factory( rollupAdmin diff --git a/contracts/src/bridge/IOutbox.sol b/contracts/src/bridge/IOutbox.sol index 1a748401c..5565122d4 100644 --- a/contracts/src/bridge/IOutbox.sol +++ b/contracts/src/bridge/IOutbox.sol @@ -28,7 +28,7 @@ interface IOutbox { function OUTBOX_VERSION() external view returns (uint128); // the outbox version function updateSendRoot(bytes32 sendRoot, bytes32 l2BlockHash) external; - + function updateRollupAddress() external; /// @notice When l2ToL1Sender returns a nonzero address, the message was originated by an L2 account diff --git a/contracts/src/bridge/Inbox.sol b/contracts/src/bridge/Inbox.sol index e39196b24..0ee7f1055 100644 --- a/contracts/src/bridge/Inbox.sol +++ b/contracts/src/bridge/Inbox.sol @@ -531,7 +531,6 @@ contract Inbox is DelegateCallAware, PausableUpgradeable, IInbox { ); } - function _deliverMessage( uint8 _kind, address _sender, diff --git a/contracts/src/challenge/OldChallengeManager.sol b/contracts/src/challenge/OldChallengeManager.sol index 585ccecc4..f66d413e6 100644 --- a/contracts/src/challenge/OldChallengeManager.sol +++ b/contracts/src/challenge/OldChallengeManager.sol @@ -59,7 +59,10 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { } else if (expectedMode == ChallengeModeRequirement.BLOCK) { require(challenge.mode == OldChallengeLib.ChallengeMode.BLOCK, "CHAL_NOT_BLOCK"); } else if (expectedMode == ChallengeModeRequirement.EXECUTION) { - require(challenge.mode == OldChallengeLib.ChallengeMode.EXECUTION, "CHAL_NOT_EXECUTION"); + require( + challenge.mode == OldChallengeLib.ChallengeMode.EXECUTION, + "CHAL_NOT_EXECUTION" + ); } else { assert(false); } @@ -146,7 +149,10 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { maxInboxMessagesRead++; } challenge.maxInboxMessages = maxInboxMessagesRead; - challenge.next = OldChallengeLib.Participant({addr: asserter_, timeLeft: asserterTimeLeft_}); + challenge.next = OldChallengeLib.Participant({ + addr: asserter_, + timeLeft: asserterTimeLeft_ + }); challenge.current = OldChallengeLib.Participant({ addr: challenger_, timeLeft: challengerTimeLeft_ @@ -254,7 +260,11 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { } bytes32 afterHash = osp.proveOneStep( - ExecutionContext({maxInboxMessagesRead: challenge.maxInboxMessages, bridge: bridge, initialWasmModuleRoot: challenge.wasmModuleRoot}), + ExecutionContext({ + maxInboxMessagesRead: challenge.maxInboxMessages, + bridge: bridge, + initialWasmModuleRoot: challenge.wasmModuleRoot + }), challengeStart, selection.oldSegments[selection.challengePosition], proof diff --git a/contracts/src/challengeV2/EdgeChallengeManager.sol b/contracts/src/challengeV2/EdgeChallengeManager.sol index 3059bd3bf..571a66c0a 100644 --- a/contracts/src/challengeV2/EdgeChallengeManager.sol +++ b/contracts/src/challengeV2/EdgeChallengeManager.sol @@ -65,9 +65,11 @@ interface IEdgeChallengeManager { /// @param prefixProof A proof to show that the bisectionHistoryRoot commits to a prefix of the current endHistoryRoot /// @return lowerChildId The id of the newly created lower child edge /// @return upperChildId The id of the newly created upper child edge - function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes calldata prefixProof) - external - returns (bytes32, bytes32); + function bisectEdge( + bytes32 edgeId, + bytes32 bisectionHistoryRoot, + bytes calldata prefixProof + ) external returns (bytes32, bytes32); /// @notice Confirm an edge if both its children are already confirmed function confirmEdgeByChildren(bytes32 edgeId) external; @@ -225,7 +227,10 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param upperChildId The id of the upper child created during bisection /// @param lowerChildAlreadyExists When an edge is bisected the lower child may already exist - created by a rival. event EdgeBisected( - bytes32 indexed edgeId, bytes32 indexed lowerChildId, bytes32 indexed upperChildId, bool lowerChildAlreadyExists + bytes32 indexed edgeId, + bytes32 indexed lowerChildId, + bytes32 indexed upperChildId, + bool lowerChildAlreadyExists ); /// @notice An edge can be confirmed if both of its children were already confirmed. @@ -237,13 +242,21 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param edgeId The edge that was confirmed /// @param mutualId The mutual id of the confirmed edge /// @param totalTimeUnrivaled The cumulative amount of time (in blocks) this edge spent unrivaled - event EdgeConfirmedByTime(bytes32 indexed edgeId, bytes32 indexed mutualId, uint64 totalTimeUnrivaled); + event EdgeConfirmedByTime( + bytes32 indexed edgeId, + bytes32 indexed mutualId, + uint64 totalTimeUnrivaled + ); /// @notice An edge can be confirmed if a zero layer edge in the level below claims this edge /// @param edgeId The edge that was confirmed /// @param mutualId The mutual id of the confirmed edge /// @param claimingEdgeId The id of the zero layer edge that claimed this edge - event EdgeConfirmedByClaim(bytes32 indexed edgeId, bytes32 indexed mutualId, bytes32 claimingEdgeId); + event EdgeConfirmedByClaim( + bytes32 indexed edgeId, + bytes32 indexed mutualId, + bytes32 claimingEdgeId + ); /// @notice A SmallStep edge of length 1 can be confirmed via a one step proof /// @param edgeId The edge that was confirmed @@ -255,7 +268,12 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param mutualId The mutual id of the confirmed edge /// @param stakeToken The ERC20 being refunded /// @param stakeAmount The amount of tokens being refunded - event EdgeRefunded(bytes32 indexed edgeId, bytes32 indexed mutualId, address stakeToken, uint256 stakeAmount); + event EdgeRefunded( + bytes32 indexed edgeId, + bytes32 indexed mutualId, + address stakeToken, + uint256 stakeAmount + ); /// @dev Store for all edges and rival data /// All edges, including edges from different challenges, are stored together in the same store @@ -373,11 +391,17 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { if (args.proof.length == 0) { revert EmptyEdgeSpecificProof(); } - (, ExecutionStateData memory predecessorStateData, ExecutionStateData memory claimStateData) = - abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); + ( + , + ExecutionStateData memory predecessorStateData, + ExecutionStateData memory claimStateData + ) = abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); assertionChain.validateAssertionHash( - args.claimId, claimStateData.executionState, claimStateData.prevAssertionHash, claimStateData.inboxAcc + args.claimId, + claimStateData.executionState, + claimStateData.prevAssertionHash, + claimStateData.inboxAcc ); assertionChain.validateAssertionHash( @@ -396,9 +420,21 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { claimStateData.executionState ); - edgeAdded = store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, NUM_BIGSTEP_LEVEL); + edgeAdded = store.createLayerZeroEdge( + args, + ard, + oneStepProofEntry, + expectedEndHeight, + NUM_BIGSTEP_LEVEL + ); } else { - edgeAdded = store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, NUM_BIGSTEP_LEVEL); + edgeAdded = store.createLayerZeroEdge( + args, + ard, + oneStepProofEntry, + expectedEndHeight, + NUM_BIGSTEP_LEVEL + ); } IERC20 st = stakeToken; @@ -431,12 +467,16 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { } /// @inheritdoc IEdgeChallengeManager - function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes calldata prefixProof) - external - returns (bytes32, bytes32) - { - (bytes32 lowerChildId, EdgeAddedData memory lowerChildAdded, EdgeAddedData memory upperChildAdded) = - store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); + function bisectEdge( + bytes32 edgeId, + bytes32 bisectionHistoryRoot, + bytes calldata prefixProof + ) external returns (bytes32, bytes32) { + ( + bytes32 lowerChildId, + EdgeAddedData memory lowerChildAdded, + EdgeAddedData memory upperChildAdded + ) = store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); bool lowerChildAlreadyExists = lowerChildAdded.edgeId == 0; // the lower child might already exist, if it didnt then a new @@ -491,7 +531,9 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { ExecutionStateData calldata claimStateData ) public { // if there are no ancestors provided, then the top edge is the edge we're confirming itself - bytes32 lastEdgeId = ancestorEdges.length > 0 ? ancestorEdges[ancestorEdges.length - 1] : edgeId; + bytes32 lastEdgeId = ancestorEdges.length > 0 + ? ancestorEdges[ancestorEdges.length - 1] + : edgeId; ChallengeEdge storage topEdge = store.get(lastEdgeId); EdgeType topLevelType = ChallengeEdgeLib.levelToType(topEdge.level, NUM_BIGSTEP_LEVEL); @@ -514,16 +556,22 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { claimStateData.prevAssertionHash, claimStateData.inboxAcc ); - assertionBlocks = assertionChain.getSecondChildCreationBlock(claimStateData.prevAssertionHash) - - assertionChain.getFirstChildCreationBlock(claimStateData.prevAssertionHash); + assertionBlocks = + assertionChain.getSecondChildCreationBlock(claimStateData.prevAssertionHash) - + assertionChain.getFirstChildCreationBlock(claimStateData.prevAssertionHash); } else { // if the assertion being claimed is not the first child, then it had siblings from the moment // it was created, so it has no time unrivaled assertionBlocks = 0; } - uint64 totalTimeUnrivaled = - store.confirmEdgeByTime(edgeId, ancestorEdges, assertionBlocks, challengePeriodBlocks, NUM_BIGSTEP_LEVEL); + uint64 totalTimeUnrivaled = store.confirmEdgeByTime( + edgeId, + ancestorEdges, + assertionBlocks, + challengePeriodBlocks, + NUM_BIGSTEP_LEVEL + ); emit EdgeConfirmedByTime(edgeId, store.edges[edgeId].mutualId(), totalTimeUnrivaled); } @@ -601,7 +649,15 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { uint256 endHeight, bytes32 endHistoryRoot ) public pure returns (bytes32) { - return ChallengeEdgeLib.idComponent(level, originId, startHeight, startHistoryRoot, endHeight, endHistoryRoot); + return + ChallengeEdgeLib.idComponent( + level, + originId, + startHeight, + startHistoryRoot, + endHeight, + endHistoryRoot + ); } /// @inheritdoc IEdgeChallengeManager @@ -612,7 +668,14 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { bytes32 startHistoryRoot, uint256 endHeight ) public pure returns (bytes32) { - return ChallengeEdgeLib.mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight); + return + ChallengeEdgeLib.mutualIdComponent( + level, + originId, + startHeight, + startHistoryRoot, + endHeight + ); } /// @inheritdoc IEdgeChallengeManager diff --git a/contracts/src/challengeV2/IAssertionChain.sol b/contracts/src/challengeV2/IAssertionChain.sol index 3420e22a9..4050f56c3 100644 --- a/contracts/src/challengeV2/IAssertionChain.sol +++ b/contracts/src/challengeV2/IAssertionChain.sol @@ -12,15 +12,21 @@ import "../rollup/Assertion.sol"; /// @notice The interface required by the EdgeChallengeManager for requesting assertion data from the AssertionChain interface IAssertionChain { function bridge() external view returns (IBridge); + function validateAssertionHash( bytes32 assertionHash, ExecutionState calldata state, bytes32 prevAssertionHash, bytes32 inboxAcc ) external view; + function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view; + function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64); + function getSecondChildCreationBlock(bytes32 assertionHash) external view returns (uint64); + function isFirstChild(bytes32 assertionHash) external view returns (bool); + function isPending(bytes32 assertionHash) external view returns (bool); } diff --git a/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol b/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol index 957fe75b7..25e3d52bf 100644 --- a/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol +++ b/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol @@ -10,7 +10,11 @@ library ArrayUtilsLib { /// @notice Append an item to the end of an array /// @param arr The array to append to /// @param newItem The item to append - function append(bytes32[] memory arr, bytes32 newItem) internal pure returns (bytes32[] memory) { + function append(bytes32[] memory arr, bytes32 newItem) + internal + pure + returns (bytes32[] memory) + { bytes32[] memory clone = new bytes32[](arr.length + 1); for (uint256 i = 0; i < arr.length; i++) { clone[i] = arr[i]; @@ -24,11 +28,11 @@ library ArrayUtilsLib { /// @param arr Array to slice /// @param startIndex The start index of the slice in the original array - inclusive /// @param endIndex The end index of the slice in the original array - exlusive - function slice(bytes32[] memory arr, uint256 startIndex, uint256 endIndex) - internal - pure - returns (bytes32[] memory) - { + function slice( + bytes32[] memory arr, + uint256 startIndex, + uint256 endIndex + ) internal pure returns (bytes32[] memory) { require(startIndex < endIndex, "Start not less than end"); require(endIndex <= arr.length, "End not less or equal than length"); @@ -42,7 +46,11 @@ library ArrayUtilsLib { /// @notice Concatenated to arrays /// @param arr1 First array /// @param arr1 Second array - function concat(bytes32[] memory arr1, bytes32[] memory arr2) internal pure returns (bytes32[] memory) { + function concat(bytes32[] memory arr1, bytes32[] memory arr2) + internal + pure + returns (bytes32[] memory) + { bytes32[] memory full = new bytes32[](arr1.length + arr2.length); for (uint256 i = 0; i < arr1.length; i++) { full[i] = arr1[i]; @@ -52,4 +60,4 @@ library ArrayUtilsLib { } return full; } -} \ No newline at end of file +} diff --git a/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol b/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol index 42e8e26aa..f8d142073 100644 --- a/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol +++ b/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol @@ -107,22 +107,23 @@ library ChallengeEdgeLib { newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); - return ChallengeEdge({ - originId: originId, - startHeight: startHeight, - startHistoryRoot: startHistoryRoot, - endHeight: endHeight, - endHistoryRoot: endHistoryRoot, - lowerChildId: 0, - upperChildId: 0, - createdAtBlock: uint64(block.number), - claimId: claimId, - staker: staker, - status: EdgeStatus.Pending, - level: level, - refunded: false, - confirmedAtBlock: 0 - }); + return + ChallengeEdge({ + originId: originId, + startHeight: startHeight, + startHistoryRoot: startHistoryRoot, + endHeight: endHeight, + endHistoryRoot: endHistoryRoot, + lowerChildId: 0, + upperChildId: 0, + createdAtBlock: uint64(block.number), + claimId: claimId, + staker: staker, + status: EdgeStatus.Pending, + level: level, + refunded: false, + confirmedAtBlock: 0 + }); } /// @notice Creates a new child edge. All edges except layer zero edges are child edges. @@ -137,22 +138,23 @@ library ChallengeEdgeLib { ) internal view returns (ChallengeEdge memory) { newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); - return ChallengeEdge({ - originId: originId, - startHeight: startHeight, - startHistoryRoot: startHistoryRoot, - endHeight: endHeight, - endHistoryRoot: endHistoryRoot, - lowerChildId: 0, - upperChildId: 0, - createdAtBlock: uint64(block.number), - claimId: 0, - staker: address(0), - status: EdgeStatus.Pending, - level: level, - refunded: false, - confirmedAtBlock: 0 - }); + return + ChallengeEdge({ + originId: originId, + startHeight: startHeight, + startHistoryRoot: startHistoryRoot, + endHeight: endHeight, + endHistoryRoot: endHistoryRoot, + lowerChildId: 0, + upperChildId: 0, + createdAtBlock: uint64(block.number), + claimId: 0, + staker: address(0), + status: EdgeStatus.Pending, + level: level, + refunded: false, + confirmedAtBlock: 0 + }); } /// @notice The "mutualId" of an edge. A mutual id is a hash of all the data that is shared by rivals. @@ -166,7 +168,8 @@ library ChallengeEdgeLib { bytes32 startHistoryRoot, uint256 endHeight ) internal pure returns (bytes32) { - return keccak256(abi.encodePacked(level, originId, startHeight, startHistoryRoot, endHeight)); + return + keccak256(abi.encodePacked(level, originId, startHeight, startHistoryRoot, endHeight)); } /// @notice The "mutualId" of an edge. A mutual id is a hash of all the data that is shared by rivals. @@ -174,11 +177,25 @@ library ChallengeEdgeLib { /// The difference between rivals is that they have a different endHistoryRoot, so that information /// is not included in this hash. function mutualId(ChallengeEdge storage ce) internal view returns (bytes32) { - return mutualIdComponent(ce.level, ce.originId, ce.startHeight, ce.startHistoryRoot, ce.endHeight); + return + mutualIdComponent( + ce.level, + ce.originId, + ce.startHeight, + ce.startHistoryRoot, + ce.endHeight + ); } function mutualIdMem(ChallengeEdge memory ce) internal pure returns (bytes32) { - return mutualIdComponent(ce.level, ce.originId, ce.startHeight, ce.startHistoryRoot, ce.endHeight); + return + mutualIdComponent( + ce.level, + ce.originId, + ce.startHeight, + ce.startHistoryRoot, + ce.endHeight + ); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information @@ -190,11 +207,13 @@ library ChallengeEdgeLib { uint256 endHeight, bytes32 endHistoryRoot ) internal pure returns (bytes32) { - return keccak256( - abi.encodePacked( - mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight), endHistoryRoot - ) - ); + return + keccak256( + abi.encodePacked( + mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight), + endHistoryRoot + ) + ); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information @@ -202,16 +221,28 @@ library ChallengeEdgeLib { /// possible to pass a storage edge to this method and the id be computed correctly, but that would load /// the whole struct into memory, so we're explicit here that this should be used for edges already in memory. function idMem(ChallengeEdge memory edge) internal pure returns (bytes32) { - return idComponent( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot - ); + return + idComponent( + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight, + edge.endHistoryRoot + ); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information function id(ChallengeEdge storage edge) internal view returns (bytes32) { - return idComponent( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot - ); + return + idComponent( + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight, + edge.endHistoryRoot + ); } /// @notice Does this edge exist in storage @@ -232,9 +263,17 @@ library ChallengeEdgeLib { /// @notice Set the children of an edge /// @dev Children can only be set once - function setChildren(ChallengeEdge storage edge, bytes32 lowerChildId, bytes32 upperChildId) internal { + function setChildren( + ChallengeEdge storage edge, + bytes32 lowerChildId, + bytes32 upperChildId + ) internal { if (edge.lowerChildId != 0 || edge.upperChildId != 0) { - revert ChildrenAlreadySet(ChallengeEdgeLib.id(edge), edge.lowerChildId, edge.upperChildId); + revert ChildrenAlreadySet( + ChallengeEdgeLib.id(edge), + edge.lowerChildId, + edge.upperChildId + ); } edge.lowerChildId = lowerChildId; edge.upperChildId = upperChildId; @@ -272,7 +311,11 @@ library ChallengeEdgeLib { } /// @notice Returns the edge type for a given level, given the total number of big step levels - function levelToType(uint8 level, uint8 numBigStepLevels) internal pure returns (EdgeType eType) { + function levelToType(uint8 level, uint8 numBigStepLevels) + internal + pure + returns (EdgeType eType) + { if (level == 0) { return EdgeType.Block; } else if (level <= numBigStepLevels) { diff --git a/contracts/src/challengeV2/libraries/ChallengeErrors.sol b/contracts/src/challengeV2/libraries/ChallengeErrors.sol index d8c7dd565..f46cac572 100644 --- a/contracts/src/challengeV2/libraries/ChallengeErrors.sol +++ b/contracts/src/challengeV2/libraries/ChallengeErrors.sol @@ -58,7 +58,11 @@ error EdgeClaimMismatch(bytes32 edgeId, bytes32 claimingEdgeId); error OriginIdMutualIdMismatch(bytes32 mutualId, bytes32 originId); /// @dev The edge does not have a valid ancestor link error EdgeNotAncestor( - bytes32 edgeId, bytes32 lowerChildId, bytes32 upperChildId, bytes32 ancestorEdgeId, bytes32 claimId + bytes32 edgeId, + bytes32 lowerChildId, + bytes32 upperChildId, + bytes32 ancestorEdgeId, + bytes32 claimId ); /// @dev The total number of blocks is not above the threshold error InsufficientConfirmationBlocks(uint256 totalBlocks, uint256 thresholdBlocks); diff --git a/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol b/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol index 0d3526858..8afe99236 100644 --- a/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol +++ b/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol @@ -134,7 +134,11 @@ library EdgeChallengeManagerLib { /// @dev Throws if the edge does not exist in the store /// @param store The edge store to fetch an id from /// @param edgeId The id of the edge to fetch - function get(EdgeStore storage store, bytes32 edgeId) internal view returns (ChallengeEdge storage) { + function get(EdgeStore storage store, bytes32 edgeId) + internal + view + returns (ChallengeEdge storage) + { if (!store.edges[edgeId].exists()) { revert EdgeNotExists(edgeId); } @@ -145,7 +149,11 @@ library EdgeChallengeManagerLib { /// @dev Useful where you already know the edge exists in the store - avoid a storage lookup /// @param store The edge store to fetch an id from /// @param edgeId The id of the edge to fetch - function getNoCheck(EdgeStore storage store, bytes32 edgeId) internal view returns (ChallengeEdge storage) { + function getNoCheck(EdgeStore storage store, bytes32 edgeId) + internal + view + returns (ChallengeEdge storage) + { return store.edges[edgeId]; } @@ -153,7 +161,10 @@ library EdgeChallengeManagerLib { /// @dev Updates first rival info for later use in calculating time unrivaled /// @param store The store to add the edge to /// @param edge The edge to add - function add(EdgeStore storage store, ChallengeEdge memory edge) internal returns (EdgeAddedData memory) { + function add(EdgeStore storage store, ChallengeEdge memory edge) + internal + returns (EdgeAddedData memory) + { bytes32 eId = edge.idMem(); // add the edge if it doesnt exist already if (store.edges[eId].exists()) { @@ -166,7 +177,11 @@ library EdgeChallengeManagerLib { // the new edge is a rival. This will later allow us to calculate time an edge // stayed unrivaled bytes32 mutualId = ChallengeEdgeLib.mutualIdComponent( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight ); bytes32 firstRival = store.firstRivals[mutualId]; @@ -184,16 +199,17 @@ library EdgeChallengeManagerLib { // other rival edges - they will all have a zero time unrivaled } - return EdgeAddedData( - eId, - mutualId, - edge.originId, - edge.claimId, - store.edges[eId].length(), - edge.level, - firstRival != 0, - edge.claimId != 0 - ); + return + EdgeAddedData( + eId, + mutualId, + edge.originId, + edge.claimId, + store.edges[eId].length(), + edge.level, + firstRival != 0, + edge.claimId != 0 + ); } /// @notice Conduct checks that are specific to the edge type. @@ -244,8 +260,10 @@ library EdgeChallengeManagerLib { if (args.proof.length == 0) { revert EmptyEdgeSpecificProof(); } - (bytes32[] memory inclusionProof,,) = - abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); + (bytes32[] memory inclusionProof, , ) = abi.decode( + args.proof, + (bytes32[], ExecutionStateData, ExecutionStateData) + ); // check the start and end execution states exist, the block hash entry should be non zero if (ard.startState.machineStatus == MachineStatus.RUNNING) { @@ -302,7 +320,10 @@ library EdgeChallengeManagerLib { // this guarantees that the edge we're creating is a 'continuation' of the claim edge, it is // a commitment to the states that between start and end states of the claim MerkleTreeLib.verifyInclusionProof( - claimEdge.startHistoryRoot, startState, claimEdge.startHeight, claimStartInclusionProof + claimEdge.startHistoryRoot, + startState, + claimEdge.startHeight, + claimStartInclusionProof ); // it's doubly important to check the end state since if the end state since the claim id is @@ -312,7 +333,10 @@ library EdgeChallengeManagerLib { // that the end history root of the new edge will be different for different claim ids, and therefore // the edge ids will be different MerkleTreeLib.verifyInclusionProof( - claimEdge.endHistoryRoot, endState, claimEdge.endHeight, claimEndInclusionProof + claimEdge.endHistoryRoot, + endState, + claimEdge.endHeight, + claimEndInclusionProof ); return (ProofData(startState, endState, edgeInclusionProof), originId); @@ -337,14 +361,16 @@ library EdgeChallengeManagerLib { /// @param proofData Data extracted from supplied proof /// @param args The edge creation args /// @param expectedEndHeight Edges have a deterministic end height dependent on their level - function layerZeroCommonChecks(ProofData memory proofData, CreateEdgeArgs calldata args, uint256 expectedEndHeight) - private - pure - returns (bytes32) - { + function layerZeroCommonChecks( + ProofData memory proofData, + CreateEdgeArgs calldata args, + uint256 expectedEndHeight + ) private pure returns (bytes32) { // since zero layer edges have a start height of zero, we know that they are a size // one tree containing only the start state. We can then compute the history root directly - bytes32 startHistoryRoot = MerkleTreeLib.root(MerkleTreeLib.appendLeaf(new bytes32[](0), proofData.startState)); + bytes32 startHistoryRoot = MerkleTreeLib.root( + MerkleTreeLib.appendLeaf(new bytes32[](0), proofData.startState) + ); // all end heights are expected to be a power of 2, the specific power is defined by the // edge challenge manager itself @@ -365,7 +391,10 @@ library EdgeChallengeManagerLib { // This ensures continuity of states between levels - the state is present in both this // level and the one below MerkleTreeLib.verifyInclusionProof( - args.endHistoryRoot, proofData.endState, args.endHeight, proofData.inclusionProof + args.endHistoryRoot, + proofData.endState, + args.endHeight, + proofData.inclusionProof ); // start root must always be a prefix of end root, we ensure that @@ -374,24 +403,39 @@ library EdgeChallengeManagerLib { if (args.prefixProof.length == 0) { revert EmptyPrefixProof(); } - (bytes32[] memory preExpansion, bytes32[] memory preProof) = - abi.decode(args.prefixProof, (bytes32[], bytes32[])); + (bytes32[] memory preExpansion, bytes32[] memory preProof) = abi.decode( + args.prefixProof, + (bytes32[], bytes32[]) + ); MerkleTreeLib.verifyPrefixProof( - startHistoryRoot, 1, args.endHistoryRoot, args.endHeight + 1, preExpansion, preProof + startHistoryRoot, + 1, + args.endHistoryRoot, + args.endHeight + 1, + preExpansion, + preProof ); return (startHistoryRoot); } /// @notice Creates a new layer zero edges from edge creation args - function toLayerZeroEdge(bytes32 originId, bytes32 startHistoryRoot, CreateEdgeArgs calldata args) - private - view - returns (ChallengeEdge memory) - { - return ChallengeEdgeLib.newLayerZeroEdge( - originId, startHistoryRoot, 0, args.endHistoryRoot, args.endHeight, args.claimId, msg.sender, args.level - ); + function toLayerZeroEdge( + bytes32 originId, + bytes32 startHistoryRoot, + CreateEdgeArgs calldata args + ) private view returns (ChallengeEdge memory) { + return + ChallengeEdgeLib.newLayerZeroEdge( + originId, + startHistoryRoot, + 0, + args.endHistoryRoot, + args.endHeight, + args.claimId, + msg.sender, + args.level + ); } /// @notice Performs necessary checks and creates a new layer zero edge @@ -413,10 +457,15 @@ library EdgeChallengeManagerLib { uint8 numBigStepLevel ) internal returns (EdgeAddedData memory) { // each edge type requires some specific checks - (ProofData memory proofData, bytes32 originId) = - layerZeroTypeSpecificChecks(store, args, ard, oneStepProofEntry, numBigStepLevel); + (ProofData memory proofData, bytes32 originId) = layerZeroTypeSpecificChecks( + store, + args, + ard, + oneStepProofEntry, + numBigStepLevel + ); // all edge types share some common checks - (bytes32 startHistoryRoot) = layerZeroCommonChecks(proofData, args, expectedEndHeight); + bytes32 startHistoryRoot = layerZeroCommonChecks(proofData, args, expectedEndHeight); // we only wrap the struct creation in a function as doing so with exceeds the stack limit ChallengeEdge memory ce = toLayerZeroEdge(originId, startHistoryRoot, args); return add(store, ce); @@ -424,7 +473,11 @@ library EdgeChallengeManagerLib { /// @notice From any given edge, get the id of the previous assertion /// @param edgeId The edge to get the prev assertion hash - function getPrevAssertionHash(EdgeStore storage store, bytes32 edgeId) internal view returns (bytes32) { + function getPrevAssertionHash(EdgeStore storage store, bytes32 edgeId) + internal + view + returns (bytes32) + { ChallengeEdge storage edge = get(store, edgeId); while (edge.level > 0) { // the origin id gives us a link to the lower level @@ -464,7 +517,11 @@ library EdgeChallengeManagerLib { /// @notice Is the edge a single step in length, and does it have at least one rival. /// @param store The edge store containing the edge /// @param edgeId The edge id to test for single step and rivaled - function hasLengthOneRival(EdgeStore storage store, bytes32 edgeId) internal view returns (bool) { + function hasLengthOneRival(EdgeStore storage store, bytes32 edgeId) + internal + view + returns (bool) + { // must be length 1 and have rivals - all rivals have the same length return (hasRival(store, edgeId) && store.edges[edgeId].length() == 1); } @@ -540,9 +597,18 @@ library EdgeChallengeManagerLib { /// @return lowerChildId The id of the newly created lower child edge /// @return lowerChildAdded Data about the lower child edge, empty if the lower child already existed /// @return upperChildAdded Data about the upper child edge, never empty - function bisectEdge(EdgeStore storage store, bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes memory prefixProof) + function bisectEdge( + EdgeStore storage store, + bytes32 edgeId, + bytes32 bisectionHistoryRoot, + bytes memory prefixProof + ) internal - returns (bytes32, EdgeAddedData memory, EdgeAddedData memory) + returns ( + bytes32, + EdgeAddedData memory, + EdgeAddedData memory + ) { if (store.edges[edgeId].status != EdgeStatus.Pending) { revert EdgeNotPending(edgeId, store.edges[edgeId].status); @@ -559,9 +625,17 @@ library EdgeChallengeManagerLib { // rival edges bisect at the same height, and create the same child if they agree uint256 middleHeight = mandatoryBisectionHeight(ce.startHeight, ce.endHeight); { - (bytes32[] memory preExpansion, bytes32[] memory proof) = abi.decode(prefixProof, (bytes32[], bytes32[])); + (bytes32[] memory preExpansion, bytes32[] memory proof) = abi.decode( + prefixProof, + (bytes32[], bytes32[]) + ); MerkleTreeLib.verifyPrefixProof( - bisectionHistoryRoot, middleHeight + 1, ce.endHistoryRoot, ce.endHeight + 1, preExpansion, proof + bisectionHistoryRoot, + middleHeight + 1, + ce.endHistoryRoot, + ce.endHeight + 1, + preExpansion, + proof ); } @@ -570,7 +644,12 @@ library EdgeChallengeManagerLib { { // midpoint proof it valid, create and store the children ChallengeEdge memory lowerChild = ChallengeEdgeLib.newChildEdge( - ce.originId, ce.startHistoryRoot, ce.startHeight, bisectionHistoryRoot, middleHeight, ce.level + ce.originId, + ce.startHistoryRoot, + ce.startHeight, + bisectionHistoryRoot, + middleHeight, + ce.level ); lowerChildId = lowerChild.idMem(); // it's possible that the store already has the lower child if it was created by a rival @@ -583,7 +662,12 @@ library EdgeChallengeManagerLib { EdgeAddedData memory upperChildAdded; { ChallengeEdge memory upperChild = ChallengeEdgeLib.newChildEdge( - ce.originId, bisectionHistoryRoot, middleHeight, ce.endHistoryRoot, ce.endHeight, ce.level + ce.originId, + bisectionHistoryRoot, + middleHeight, + ce.endHistoryRoot, + ce.endHeight, + ce.level ); // add checks existence and throws if the id already exists @@ -656,20 +740,28 @@ library EdgeChallengeManagerLib { /// @param edgeId The edge being claimed /// @param claimingEdgeId The edge with a claim id equal to edge id /// @param numBigStepLevel The number of big step levels in this challenge - function checkClaimIdLink(EdgeStore storage store, bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) - private - view - { + function checkClaimIdLink( + EdgeStore storage store, + bytes32 edgeId, + bytes32 claimingEdgeId, + uint8 numBigStepLevel + ) private view { // we do some extra checks that edge being claimed is eligible to be claimed by the claiming edge // these shouldn't be necessary since it should be impossible to add layer zero edges that do not // satisfy the checks below, but we conduct these checks anyway for double safety // the origin id of an edge should be the mutual id of the edge in the level below if (store.edges[edgeId].mutualId() != store.edges[claimingEdgeId].originId) { - revert OriginIdMutualIdMismatch(store.edges[edgeId].mutualId(), store.edges[claimingEdgeId].originId); + revert OriginIdMutualIdMismatch( + store.edges[edgeId].mutualId(), + store.edges[claimingEdgeId].originId + ); } // the claiming edge must be exactly one level below - if (nextEdgeLevel(store.edges[edgeId].level, numBigStepLevel) != store.edges[claimingEdgeId].level) { + if ( + nextEdgeLevel(store.edges[edgeId].level, numBigStepLevel) != + store.edges[claimingEdgeId].level + ) { revert EdgeLevelInvalid( edgeId, claimingEdgeId, @@ -686,9 +778,12 @@ library EdgeChallengeManagerLib { /// @param edgeId The id of the edge to confirm /// @param claimingEdgeId The id of the edge which has a claimId equal to edgeId /// @param numBigStepLevel The number of big step levels in this challenge - function confirmEdgeByClaim(EdgeStore storage store, bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) - internal - { + function confirmEdgeByClaim( + EdgeStore storage store, + bytes32 edgeId, + bytes32 claimingEdgeId, + uint8 numBigStepLevel + ) internal { if (!store.edges[edgeId].exists()) { revert EdgeNotExists(edgeId); } @@ -807,7 +902,10 @@ library EdgeChallengeManagerLib { uint256 machineStep = get(store, edgeId).startHeight; // edge must be length one and be of type SmallStep - if (ChallengeEdgeLib.levelToType(store.edges[edgeId].level, numBigStepLevel) != EdgeType.SmallStep) { + if ( + ChallengeEdgeLib.levelToType(store.edges[edgeId].level, numBigStepLevel) != + EdgeType.SmallStep + ) { revert EdgeTypeNotSmallStep(store.edges[edgeId].level); } if (store.edges[edgeId].length() != 1) { @@ -816,16 +914,26 @@ library EdgeChallengeManagerLib { // the state in the onestep data must be committed to by the startHistoryRoot MerkleTreeLib.verifyInclusionProof( - store.edges[edgeId].startHistoryRoot, oneStepData.beforeHash, machineStep, beforeHistoryInclusionProof + store.edges[edgeId].startHistoryRoot, + oneStepData.beforeHash, + machineStep, + beforeHistoryInclusionProof ); // execute the single step to produce the after state - bytes32 afterHash = - oneStepProofEntry.proveOneStep(execCtx, machineStep, oneStepData.beforeHash, oneStepData.proof); + bytes32 afterHash = oneStepProofEntry.proveOneStep( + execCtx, + machineStep, + oneStepData.beforeHash, + oneStepData.proof + ); // check that the after state was indeed committed to by the endHistoryRoot MerkleTreeLib.verifyInclusionProof( - store.edges[edgeId].endHistoryRoot, afterHash, machineStep + 1, afterHistoryInclusionProof + store.edges[edgeId].endHistoryRoot, + afterHash, + machineStep + 1, + afterHistoryInclusionProof ); // also checks that no other rival has been confirmed diff --git a/contracts/src/challengeV2/libraries/MerkleTreeLib.sol b/contracts/src/challengeV2/libraries/MerkleTreeLib.sol index dfaa1260d..1341da1dd 100644 --- a/contracts/src/challengeV2/libraries/MerkleTreeLib.sol +++ b/contracts/src/challengeV2/libraries/MerkleTreeLib.sol @@ -148,11 +148,11 @@ library MerkleTreeLib { /// @param me The merkle expansion to append a complete sub tree to /// @param level The level at which to append the complete subtree /// @param subtreeRoot The root of the complete subtree to be appended - function appendCompleteSubTree(bytes32[] memory me, uint256 level, bytes32 subtreeRoot) - internal - pure - returns (bytes32[] memory) - { + function appendCompleteSubTree( + bytes32[] memory me, + uint256 level, + bytes32 subtreeRoot + ) internal pure returns (bytes32[] memory) { // we use number representations of the levels elsewhere, so we need to ensure we're appending a leve // that's too high to use in uint require(level < MAX_LEVEL, "Level too high"); @@ -171,13 +171,14 @@ library MerkleTreeLib { bytes32 accumHash = subtreeRoot; uint256 meSize = treeSize(me); - uint256 postSize = meSize + 2 ** level; + uint256 postSize = meSize + 2**level; // if by appending the sub tree we increase the numbe of most sig bits of the size, that means // we'll need more space in the expansion to describe the tree, so we enlarge by one - bytes32[] memory next = UintUtilsLib.mostSignificantBit(postSize) > UintUtilsLib.mostSignificantBit(meSize) + bytes32[] memory next = UintUtilsLib.mostSignificantBit(postSize) > + UintUtilsLib.mostSignificantBit(meSize) ? new bytes32[](me.length + 1) - : new bytes32[](me.length ); + : new bytes32[](me.length); // ensure we're never creating an expansion that's too big require(next.length <= MAX_LEVEL, "Append creates oversize tree"); @@ -235,7 +236,11 @@ library MerkleTreeLib { /// into the tree to avoid root collisions. /// @param me The merkle expansion to append a leaf to /// @param leaf The leaf to append - will be hashed in here before appending - function appendLeaf(bytes32[] memory me, bytes32 leaf) internal pure returns (bytes32[] memory) { + function appendLeaf(bytes32[] memory me, bytes32 leaf) + internal + pure + returns (bytes32[] memory) + { // it's important that we hash the leaf, this ensures that this leaf cannot be a collision with any other non leaf // or root node, since these are always the hash of 64 bytes of data, and we're hashing 32 bytes return appendCompleteSubTree(me, 0, keccak256(abi.encodePacked(leaf))); @@ -248,7 +253,11 @@ library MerkleTreeLib { /// subtree in the expansion /// @param startSize The size of the start tree to find the maximum append to /// @param endSize The size of the end tree to find a maximum append under - function maximumAppendBetween(uint256 startSize, uint256 endSize) internal pure returns (uint256) { + function maximumAppendBetween(uint256 startSize, uint256 endSize) + internal + pure + returns (uint256) + { // Since the tree is binary we can represent it using the binary representation of a number // As described above, subtrees can only be appended to a tree if they are at the same level, or below, // the current lowest subtree. @@ -266,7 +275,7 @@ library MerkleTreeLib { // remove the high order bits that are shared uint256 msb = UintUtilsLib.mostSignificantBit(startSize ^ endSize); - uint256 mask = (1 << (msb) + 1) - 1; + uint256 mask = (1 << ((msb) + 1)) - 1; uint256 y = startSize & mask; uint256 z = endSize & mask; @@ -293,7 +302,7 @@ library MerkleTreeLib { uint256 sum = 0; for (uint256 i = 0; i < me.length; i++) { if (me[i] != 0) { - sum += 2 ** i; + sum += 2**i; } } return sum; @@ -356,11 +365,17 @@ library MerkleTreeLib { /// @param leaf The leaf preimage to prove inclusion - will be hashed in here before checking inclusion /// @param index The index of the leaf in the tree /// @param proof The path from the leaf to the root - function verifyInclusionProof(bytes32 rootHash, bytes32 leaf, uint256 index, bytes32[] memory proof) - internal - pure - { - bytes32 calculatedRoot = MerkleLib.calculateRoot(proof, index, keccak256(abi.encodePacked(leaf))); + function verifyInclusionProof( + bytes32 rootHash, + bytes32 leaf, + uint256 index, + bytes32[] memory proof + ) internal pure { + bytes32 calculatedRoot = MerkleLib.calculateRoot( + proof, + index, + keccak256(abi.encodePacked(leaf)) + ); require(rootHash == calculatedRoot, "Invalid inclusion proof"); } } diff --git a/contracts/src/challengeV2/libraries/UintUtilsLib.sol b/contracts/src/challengeV2/libraries/UintUtilsLib.sol index 82cd5423f..ad9d84331 100644 --- a/contracts/src/challengeV2/libraries/UintUtilsLib.sol +++ b/contracts/src/challengeV2/libraries/UintUtilsLib.sol @@ -16,7 +16,7 @@ library UintUtilsLib { // isolate the least sig bit uint256 isolated = ((x - 1) & x) ^ x; - + // since we removed all higher bits, least sig == most sig return mostSignificantBit(isolated); } @@ -67,4 +67,4 @@ library UintUtilsLib { // x >= 2 ** 1 if (x >= 0x2) msb += 1; } -} \ No newline at end of file +} diff --git a/contracts/src/mocks/BridgeStub.sol b/contracts/src/mocks/BridgeStub.sol index 6b183bd68..72b0d5b3f 100644 --- a/contracts/src/mocks/BridgeStub.sol +++ b/contracts/src/mocks/BridgeStub.sol @@ -163,8 +163,7 @@ contract BridgeStub is IBridge { function setOutbox( address, /* outbox */ bool /* enabled*/ - ) external pure override { - } + ) external pure override {} function delayedMessageCount() external view override returns (uint256) { return delayedInboxAccs.length; diff --git a/contracts/src/mocks/ExecutionManager.sol b/contracts/src/mocks/ExecutionManager.sol index df8b7287c..38a920913 100644 --- a/contracts/src/mocks/ExecutionManager.sol +++ b/contracts/src/mocks/ExecutionManager.sol @@ -28,7 +28,10 @@ contract SingleExecutionChallenge is OldChallengeManager { segments[1] = startAndEndHashes[1]; bytes32 challengeStateHash = OldChallengeLib.hashChallengeState(0, numSteps_, segments); challenge.challengeStateHash = challengeStateHash; - challenge.next = OldChallengeLib.Participant({addr: asserter_, timeLeft: asserterTimeLeft_}); + challenge.next = OldChallengeLib.Participant({ + addr: asserter_, + timeLeft: asserterTimeLeft_ + }); challenge.current = OldChallengeLib.Participant({ addr: challenger_, timeLeft: challengerTimeLeft_ diff --git a/contracts/src/mocks/MerkleTreeAccess.sol b/contracts/src/mocks/MerkleTreeAccess.sol index b885fc8ff..6d7a47429 100644 --- a/contracts/src/mocks/MerkleTreeAccess.sol +++ b/contracts/src/mocks/MerkleTreeAccess.sol @@ -20,19 +20,27 @@ contract MerkleTreeAccess { return MerkleTreeLib.root(me); } - function appendCompleteSubTree(bytes32[] memory me, uint256 level, bytes32 subtreeRoot) + function appendCompleteSubTree( + bytes32[] memory me, + uint256 level, + bytes32 subtreeRoot + ) external pure returns (bytes32[] memory) { + return MerkleTreeLib.appendCompleteSubTree(me, level, subtreeRoot); + } + + function appendLeaf(bytes32[] memory me, bytes32 leaf) external pure returns (bytes32[] memory) { - return MerkleTreeLib.appendCompleteSubTree(me, level, subtreeRoot); - } - - function appendLeaf(bytes32[] memory me, bytes32 leaf) external pure returns (bytes32[] memory) { return MerkleTreeLib.appendLeaf(me, leaf); } - function maximumAppendBetween(uint256 startSize, uint256 endSize) external pure returns (uint256) { + function maximumAppendBetween(uint256 startSize, uint256 endSize) + external + pure + returns (uint256) + { return MerkleTreeLib.maximumAppendBetween(startSize, endSize); } @@ -44,13 +52,23 @@ contract MerkleTreeAccess { bytes32[] memory preExpansion, bytes32[] memory proof ) external pure { - return MerkleTreeLib.verifyPrefixProof(preRoot, preSize, postRoot, postSize, preExpansion, proof); + return + MerkleTreeLib.verifyPrefixProof( + preRoot, + preSize, + postRoot, + postSize, + preExpansion, + proof + ); } - function verifyInclusionProof(bytes32 rootHash, bytes32 leaf, uint256 index, bytes32[] memory proof) - external - pure - { + function verifyInclusionProof( + bytes32 rootHash, + bytes32 leaf, + uint256 index, + bytes32[] memory proof + ) external pure { MerkleTreeLib.verifyInclusionProof(rootHash, leaf, index, proof); } } diff --git a/contracts/src/mocks/SimpleOneStepProofEntry.sol b/contracts/src/mocks/SimpleOneStepProofEntry.sol index 3916feb86..b583e5b7f 100644 --- a/contracts/src/mocks/SimpleOneStepProofEntry.sol +++ b/contracts/src/mocks/SimpleOneStepProofEntry.sol @@ -44,9 +44,13 @@ contract SimpleOneStepProofEntry is IOneStepProofEntry { return globalState.hash(); } - function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { + function getMachineHash(ExecutionState calldata execState) + external + pure + override + returns (bytes32) + { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return execState.globalState.hash(); - } } diff --git a/contracts/src/osp/OneStepProofEntry.sol b/contracts/src/osp/OneStepProofEntry.sol index 88d2104e7..ae05fd559 100644 --- a/contracts/src/osp/OneStepProofEntry.sol +++ b/contracts/src/osp/OneStepProofEntry.sol @@ -62,7 +62,12 @@ contract OneStepProofEntry is IOneStepProofEntry { return mach.hash(); } - function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { + function getMachineHash(ExecutionState calldata execState) + external + pure + override + returns (bytes32) + { if (execState.machineStatus == MachineStatus.FINISHED) { return keccak256(abi.encodePacked("Machine finished:", execState.globalState.hash())); } else if (execState.machineStatus == MachineStatus.ERRORED) { @@ -93,7 +98,11 @@ contract OneStepProofEntry is IOneStepProofEntry { GlobalState memory globalState; (globalState, offset) = Deserialize.globalState(proof, offset); require(globalState.hash() == mach.globalStateHash, "BAD_GLOBAL_STATE"); - if (mach.status == MachineStatus.FINISHED && machineStep == 0 && globalState.getInboxPosition() < execCtx.maxInboxMessagesRead) { + if ( + mach.status == MachineStatus.FINISHED && + machineStep == 0 && + globalState.getInboxPosition() < execCtx.maxInboxMessagesRead + ) { // Kickstart the machine return getStartMachineHash(mach.globalStateHash, execCtx.initialWasmModuleRoot); } diff --git a/contracts/src/rollup/Assertion.sol b/contracts/src/rollup/Assertion.sol index 0a3881c70..9364d43b3 100644 --- a/contracts/src/rollup/Assertion.sol +++ b/contracts/src/rollup/Assertion.sol @@ -69,10 +69,11 @@ library AssertionNodeLib { /** * @notice Initialize a Assertion */ - function createAssertion( - bool _isFirstChild, - bytes32 _configHash - ) internal view returns (AssertionNode memory) { + function createAssertion(bool _isFirstChild, bytes32 _configHash) + internal + view + returns (AssertionNode memory) + { AssertionNode memory assertion; assertion.createdAtBlock = uint64(block.number); assertion.isFirstChild = _isFirstChild; diff --git a/contracts/src/rollup/BOLDUpgradeAction.sol b/contracts/src/rollup/BOLDUpgradeAction.sol index 4d848d1e0..82cf694b4 100644 --- a/contracts/src/rollup/BOLDUpgradeAction.sol +++ b/contracts/src/rollup/BOLDUpgradeAction.sol @@ -65,18 +65,27 @@ interface IOldRollup { ); function wasmModuleRoot() external view returns (bytes32); + function latestConfirmed() external view returns (uint64); + function getNode(uint64 nodeNum) external view returns (Node memory); + function getStakerAddress(uint64 stakerNum) external view returns (address); + function stakerCount() external view returns (uint64); + function getStaker(address staker) external view returns (OldStaker memory); + function isValidator(address validator) external view returns (bool); + function validatorWalletCreator() external view returns (address); } interface IOldRollupAdmin { function forceRefundStaker(address[] memory stacker) external; + function pause() external; + function resume() external; } @@ -94,17 +103,36 @@ contract StateHashPreImageLookup { mapping(bytes32 => bytes) internal preImages; - function stateHash(ExecutionState calldata execState, uint256 inboxMaxCount) public pure returns (bytes32) { - return keccak256(abi.encodePacked(execState.globalState.hash(), inboxMaxCount, execState.machineStatus)); + function stateHash(ExecutionState calldata execState, uint256 inboxMaxCount) + public + pure + returns (bytes32) + { + return + keccak256( + abi.encodePacked( + execState.globalState.hash(), + inboxMaxCount, + execState.machineStatus + ) + ); } - function set(bytes32 h, ExecutionState calldata execState, uint256 inboxMaxCount) public { + function set( + bytes32 h, + ExecutionState calldata execState, + uint256 inboxMaxCount + ) public { require(h == stateHash(execState, inboxMaxCount), "Invalid hash"); preImages[h] = abi.encode(execState, inboxMaxCount); emit HashSet(h, execState, inboxMaxCount); } - function get(bytes32 h) public view returns (ExecutionState memory execState, uint256 inboxMaxCount) { + function get(bytes32 h) + public + view + returns (ExecutionState memory execState, uint256 inboxMaxCount) + { (execState, inboxMaxCount) = abi.decode(preImages[h], (ExecutionState, uint256)); require(inboxMaxCount != 0, "Hash not yet set"); } @@ -320,15 +348,21 @@ contract BOLDUpgradeAction { } // upgrade the rollup to one that allows validators to withdraw even whilst paused - DoubleLogicUUPSUpgradeable(address(OLD_ROLLUP)).upgradeSecondaryTo(IMPL_PATCHED_OLD_ROLLUP_USER); + DoubleLogicUUPSUpgradeable(address(OLD_ROLLUP)).upgradeSecondaryTo( + IMPL_PATCHED_OLD_ROLLUP_USER + ); } /// @dev Create a config for the new rollup - fetches the latest confirmed /// assertion from the old rollup and uses it as genesis function createConfig() private view returns (Config memory) { // fetch the assertion associated with the latest confirmed state - bytes32 latestConfirmedStateHash = ROLLUP_READER.getNode(ROLLUP_READER.latestConfirmed()).stateHash; - (ExecutionState memory genesisExecState, uint256 inboxMaxCount) = PREIMAGE_LOOKUP.get(latestConfirmedStateHash); + bytes32 latestConfirmedStateHash = ROLLUP_READER + .getNode(ROLLUP_READER.latestConfirmed()) + .stateHash; + (ExecutionState memory genesisExecState, uint256 inboxMaxCount) = PREIMAGE_LOOKUP.get( + latestConfirmedStateHash + ); // double check the hash require( PREIMAGE_LOOKUP.stateHash(genesisExecState, inboxMaxCount) == latestConfirmedStateHash, @@ -338,26 +372,27 @@ contract BOLDUpgradeAction { // this isnt used during rollup creation, so we can pass in empty ISequencerInbox.MaxTimeVariation memory maxTimeVariation; - return Config({ - confirmPeriodBlocks: CONFIRM_PERIOD_BLOCKS, - stakeToken: STAKE_TOKEN, - baseStake: STAKE_AMOUNT, - wasmModuleRoot: ROLLUP_READER.wasmModuleRoot(), - owner: address(this), // upgrade executor is the owner - loserStakeEscrow: L1_TIMELOCK, // additional funds get sent to the l1 timelock - chainId: CHAIN_ID, - chainConfig: "", // we can use an empty chain config it wont be used in the rollup initialization because we check if the rei is already connected there - miniStakeValue: MINI_STAKE_AMOUNT, - sequencerInboxMaxTimeVariation: maxTimeVariation, - layerZeroBlockEdgeHeight: BLOCK_LEAF_SIZE, - layerZeroBigStepEdgeHeight: BIGSTEP_LEAF_SIZE, - layerZeroSmallStepEdgeHeight: SMALLSTEP_LEAF_SIZE, - genesisExecutionState: genesisExecState, - genesisInboxCount: inboxMaxCount, - anyTrustFastConfirmer: ANY_TRUST_FAST_CONFIRMER, - numBigStepLevel: NUM_BIGSTEP_LEVEL, - challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS - }); + return + Config({ + confirmPeriodBlocks: CONFIRM_PERIOD_BLOCKS, + stakeToken: STAKE_TOKEN, + baseStake: STAKE_AMOUNT, + wasmModuleRoot: ROLLUP_READER.wasmModuleRoot(), + owner: address(this), // upgrade executor is the owner + loserStakeEscrow: L1_TIMELOCK, // additional funds get sent to the l1 timelock + chainId: CHAIN_ID, + chainConfig: "", // we can use an empty chain config it wont be used in the rollup initialization because we check if the rei is already connected there + miniStakeValue: MINI_STAKE_AMOUNT, + sequencerInboxMaxTimeVariation: maxTimeVariation, + layerZeroBlockEdgeHeight: BLOCK_LEAF_SIZE, + layerZeroBigStepEdgeHeight: BIGSTEP_LEAF_SIZE, + layerZeroSmallStepEdgeHeight: SMALLSTEP_LEAF_SIZE, + genesisExecutionState: genesisExecState, + genesisInboxCount: inboxMaxCount, + anyTrustFastConfirmer: ANY_TRUST_FAST_CONFIRMER, + numBigStepLevel: NUM_BIGSTEP_LEVEL, + challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS + }); } function upgradeSurroundingContracts(address newRollupAddress) private { @@ -367,28 +402,42 @@ contract BOLDUpgradeAction { TransparentUpgradeableProxy bridge = TransparentUpgradeableProxy(payable(BRIDGE)); address currentBridgeImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation(bridge); PROXY_ADMIN_BRIDGE.upgradeAndCall( - bridge, IMPL_BRIDGE, abi.encodeWithSelector(IBridge.updateRollupAddress.selector, newRollupAddress) + bridge, + IMPL_BRIDGE, + abi.encodeWithSelector(IBridge.updateRollupAddress.selector, newRollupAddress) ); PROXY_ADMIN_BRIDGE.upgrade(bridge, currentBridgeImpl); - TransparentUpgradeableProxy sequencerInbox = TransparentUpgradeableProxy(payable(SEQ_INBOX)); - address currentSequencerInboxImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation(sequencerInbox); + TransparentUpgradeableProxy sequencerInbox = TransparentUpgradeableProxy( + payable(SEQ_INBOX) + ); + address currentSequencerInboxImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation( + sequencerInbox + ); PROXY_ADMIN_SEQUENCER_INBOX.upgradeAndCall( - sequencerInbox, IMPL_SEQUENCER_INBOX, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + sequencerInbox, + IMPL_SEQUENCER_INBOX, + abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_SEQUENCER_INBOX.upgrade(sequencerInbox, currentSequencerInboxImpl); TransparentUpgradeableProxy rollupEventInbox = TransparentUpgradeableProxy(payable(REI)); - address currentRollupEventInboxImpl = PROXY_ADMIN_REI.getProxyImplementation(rollupEventInbox); + address currentRollupEventInboxImpl = PROXY_ADMIN_REI.getProxyImplementation( + rollupEventInbox + ); PROXY_ADMIN_REI.upgradeAndCall( - rollupEventInbox, IMPL_REI, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + rollupEventInbox, + IMPL_REI, + abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_REI.upgrade(rollupEventInbox, currentRollupEventInboxImpl); TransparentUpgradeableProxy outbox = TransparentUpgradeableProxy(payable(OUTBOX)); address currentOutboxImpl = PROXY_ADMIN_REI.getProxyImplementation(outbox); PROXY_ADMIN_OUTBOX.upgradeAndCall( - outbox, IMPL_OUTBOX, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + outbox, + IMPL_OUTBOX, + abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_OUTBOX.upgrade(outbox, currentOutboxImpl); } @@ -428,8 +477,10 @@ contract BOLDUpgradeAction { // upgrade the surrounding contracts eg bridge, outbox, seq inbox, rollup event inbox // to set of the new rollup address bytes32 rollupSalt = keccak256(abi.encode(config)); - address expectedRollupAddress = - Create2Upgradeable.computeAddress(rollupSalt, keccak256(type(RollupProxy).creationCode)); + address expectedRollupAddress = Create2Upgradeable.computeAddress( + rollupSalt, + keccak256(type(RollupProxy).creationCode) + ); upgradeSurroundingContracts(expectedRollupAddress); challengeManager.initialize({ @@ -445,7 +496,7 @@ contract BOLDUpgradeAction { _numBigStepLevel: config.numBigStepLevel }); - RollupProxy rollup = new RollupProxy{ salt: rollupSalt}(); + RollupProxy rollup = new RollupProxy{salt: rollupSalt}(); require(address(rollup) == expectedRollupAddress, "UNEXPCTED_ROLLUP_ADDR"); // initialize the rollup with this contract as owner to set batch poster and validators @@ -464,7 +515,9 @@ contract BOLDUpgradeAction { IRollupAdmin(address(rollup)).setValidator(validators, _vals); } if (DISABLE_VALIDATOR_WHITELIST) { - IRollupAdmin(address(rollup)).setValidatorWhitelistDisabled(DISABLE_VALIDATOR_WHITELIST); + IRollupAdmin(address(rollup)).setValidatorWhitelistDisabled( + DISABLE_VALIDATOR_WHITELIST + ); } IRollupAdmin(address(rollup)).setOwner(actualOwner); diff --git a/contracts/src/rollup/IRollupAdmin.sol b/contracts/src/rollup/IRollupAdmin.sol index bd1d288ad..5ec67c9c3 100644 --- a/contracts/src/rollup/IRollupAdmin.sol +++ b/contracts/src/rollup/IRollupAdmin.sol @@ -13,7 +13,8 @@ import "./Config.sol"; interface IRollupAdmin { event OwnerFunctionCalled(uint256 indexed id); - function initialize(Config calldata config, ContractDependencies calldata connectedContracts) external; + function initialize(Config calldata config, ContractDependencies calldata connectedContracts) + external; /** * @notice Add a contract authorized to put messages into this rollup's inbox diff --git a/contracts/src/rollup/IRollupCore.sol b/contracts/src/rollup/IRollupCore.sol index 156c9c926..ab832a920 100644 --- a/contracts/src/rollup/IRollupCore.sol +++ b/contracts/src/rollup/IRollupCore.sol @@ -36,12 +36,19 @@ interface IRollupCore is IAssertionChain { event AssertionConfirmed(bytes32 indexed assertionHash, bytes32 blockHash, bytes32 sendRoot); event RollupChallengeStarted( - uint64 indexed challengeIndex, address asserter, address challenger, uint64 challengedAssertion + uint64 indexed challengeIndex, + address asserter, + address challenger, + uint64 challengedAssertion ); event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); - event UserWithdrawableFundsUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); + event UserWithdrawableFundsUpdated( + address indexed user, + uint256 initialBalance, + uint256 finalBalance + ); function confirmPeriodBlocks() external view returns (uint64); @@ -83,7 +90,10 @@ interface IRollupCore is IAssertionChain { * This function will revert if the given assertion hash does not exist. * @dev This function is meant for internal use only and has no stability guarantees. */ - function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) external view returns (uint256); + function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) + external + view + returns (uint256); /** * @notice Get the address of the staker at the given index @@ -126,6 +136,7 @@ interface IRollupCore is IAssertionChain { * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view returns (uint256); + /// @return Index of the latest confirmed assertion function latestConfirmed() external view returns (bytes32); diff --git a/contracts/src/rollup/IRollupLogic.sol b/contracts/src/rollup/IRollupLogic.sol index d1e2f5de9..9221f870c 100644 --- a/contracts/src/rollup/IRollupLogic.sol +++ b/contracts/src/rollup/IRollupLogic.sol @@ -27,7 +27,8 @@ interface IRollupUser is IRollupCore, IOwnable { bytes32 inboxAcc ) external; - function stakeOnNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) external; + function stakeOnNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) + external; function returnOldDeposit() external; diff --git a/contracts/src/rollup/RollupAdminLogic.sol b/contracts/src/rollup/RollupAdminLogic.sol index 7b383b2ad..647c19214 100644 --- a/contracts/src/rollup/RollupAdminLogic.sol +++ b/contracts/src/rollup/RollupAdminLogic.sol @@ -31,12 +31,25 @@ contract RollupAdminLogic is RollupCore, IRollupAdmin, DoubleLogicUUPSUpgradeabl // dont need to connect and initialize the event inbox if it's already been initialized if (!bridge.allowedDelayedInboxes(address(connectedContracts.rollupEventInbox))) { - connectedContracts.bridge.setDelayedInbox(address(connectedContracts.rollupEventInbox), true); - connectedContracts.rollupEventInbox.rollupInitialized(config.chainId, config.chainConfig); + connectedContracts.bridge.setDelayedInbox( + address(connectedContracts.rollupEventInbox), + true + ); + connectedContracts.rollupEventInbox.rollupInitialized( + config.chainId, + config.chainConfig + ); } if (connectedContracts.sequencerInbox.totalDelayedMessagesRead() == 0) { - connectedContracts.sequencerInbox.addSequencerL2Batch(0, "", 1, IGasRefunder(address(0)), 0, 1); + connectedContracts.sequencerInbox.addSequencerL2Batch( + 0, + "", + 1, + IGasRefunder(address(0)), + 0, + 1 + ); } validatorWalletCreator = connectedContracts.validatorWalletCreator; diff --git a/contracts/src/rollup/RollupCore.sol b/contracts/src/rollup/RollupCore.sol index d8ea8020c..6a2bf5b97 100644 --- a/contracts/src/rollup/RollupCore.sol +++ b/contracts/src/rollup/RollupCore.sol @@ -123,7 +123,11 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { * @param assertionHash Id of the assertion * @return Assertion struct */ - function getAssertionStorage(bytes32 assertionHash) internal view returns (AssertionNode storage) { + function getAssertionStorage(bytes32 assertionHash) + internal + view + returns (AssertionNode storage) + { require(assertionHash != bytes32(0), "ASSERTION_ID_CANNOT_BE_ZERO"); return _assertions[assertionHash]; } @@ -131,7 +135,12 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { /** * @notice Get the Assertion for the given index. */ - function getAssertion(bytes32 assertionHash) public view override returns (AssertionNode memory) { + function getAssertion(bytes32 assertionHash) + public + view + override + returns (AssertionNode memory) + { return getAssertionStorage(assertionHash); } @@ -142,7 +151,12 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { * This function will revert if the given assertion hash does not exist. * @dev This function is meant for internal use only and has no stability guarantees. */ - function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) external view override returns (uint256) { + function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) + external + view + override + returns (uint256) + { if (_hostChainIsArbitrum) { uint256 blockNum = _assertionCreatedAtArbSysBlock[assertionHash]; require(blockNum > 0, "NO_ASSERTION"); @@ -245,8 +259,8 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // Authenticate data against assertionHash pre-image require( - assertionHash - == RollupLib.assertionHash({ + assertionHash == + RollupLib.assertionHash({ parentAssertionHash: parentAssertionHash, afterState: confirmState, inboxAcc: inboxAcc @@ -367,15 +381,16 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { ) internal returns (bytes32) { // Validate the config hash RollupLib.validateConfigHash( - assertion.beforeStateData.configData, getAssertionStorage(prevAssertionHash).configHash + assertion.beforeStateData.configData, + getAssertionStorage(prevAssertionHash).configHash ); // reading inbox messages always terminates in either a finished or errored state // although the challenge protocol that any invalid terminal state will be proven incorrect // we can do a quick sanity check here require( - assertion.afterState.machineStatus == MachineStatus.FINISHED - || assertion.afterState.machineStatus == MachineStatus.ERRORED, + assertion.afterState.machineStatus == MachineStatus.FINISHED || + assertion.afterState.machineStatus == MachineStatus.ERRORED, "BAD_AFTER_STATUS" ); @@ -413,7 +428,10 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // All types of assertion must have inbox position in the range prev.inboxPosition <= x <= prev.nextInboxPosition require(afterInboxPosition >= prevInboxPosition, "INBOX_BACKWARDS"); - require(afterInboxPosition <= assertion.beforeStateData.configData.nextInboxPosition, "INBOX_TOO_FAR"); + require( + afterInboxPosition <= assertion.beforeStateData.configData.nextInboxPosition, + "INBOX_TOO_FAR" + ); // SANITY CHECK: the next inbox position did indeed move forward // this is enforced by code in a later section that artificially increases the nextInboxPosition @@ -421,14 +439,19 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // this ensures that assertions will continue to advance. // It also means that below, where we check that afterInboxPosition equals prev.nextInboxPosition // in the FINISHED state, we can be sure that it processed at least one message - require(assertion.beforeStateData.configData.nextInboxPosition > prevInboxPosition, "NEXT_INBOX_BACKWARDS"); + require( + assertion.beforeStateData.configData.nextInboxPosition > prevInboxPosition, + "NEXT_INBOX_BACKWARDS" + ); // if the position in the message is > 0, then the afterInboxPosition cannot be the nextInboxPosition // as this would be outside the range - this can only occur for ERRORED states if (assertion.afterState.machineStatus == MachineStatus.ERRORED) { if (assertion.afterState.globalState.getPositionInMessage() > 0) { require( - afterInboxPosition != assertion.beforeStateData.configData.nextInboxPosition, "POSITION_TOO_FAR" + afterInboxPosition != + assertion.beforeStateData.configData.nextInboxPosition, + "POSITION_TOO_FAR" ); } } else if (assertion.afterState.machineStatus == MachineStatus.FINISHED) { @@ -438,7 +461,10 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { "INVALID_FINISHED_INBOX" ); // and it should have position in message == 0, ready to start reading the next message - require(assertion.afterState.globalState.getPositionInMessage() == 0, "NON_ZERO_FINISHED_POS_IN_MSG"); + require( + assertion.afterState.globalState.getPositionInMessage() == 0, + "NON_ZERO_FINISHED_POS_IN_MSG" + ); } else { // we checked this above, but include a safety check here in case of refactoring revert("INVALID_STATUS"); @@ -454,7 +480,8 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // in this case we need to ensure when the assertion is made the inbox messages are available // to ensure that a valid assertion can actually be made. require( - assertion.beforeStateData.configData.nextInboxPosition <= currentInboxPosition, "INBOX_NOT_POPULATED" + assertion.beforeStateData.configData.nextInboxPosition <= currentInboxPosition, + "INBOX_NOT_POPULATED" ); // The next assertion must consume all the messages that are currently found in the inbox @@ -481,7 +508,11 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { sequencerBatchAcc = bridge.sequencerInboxAccs(afterInboxPosition - 1); } - bytes32 newAssertionHash = RollupLib.assertionHash(prevAssertionHash, assertion.afterState, sequencerBatchAcc); + bytes32 newAssertionHash = RollupLib.assertionHash( + prevAssertionHash, + assertion.afterState, + sequencerBatchAcc + ); // allow an assertion creator to ensure that they're creating their assertion against the expected state require( @@ -492,7 +523,10 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // the assertion hash is unique - it's only possible to have one correct assertion hash // per assertion. Therefore we can check if this assertion has already been made, and if so // we can revert - require(getAssertionStorage(newAssertionHash).status == AssertionStatus.NoAssertion, "ASSERTION_SEEN"); + require( + getAssertionStorage(newAssertionHash).status == AssertionStatus.NoAssertion, + "ASSERTION_SEEN" + ); // state updates AssertionNode memory newAssertion = AssertionNodeLib.createAssertion( @@ -523,7 +557,8 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { confirmPeriodBlocks ); if (_hostChainIsArbitrum) { - _assertionCreatedAtArbSysBlock[newAssertionHash] = ArbSys(address(100)).arbBlockNumber(); + _assertionCreatedAtArbSysBlock[newAssertionHash] = ArbSys(address(100)) + .arbBlockNumber(); } return newAssertionHash; @@ -531,14 +566,18 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { function genesisAssertionHash() external pure returns (bytes32) { GlobalState memory emptyGlobalState; - ExecutionState memory emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); + ExecutionState memory emptyExecutionState = ExecutionState( + emptyGlobalState, + MachineStatus.FINISHED + ); bytes32 parentAssertionHash = bytes32(0); bytes32 inboxAcc = bytes32(0); - return RollupLib.assertionHash({ - parentAssertionHash: parentAssertionHash, - afterState: emptyExecutionState, - inboxAcc: inboxAcc - }); + return + RollupLib.assertionHash({ + parentAssertionHash: parentAssertionHash, + afterState: emptyExecutionState, + inboxAcc: inboxAcc + }); } function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64) { @@ -555,7 +594,10 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { bytes32 prevAssertionHash, bytes32 inboxAcc ) external pure { - require(assertionHash == RollupLib.assertionHash(prevAssertionHash, state, inboxAcc), "INVALID_ASSERTION_HASH"); + require( + assertionHash == RollupLib.assertionHash(prevAssertionHash, state, inboxAcc), + "INVALID_ASSERTION_HASH" + ); } function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view { diff --git a/contracts/src/rollup/RollupCreator.sol b/contracts/src/rollup/RollupCreator.sol index 293ec3e34..62a80670e 100644 --- a/contracts/src/rollup/RollupCreator.sol +++ b/contracts/src/rollup/RollupCreator.sol @@ -15,7 +15,11 @@ import "./IRollupAdmin.sol"; contract RollupCreator is Ownable { event RollupCreated( - address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge + address indexed rollupAddress, + address inboxAddress, + address adminProxy, + address sequencerInbox, + address bridge ); event TemplatesUpdated(); @@ -47,10 +51,11 @@ contract RollupCreator is Ownable { } // internal function to workaround stack limit - function createChallengeManager(address rollupAddr, address proxyAdminAddr, Config memory config) - internal - returns (IEdgeChallengeManager) - { + function createChallengeManager( + address rollupAddr, + address proxyAdminAddr, + Config memory config + ) internal returns (IEdgeChallengeManager) { IEdgeChallengeManager challengeManager = IEdgeChallengeManager( address( new TransparentUpgradeableProxy( @@ -109,24 +114,49 @@ contract RollupCreator is Ownable { uint256 maxDataSize ) public returns (address) { // Make sure the immutable maxDataSize is as expected - require(maxDataSize == bridgeCreator.sequencerInboxTemplate().maxDataSize(), "SI_MAX_DATA_SIZE_MISMATCH"); - require(maxDataSize == bridgeCreator.inboxTemplate().maxDataSize(), "I_MAX_DATA_SIZE_MISMATCH"); + require( + maxDataSize == bridgeCreator.sequencerInboxTemplate().maxDataSize(), + "SI_MAX_DATA_SIZE_MISMATCH" + ); + require( + maxDataSize == bridgeCreator.inboxTemplate().maxDataSize(), + "I_MAX_DATA_SIZE_MISMATCH" + ); DeployedContracts memory deployed; deployed.proxyAdmin = new ProxyAdmin(); deployed.proxyAdmin.transferOwnership(config.owner); // Create the rollup proxy to figure out the address and initialize it later - deployed.rollup = - new RollupProxy{salt: keccak256(abi.encode(config, _batchPoster, _validators, disableValidatorWhitelist, maxDataSize))}(); - - (deployed.bridge, deployed.sequencerInbox, deployed.inbox, deployed.rollupEventInbox, deployed.outbox) = - bridgeCreator.createBridge( - address(deployed.proxyAdmin), address(deployed.rollup), config.sequencerInboxMaxTimeVariation + deployed.rollup = new RollupProxy{ + salt: keccak256( + abi.encode( + config, + _batchPoster, + _validators, + disableValidatorWhitelist, + maxDataSize + ) + ) + }(); + + ( + deployed.bridge, + deployed.sequencerInbox, + deployed.inbox, + deployed.rollupEventInbox, + deployed.outbox + ) = bridgeCreator.createBridge( + address(deployed.proxyAdmin), + address(deployed.rollup), + config.sequencerInboxMaxTimeVariation ); - deployed.challengeManager = - createChallengeManager(address(deployed.rollup), address(deployed.proxyAdmin), config); + deployed.challengeManager = createChallengeManager( + address(deployed.rollup), + address(deployed.proxyAdmin), + config + ); // initialize the rollup with this contract as owner to set batch poster and validators // it will transfer the ownership back to the actual owner later @@ -161,7 +191,9 @@ contract RollupCreator is Ownable { IRollupAdmin(address(deployed.rollup)).setValidator(_validators, _vals); } if (disableValidatorWhitelist == true) { - IRollupAdmin(address(deployed.rollup)).setValidatorWhitelistDisabled(disableValidatorWhitelist); + IRollupAdmin(address(deployed.rollup)).setValidatorWhitelistDisabled( + disableValidatorWhitelist + ); } IRollupAdmin(address(deployed.rollup)).setOwner(actualOwner); diff --git a/contracts/src/rollup/RollupLib.sol b/contracts/src/rollup/RollupLib.sol index be62d6e66..61baf2d2f 100644 --- a/contracts/src/rollup/RollupLib.sol +++ b/contracts/src/rollup/RollupLib.sol @@ -31,11 +31,7 @@ library RollupLib { bytes32 inboxAcc ) internal pure returns (bytes32) { // we can no longer have `hasSibling` in the assertion hash as it would allow identical assertions - return assertionHash( - parentAssertionHash, - executionStateHash(afterState), - inboxAcc - ); + return assertionHash(parentAssertionHash, executionStateHash(afterState), inboxAcc); } // Takes in a hash of the afterState instead of the afterState itself @@ -45,14 +41,7 @@ library RollupLib { bytes32 inboxAcc ) internal pure returns (bytes32) { // we can no longer have `hasSibling` in the assertion hash as it would allow identical assertions - return - keccak256( - abi.encodePacked( - parentAssertionHash, - afterStateHash, - inboxAcc - ) - ); + return keccak256(abi.encodePacked(parentAssertionHash, afterStateHash, inboxAcc)); } // All these should be emited in AssertionCreated event @@ -75,13 +64,10 @@ library RollupLib { ); } - function validateConfigHash( - ConfigData calldata configData, - bytes32 _configHash - ) internal pure { + function validateConfigHash(ConfigData calldata configData, bytes32 _configHash) internal pure { require( - _configHash - == configHash( + _configHash == + configHash( configData.wasmModuleRoot, configData.requiredStake, configData.challengeManager, diff --git a/contracts/src/rollup/RollupProxy.sol b/contracts/src/rollup/RollupProxy.sol index aa490fc83..28bf3aa1f 100644 --- a/contracts/src/rollup/RollupProxy.sol +++ b/contracts/src/rollup/RollupProxy.sol @@ -19,11 +19,7 @@ contract RollupProxy is AdminFallbackProxy { ) { _initialize( address(connectedContracts.rollupAdminLogic), - abi.encodeCall( - IRollupAdmin.initialize, - (config, - connectedContracts) - ), + abi.encodeCall(IRollupAdmin.initialize, (config, connectedContracts)), address(connectedContracts.rollupUserLogic), abi.encodeCall(IRollupUser.initialize, (config.stakeToken)), config.owner diff --git a/contracts/src/rollup/RollupUserLogic.sol b/contracts/src/rollup/RollupUserLogic.sol index a23500b6b..9ba088d11 100644 --- a/contracts/src/rollup/RollupUserLogic.sol +++ b/contracts/src/rollup/RollupUserLogic.sol @@ -88,16 +88,16 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { bytes32 inboxAcc ) external onlyValidator whenNotPaused { /* - * To confirm an assertion, the following must be true: - * 1. The assertion must be pending - * 2. The assertion's deadline must have passed - * 3. The assertion's prev must be latest confirmed - * 4. The assertion's prev's child confirm deadline must have passed - * 5. If the assertion's prev has more than 1 child, the assertion must be the winner of the challenge - * - * Note that we do not need to ever reject invalid assertion because they can never confirm - * and the stake on them is swept to the loserStakeEscrow as soon as the leaf is created - */ + * To confirm an assertion, the following must be true: + * 1. The assertion must be pending + * 2. The assertion's deadline must have passed + * 3. The assertion's prev must be latest confirmed + * 4. The assertion's prev's child confirm deadline must have passed + * 5. If the assertion's prev has more than 1 child, the assertion must be the winner of the challenge + * + * Note that we do not need to ever reject invalid assertion because they can never confirm + * and the stake on them is swept to the loserStakeEscrow as soon as the leaf is created + */ // The assertion's must exists and be pending and will be validated in RollupCore.confirmAssertionInternal AssertionNode storage assertion = getAssertionStorage(assertionHash); @@ -107,14 +107,18 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { RollupLib.validateConfigHash(prevConfig, prevAssertion.configHash); // Check that deadline has passed - require(block.number >= assertion.createdAtBlock + prevConfig.confirmPeriodBlocks, "BEFORE_DEADLINE"); + require( + block.number >= assertion.createdAtBlock + prevConfig.confirmPeriodBlocks, + "BEFORE_DEADLINE" + ); // Check that prev is latest confirmed require(prevAssertionHash == latestConfirmed(), "PREV_NOT_LATEST_CONFIRMED"); if (prevAssertion.secondChildBlock > 0) { // if the prev has more than 1 child, check if this assertion is the challenge winner - ChallengeEdge memory winningEdge = IEdgeChallengeManager(prevConfig.challengeManager).getEdge(winningEdgeId); + ChallengeEdge memory winningEdge = IEdgeChallengeManager(prevConfig.challengeManager) + .getEdge(winningEdgeId); require(winningEdge.claimId == assertionHash, "NOT_WINNER"); require(winningEdge.status == EdgeStatus.Confirmed, "EDGE_NOT_CONFIRMED"); require(winningEdge.confirmedAtBlock != 0, "ZERO_CONFIRMED_AT_BLOCK"); @@ -147,11 +151,11 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param prevAssertionHash The hash of the assertion's parent * @param inboxAcc The inbox batch accumulator */ - function computeAssertionHash(bytes32 prevAssertionHash, ExecutionState calldata state, bytes32 inboxAcc) - external - pure - returns (bytes32) - { + function computeAssertionHash( + bytes32 prevAssertionHash, + ExecutionState calldata state, + bytes32 inboxAcc + ) external pure returns (bytes32) { return RollupLib.assertionHash(prevAssertionHash, state, inboxAcc); } @@ -167,8 +171,8 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { { // Early revert on duplicated assertion if expectedAssertionHash is set require( - expectedAssertionHash == bytes32(0) - || getAssertionStorage(expectedAssertionHash).status == AssertionStatus.NoAssertion, + expectedAssertionHash == bytes32(0) || + getAssertionStorage(expectedAssertionHash).status == AssertionStatus.NoAssertion, "EXPECTED_ASSERTION_SEEN" ); @@ -179,7 +183,10 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // the staker may have more than enough stake, and the entire stake will be locked // we cannot do a refund here because the staker may be staker on an unconfirmed ancestor that requires more stake // excess stake can be removed by calling reduceDeposit when the staker is inactive - require(amountStaked(msg.sender) >= assertion.beforeStateData.configData.requiredStake, "INSUFFICIENT_STAKE"); + require( + amountStaked(msg.sender) >= assertion.beforeStateData.configData.requiredStake, + "INSUFFICIENT_STAKE" + ); bytes32 prevAssertion = RollupLib.assertionHash( assertion.beforeStateData.prevPrevAssertionHash, @@ -193,7 +200,8 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // b) its last staked assertion have a child bytes32 lastAssertion = latestStakedAssertion(msg.sender); require( - lastAssertion == prevAssertion || getAssertionStorage(lastAssertion).firstChildBlock > 0, + lastAssertion == prevAssertion || + getAssertionStorage(lastAssertion).firstChildBlock > 0, "STAKED_ON_ANOTHER_BRANCH" ); @@ -201,7 +209,11 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // Verify that assertion meets the minimum Delta time requirement require(timeSincePrev >= minimumAssertionPeriod, "TIME_DELTA"); - bytes32 newAssertionHash = createNewAssertion(assertion, prevAssertion, expectedAssertionHash); + bytes32 newAssertionHash = createNewAssertion( + assertion, + prevAssertion, + expectedAssertionHash + ); _stakerMap[msg.sender].latestStakedAssertion = newAssertionHash; if (!getAssertionStorage(newAssertionHash).isFirstChild) { @@ -209,7 +221,10 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // only 1 of the children can be confirmed and get their stake refunded // so we send the other children's stake to the loserStakeEscrow // NOTE: if the losing staker have staked more than requiredStake, the excess stake will be stuck - increaseWithdrawableFunds(loserStakeEscrow, assertion.beforeStateData.configData.requiredStake); + increaseWithdrawableFunds( + loserStakeEscrow, + assertion.beforeStateData.configData.requiredStake + ); } } @@ -226,7 +241,11 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param stakerAddress Address of the staker whose stake is increased * @param depositAmount The amount of either eth or tokens deposited */ - function _addToDeposit(address stakerAddress, uint256 depositAmount) internal onlyValidator whenNotPaused { + function _addToDeposit(address stakerAddress, uint256 depositAmount) + internal + onlyValidator + whenNotPaused + { require(isStaked(stakerAddress), "NOT_STAKED"); increaseStakeBy(stakerAddress, depositAmount); } @@ -267,10 +286,10 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * as doing so would result in incorrect accounting of withdrawable funds in the loserStakeEscrow. * This is because the protocol assume there is only 1 unique confirmable child assertion. */ - function fastConfirmNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) - external - whenNotPaused - { + function fastConfirmNewAssertion( + AssertionInputs calldata assertion, + bytes32 expectedAssertionHash + ) external whenNotPaused { // Must supply expectedAssertionHash to fastConfirmNewAssertion require(expectedAssertionHash != bytes32(0), "EXPECTED_ASSERTION_HASH"); AssertionStatus status = getAssertionStorage(expectedAssertionHash).status; @@ -284,12 +303,19 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { if (status == AssertionStatus.NoAssertion) { // If not exists, we create the new assertion - bytes32 newAssertionHash = createNewAssertion(assertion, prevAssertion, expectedAssertionHash); + bytes32 newAssertionHash = createNewAssertion( + assertion, + prevAssertion, + expectedAssertionHash + ); if (!getAssertionStorage(newAssertionHash).isFirstChild) { // only 1 of the children can be confirmed and get their stake refunded // so we send the other children's stake to the loserStakeEscrow // NOTE: if the losing staker have staked more than requiredStake, the excess stake will be stuck - increaseWithdrawableFunds(loserStakeEscrow, assertion.beforeStateData.configData.requiredStake); + increaseWithdrawableFunds( + loserStakeEscrow, + assertion.beforeStateData.configData.requiredStake + ); } } @@ -328,7 +354,11 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param stakerAddress Address of the staker whose stake is increased * @param tokenAmount the amount of tokens staked */ - function addToDeposit(address stakerAddress, uint256 tokenAmount) external onlyValidator whenNotPaused { + function addToDeposit(address stakerAddress, uint256 tokenAmount) + external + onlyValidator + whenNotPaused + { _addToDeposit(stakerAddress, tokenAmount); /// @dev This is an external call, safe because it's at the end of the function receiveTokens(tokenAmount); diff --git a/contracts/src/rollup/ValidatorWallet.sol b/contracts/src/rollup/ValidatorWallet.sol index f064710f5..0a56c2598 100644 --- a/contracts/src/rollup/ValidatorWallet.sol +++ b/contracts/src/rollup/ValidatorWallet.sol @@ -160,7 +160,9 @@ contract ValidatorWallet is OwnableUpgradeable, DelegateCallAware, GasRefundEnab } } - function timeoutChallenges(IOldChallengeManager manager, uint64[] calldata challenges) external { + function timeoutChallenges(IOldChallengeManager manager, uint64[] calldata challenges) + external + { timeoutChallengesWithGasRefunder(IGasRefunder(address(0)), manager, challenges); } diff --git a/contracts/test/ERC20Mock.sol b/contracts/test/ERC20Mock.sol index b271b30c1..f114b92d1 100644 --- a/contracts/test/ERC20Mock.sol +++ b/contracts/test/ERC20Mock.sol @@ -38,4 +38,4 @@ contract ERC20Mock is ERC20 { ) public { _approve(owner, spender, value); } -} \ No newline at end of file +} diff --git a/contracts/test/MockAssertionChain.sol b/contracts/test/MockAssertionChain.sol index af9e21af8..84588c5da 100644 --- a/contracts/test/MockAssertionChain.sol +++ b/contracts/test/MockAssertionChain.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.17; import "forge-std/Test.sol"; import {IAssertionChain} from "../src/challengeV2/IAssertionChain.sol"; -import { IEdgeChallengeManager } from "../src/challengeV2/EdgeChallengeManager.sol"; +import {IEdgeChallengeManager} from "../src/challengeV2/EdgeChallengeManager.sol"; import "../src/bridge/IBridge.sol"; import "../src/rollup/RollupLib.sol"; import "./challengeV2/StateTools.sol"; @@ -32,7 +32,7 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].height != 0; } - function stakeToken() public view returns(address) { + function stakeToken() public view returns (address) { return address(0); } @@ -44,7 +44,10 @@ contract MockAssertionChain is IAssertionChain { ) external view { require(assertionExists(assertionHash), "Assertion does not exist"); // TODO: HN: This is not how the real assertion chain calculate assertion hash - require(assertionHash == calculateAssertionHash(prevAssertionHash, state), "INVALID_ASSERTION_HASH"); + require( + assertionHash == calculateAssertionHash(prevAssertionHash, state), + "INVALID_ASSERTION_HASH" + ); } function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64) { @@ -57,10 +60,7 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].secondChildCreationBlock; } - function validateConfig( - bytes32 assertionHash, - ConfigData calldata configData - ) external view { + function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view { require( RollupLib.configHash({ wasmModuleRoot: configData.wasmModuleRoot, @@ -83,19 +83,17 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].isPending; } - function calculateAssertionHash( - bytes32 predecessorId, - ExecutionState memory afterState - ) + function calculateAssertionHash(bytes32 predecessorId, ExecutionState memory afterState) public view returns (bytes32) { - return RollupLib.assertionHash({ - parentAssertionHash: predecessorId, - afterState: afterState, - inboxAcc: keccak256(abi.encode(afterState.globalState.u64Vals[0])) // mock accumulator based on inbox count - }); + return + RollupLib.assertionHash({ + parentAssertionHash: predecessorId, + afterState: afterState, + inboxAcc: keccak256(abi.encode(afterState.globalState.u64Vals[0])) // mock accumulator based on inbox count + }); } function childCreated(bytes32 assertionHash) internal { @@ -148,8 +146,18 @@ contract MockAssertionChain is IAssertionChain { require(!assertionExists(assertionHash), "Assertion already exists"); require(assertionExists(predecessorId), "Predecessor does not exists"); require(height > assertions[predecessorId].height, "Height too low"); - require(beforeStateHash == StateToolsLib.hash(assertions[predecessorId].state), "Before state hash does not match predecessor"); + require( + beforeStateHash == StateToolsLib.hash(assertions[predecessorId].state), + "Before state hash does not match predecessor" + ); - return addAssertionUnsafe(predecessorId, height, nextInboxPosition, afterState, successionChallenge); + return + addAssertionUnsafe( + predecessorId, + height, + nextInboxPosition, + afterState, + successionChallenge + ); } } diff --git a/contracts/test/Rollup.t.sol b/contracts/test/Rollup.t.sol index aee3f4eca..6eaebef44 100644 --- a/contracts/test/Rollup.t.sol +++ b/contracts/test/Rollup.t.sol @@ -47,7 +47,7 @@ contract RollupTest is Test { bytes32 constant FIRST_ASSERTION_BLOCKHASH = keccak256("FIRST_ASSERTION_BLOCKHASH"); bytes32 constant FIRST_ASSERTION_SENDROOT = keccak256("FIRST_ASSERTION_SENDROOT"); - uint256 constant LAYERZERO_BLOCKEDGE_HEIGHT = 2 ** 5; + uint256 constant LAYERZERO_BLOCKEDGE_HEIGHT = 2**5; IERC20 token; RollupProxy rollup; @@ -61,15 +61,20 @@ contract RollupTest is Test { GlobalState emptyGlobalState; ExecutionState emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); - bytes32 genesisHash = RollupLib.assertionHash({ - parentAssertionHash: bytes32(0), - afterState: emptyExecutionState, - inboxAcc: bytes32(0) - }); + bytes32 genesisHash = + RollupLib.assertionHash({ + parentAssertionHash: bytes32(0), + afterState: emptyExecutionState, + inboxAcc: bytes32(0) + }); ExecutionState firstState; event RollupCreated( - address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge + address indexed rollupAddress, + address inboxAddress, + address adminProxy, + address sequencerInbox, + address bridge ); function setUp() public { @@ -98,8 +103,10 @@ contract RollupTest is Test { address(0) ); - ExecutionState memory emptyState = - ExecutionState(GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), MachineStatus.FINISHED); + ExecutionState memory emptyState = ExecutionState( + GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), + MachineStatus.FINISHED + ); token = new TestWETH9("Test", "TEST"); IWETH9(address(token)).deposit{value: 10 ether}(); @@ -121,9 +128,9 @@ contract RollupTest is Test { genesisExecutionState: emptyState, genesisInboxCount: 0, miniStakeValue: MINI_STAKE_VALUE, - layerZeroBlockEdgeHeight: 2 ** 5, - layerZeroBigStepEdgeHeight: 2 ** 5, - layerZeroSmallStepEdgeHeight: 2 ** 5, + layerZeroBlockEdgeHeight: 2**5, + layerZeroBigStepEdgeHeight: 2**5, + layerZeroSmallStepEdgeHeight: 2**5, anyTrustFastConfirmer: anyTrustFastConfirmer, numBigStepLevel: 3, challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS @@ -131,10 +138,20 @@ contract RollupTest is Test { vm.expectEmit(false, false, false, false); emit RollupCreated(address(0), address(0), address(0), address(0), address(0)); - address rollupAddr = rollupCreator.createRollup(config, address(0), new address[](0), false, MAX_DATA_SIZE); - bytes32 rollupSalt = keccak256(abi.encode(config, address(0), new address[](0), false, MAX_DATA_SIZE)); + address rollupAddr = rollupCreator.createRollup( + config, + address(0), + new address[](0), + false, + MAX_DATA_SIZE + ); + bytes32 rollupSalt = keccak256( + abi.encode(config, address(0), new address[](0), false, MAX_DATA_SIZE) + ); address expectedRollupAddress = Create2Upgradeable.computeAddress( - rollupSalt, keccak256(type(RollupProxy).creationCode), address(rollupCreator) + rollupSalt, + keccak256(type(RollupProxy).creationCode), + address(rollupCreator) ); assertEq(expectedRollupAddress, rollupAddr, "Unexpected rollup address"); @@ -210,7 +227,10 @@ contract RollupTest is Test { function testGenesisAssertionConfirmed() external { bytes32 latestConfirmed = userRollup.latestConfirmed(); assertEq(latestConfirmed, genesisHash); - assertEq(userRollup.getAssertion(latestConfirmed).status == AssertionStatus.Confirmed, true); + assertEq( + userRollup.getAssertion(latestConfirmed).status == AssertionStatus.Confirmed, + true + ); } function testSuccessPause() public { @@ -219,7 +239,11 @@ contract RollupTest is Test { } function testConfirmAssertionWhenPaused() public { - (bytes32 assertionHash, ExecutionState memory state, uint64 inboxcount) = testSuccessCreateAssertion(); + ( + bytes32 assertionHash, + ExecutionState memory state, + uint64 inboxcount + ) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(owner); @@ -268,7 +292,14 @@ contract RollupTest is Test { userRollup.removeWhitelistAfterFork(); } - function testSuccessCreateAssertion() public returns (bytes32, ExecutionState memory, uint64) { + function testSuccessCreateAssertion() + public + returns ( + bytes32, + ExecutionState memory, + uint64 + ) + { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -316,7 +347,14 @@ contract RollupTest is Test { assertEq(userRollup.getStakerAddress(userRollup.getStaker(validator1).index), validator1); } - function testSuccessCreateErroredAssertions() public returns (bytes32, ExecutionState memory, uint64) { + function testSuccessCreateErroredAssertions() + public + returns ( + bytes32, + ExecutionState memory, + uint64 + ) + { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -537,8 +575,12 @@ contract RollupTest is Test { ExecutionState memory afterState2; afterState2.machineStatus = MachineStatus.FINISHED; - afterState2.globalState.bytes32Vals[0] = keccak256(abi.encodePacked(FIRST_ASSERTION_BLOCKHASH)); // blockhash - afterState2.globalState.bytes32Vals[1] = keccak256(abi.encodePacked(FIRST_ASSERTION_SENDROOT)); // sendroot + afterState2.globalState.bytes32Vals[0] = keccak256( + abi.encodePacked(FIRST_ASSERTION_BLOCKHASH) + ); // blockhash + afterState2.globalState.bytes32Vals[1] = keccak256( + abi.encodePacked(FIRST_ASSERTION_SENDROOT) + ); // sendroot afterState2.globalState.u64Vals[0] = 1; // inbox count afterState2.globalState.u64Vals[1] = 0; // modify the state @@ -582,7 +624,7 @@ contract RollupTest is Test { } function testRevertConfirmWrongInput() public { - (bytes32 assertionHash1,,) = testSuccessCreateAssertion(); + (bytes32 assertionHash1, , ) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -603,8 +645,19 @@ contract RollupTest is Test { ); } - function testSuccessConfirmUnchallengedAssertions() public returns (bytes32, ExecutionState memory, uint64) { - (bytes32 assertionHash, ExecutionState memory state, uint64 inboxcount) = testSuccessCreateAssertion(); + function testSuccessConfirmUnchallengedAssertions() + public + returns ( + bytes32, + ExecutionState memory, + uint64 + ) + { + ( + bytes32 assertionHash, + ExecutionState memory state, + uint64 inboxcount + ) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -626,8 +679,12 @@ contract RollupTest is Test { } function testSuccessRemoveWhitelistAfterValidatorAfk() public { - (bytes32 assertionHash,,) = testSuccessConfirmUnchallengedAssertions(); - vm.roll(userRollup.getAssertion(assertionHash).createdAtBlock + userRollup.VALIDATOR_AFK_BLOCKS() + 1); + (bytes32 assertionHash, , ) = testSuccessConfirmUnchallengedAssertions(); + vm.roll( + userRollup.getAssertion(assertionHash).createdAtBlock + + userRollup.VALIDATOR_AFK_BLOCKS() + + 1 + ); userRollup.removeWhitelistAfterValidatorAfk(); } @@ -637,7 +694,7 @@ contract RollupTest is Test { } function testRevertConfirmSiblingedAssertions() public { - (,,,,, bytes32 assertionHash,) = testSuccessCreateSecondChild(); + (, , , , , bytes32 assertionHash, ) = testSuccessCreateSecondChild(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -689,7 +746,9 @@ contract RollupTest is Test { states = fillStatesInBetween(h0, h1, LAYERZERO_BLOCKEDGE_HEIGHT + 1); } - bytes32 root = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1)); + bytes32 root = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1) + ); data.e1Id = challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -700,12 +759,19 @@ contract RollupTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), ExecutionStateData(data.beforeState, bytes32(0), bytes32(0)), - ExecutionStateData(data.afterState1, genesisHash, userRollup.bridge().sequencerInboxAccs(0)) + ExecutionStateData( + data.afterState1, + genesisHash, + userRollup.bridge().sequencerInboxAccs(0) ) + ) }) ); } @@ -723,7 +789,9 @@ contract RollupTest is Test { states = fillStatesInBetween(h0, h1, LAYERZERO_BLOCKEDGE_HEIGHT + 1); } - bytes32 root = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1)); + bytes32 root = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1) + ); bytes32 e2Id = challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -734,19 +802,30 @@ contract RollupTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), ExecutionStateData(data.beforeState, bytes32(0), bytes32(0)), - ExecutionStateData(data.afterState2, genesisHash, userRollup.bridge().sequencerInboxAccs(0)) + ExecutionStateData( + data.afterState2, + genesisHash, + userRollup.bridge().sequencerInboxAccs(0) ) + ) }) ); return (data.e1Id, e2Id); } - function fillStatesInBetween(bytes32 start, bytes32 end, uint256 totalCount) internal returns (bytes32[] memory) { + function fillStatesInBetween( + bytes32 start, + bytes32 end, + uint256 totalCount + ) internal returns (bytes32[] memory) { bytes32[] memory innerStates = rand.hashes(totalCount - 2); bytes32[] memory states = new bytes32[](totalCount); @@ -889,15 +968,30 @@ contract RollupTest is Test { userRollup.addToDeposit(sequencer, 1); } - function testSuccessCreateSecondAssertion() public returns (bytes32, bytes32, ExecutionState memory, bytes32) { - (bytes32 prevHash, ExecutionState memory beforeState, uint64 prevInboxCount) = testSuccessCreateAssertion(); + function testSuccessCreateSecondAssertion() + public + returns ( + bytes32, + bytes32, + ExecutionState memory, + bytes32 + ) + { + ( + bytes32 prevHash, + ExecutionState memory beforeState, + uint64 prevInboxCount + ) = testSuccessCreateAssertion(); ExecutionState memory afterState; afterState.machineStatus = MachineStatus.FINISHED; afterState.globalState.u64Vals[0] = prevInboxCount; bytes32 inboxAcc = userRollup.bridge().sequencerInboxAccs(1); // 1 because we moved the position within message - bytes32 expectedAssertionHash2 = - RollupLib.assertionHash({parentAssertionHash: prevHash, afterState: afterState, inboxAcc: inboxAcc}); + bytes32 expectedAssertionHash2 = RollupLib.assertionHash({ + parentAssertionHash: prevHash, + afterState: afterState, + inboxAcc: inboxAcc + }); bytes32 prevInboxAcc = userRollup.bridge().sequencerInboxAccs(0); vm.roll(block.number + 75); vm.prank(validator1); @@ -923,8 +1017,11 @@ contract RollupTest is Test { } function testRevertCreateChildReducedStake() public { - (bytes32 prevHash, ExecutionState memory beforeState, uint64 prevInboxCount) = - testSuccessConfirmUnchallengedAssertions(); + ( + bytes32 prevHash, + ExecutionState memory beforeState, + uint64 prevInboxCount + ) = testSuccessConfirmUnchallengedAssertions(); vm.prank(validator1); userRollup.reduceDeposit(1); @@ -962,7 +1059,7 @@ contract RollupTest is Test { } function testSuccessFastConfirmNext() public { - (bytes32 assertionHash,,) = testSuccessCreateAssertion(); + (bytes32 assertionHash, , ) = testSuccessCreateAssertion(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); assertEq(userRollup.latestConfirmed(), genesisHash); vm.prank(anyTrustFastConfirmer); @@ -971,8 +1068,12 @@ contract RollupTest is Test { } function testSuccessFastConfirmSkipOne() public { - (bytes32 prevHash, bytes32 assertionHash, ExecutionState memory afterState, bytes32 inboxAcc) = - testSuccessCreateSecondAssertion(); + ( + bytes32 prevHash, + bytes32 assertionHash, + ExecutionState memory afterState, + bytes32 inboxAcc + ) = testSuccessCreateSecondAssertion(); assertEq(userRollup.latestConfirmed() != prevHash, true); vm.prank(anyTrustFastConfirmer); userRollup.fastConfirmAssertion(assertionHash, prevHash, afterState, inboxAcc); @@ -980,7 +1081,7 @@ contract RollupTest is Test { } function testRevertFastConfirmNotPending() public { - (bytes32 assertionHash,,) = testSuccessConfirmUnchallengedAssertions(); + (bytes32 assertionHash, , ) = testSuccessConfirmUnchallengedAssertions(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.expectRevert("NOT_PENDING"); vm.prank(anyTrustFastConfirmer); @@ -988,16 +1089,17 @@ contract RollupTest is Test { } function testRevertFastConfirmNotConfirmer() public { - (bytes32 assertionHash,,) = testSuccessCreateAssertion(); + (bytes32 assertionHash, , ) = testSuccessCreateAssertion(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.expectRevert("NOT_FAST_CONFIRMER"); userRollup.fastConfirmAssertion(assertionHash, genesisHash, firstState, inboxAccs); } - function _testFastConfirmNewAssertion(address by, string memory err, bool isCreated) - internal - returns (AssertionInputs memory, bytes32) - { + function _testFastConfirmNewAssertion( + address by, + string memory err, + bool isCreated + ) internal returns (AssertionInputs memory, bytes32) { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -1043,7 +1145,10 @@ contract RollupTest is Test { vm.expectRevert(bytes(err)); } vm.prank(by); - userRollup.fastConfirmNewAssertion({assertion: assertion, expectedAssertionHash: expectedAssertionHash}); + userRollup.fastConfirmNewAssertion({ + assertion: assertion, + expectedAssertionHash: expectedAssertionHash + }); if (bytes(err).length == 0) { assertEq(userRollup.latestConfirmed(), expectedAssertionHash); } @@ -1063,15 +1168,22 @@ contract RollupTest is Test { } function testRevertFastConfirmNewAssertionConfirmed() public { - (AssertionInputs memory assertion, bytes32 expectedAssertionHash) = - _testFastConfirmNewAssertion(anyTrustFastConfirmer, "", true); + ( + AssertionInputs memory assertion, + bytes32 expectedAssertionHash + ) = _testFastConfirmNewAssertion(anyTrustFastConfirmer, "", true); vm.expectRevert("NOT_PENDING"); vm.prank(anyTrustFastConfirmer); - userRollup.fastConfirmNewAssertion({assertion: assertion, expectedAssertionHash: expectedAssertionHash}); + userRollup.fastConfirmNewAssertion({ + assertion: assertion, + expectedAssertionHash: expectedAssertionHash + }); } - bytes32 constant _IMPLEMENTATION_PRIMARY_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - bytes32 constant _IMPLEMENTATION_SECONDARY_SLOT = 0x2b1dbce74324248c222f0ec2d5ed7bd323cfc425b336f0253c5ccfda7265546d; + bytes32 constant _IMPLEMENTATION_PRIMARY_SLOT = + 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; + bytes32 constant _IMPLEMENTATION_SECONDARY_SLOT = + 0x2b1dbce74324248c222f0ec2d5ed7bd323cfc425b336f0253c5ccfda7265546d; // should only allow admin to upgrade primary logic function testRevertUpgradeNotAdmin() public { @@ -1101,48 +1213,64 @@ contract RollupTest is Test { } function testSuccessUpgradePrimary() public { - address ori_secondary_impl = - address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); + address ori_secondary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) + ); RollupAdminLogic newAdminLogicImpl = new RollupAdminLogic(); vm.prank(owner); adminRollup.upgradeTo(address(newAdminLogicImpl)); - address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); - address new_secondary_impl = - address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); + address new_primary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) + ); + address new_secondary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) + ); assertEq(address(newAdminLogicImpl), new_primary_impl); assertEq(ori_secondary_impl, new_secondary_impl); } function testSuccessUpgradePrimaryAndCall() public { - address ori_secondary_impl = - address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); + address ori_secondary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) + ); RollupAdminLogic newAdminLogicImpl = new RollupAdminLogic(); vm.prank(owner); - adminRollup.upgradeToAndCall(address(newAdminLogicImpl), abi.encodeCall(adminRollup.pause, ())); + adminRollup.upgradeToAndCall( + address(newAdminLogicImpl), + abi.encodeCall(adminRollup.pause, ()) + ); assertEq(adminRollup.paused(), true); - address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); - address new_secondary_impl = - address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); + address new_primary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) + ); + address new_secondary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) + ); assertEq(address(newAdminLogicImpl), new_primary_impl); assertEq(ori_secondary_impl, new_secondary_impl); } function testSuccessUpgradeSecondary() public { - address ori_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); + address ori_primary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) + ); RollupUserLogic newUserLogicImpl = new RollupUserLogic(); vm.prank(owner); adminRollup.upgradeSecondaryTo(address(newUserLogicImpl)); - address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); - address new_secondary_impl = - address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); + address new_primary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) + ); + address new_secondary_impl = address( + uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) + ); assertEq(ori_primary_impl, new_primary_impl); assertEq(address(newUserLogicImpl), new_secondary_impl); @@ -1195,7 +1323,10 @@ contract RollupTest is Test { function testExecutionStateHash() public { ExecutionState memory es = ExecutionState( - GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), + GlobalState( + [rand.hash(), rand.hash()], + [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] + ), MachineStatus.FINISHED ); bytes32 expectedHash = keccak256(abi.encodePacked(es.machineStatus, es.globalState.hash())); @@ -1205,11 +1336,20 @@ contract RollupTest is Test { function testAssertionHash() public { bytes32 parentHash = rand.hash(); ExecutionState memory es = ExecutionState( - GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), + GlobalState( + [rand.hash(), rand.hash()], + [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] + ), MachineStatus.FINISHED ); bytes32 inboxAcc = rand.hash(); - bytes32 expectedHash = keccak256(abi.encodePacked(parentHash, RollupLib.executionStateHash(es), inboxAcc)); - assertEq(RollupLib.assertionHash(parentHash, es, inboxAcc), expectedHash, "Unexpected hash"); + bytes32 expectedHash = keccak256( + abi.encodePacked(parentHash, RollupLib.executionStateHash(es), inboxAcc) + ); + assertEq( + RollupLib.assertionHash(parentHash, es, inboxAcc), + expectedHash, + "Unexpected hash" + ); } } diff --git a/contracts/test/RollupMock.sol b/contracts/test/RollupMock.sol new file mode 100644 index 000000000..431d30e89 --- /dev/null +++ b/contracts/test/RollupMock.sol @@ -0,0 +1,15 @@ +// Copyright 2021-2022, Offchain Labs, Inc. +// For license information, see https://github.com/nitro/blob/master/LICENSE +// SPDX-License-Identifier: BUSL-1.1 + +pragma solidity ^0.8.4; + +contract RollupMock { + event WithdrawTriggered(); + event ZombieTriggered(); + + function withdrawStakerFunds() external returns (uint256) { + emit WithdrawTriggered(); + return 0; + } +} diff --git a/contracts/test/ValidatorWalletTest.t.sol b/contracts/test/ValidatorWalletTest.t.sol new file mode 100644 index 000000000..f0d4e37a3 --- /dev/null +++ b/contracts/test/ValidatorWalletTest.t.sol @@ -0,0 +1,179 @@ +// Copyright 2021-2022, Offchain Labs, Inc. +// For license information, see https://github.com/nitro/blob/master/LICENSE +// SPDX-License-Identifier: BUSL-1.1 + +pragma solidity ^0.8.17; + +import "forge-std/Test.sol"; +import "../src/rollup/ValidatorWallet.sol"; +import "../src/rollup/ValidatorWalletCreator.sol"; +import "./util/TestUtil.sol"; +import "./RollupMock.sol"; + +contract ValidatorWalletTest is Test { + // Contract instances + ValidatorWalletCreator creator; + ValidatorWallet wallet; + RollupMock rollupMock1; + RollupMock rollupMock2; + + // Set initial executor and owner + address public executor = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4; + address public owner = 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2; + + function setUp() public { + // Create instances + creator = new ValidatorWalletCreator(); + rollupMock1 = new RollupMock(); + rollupMock2 = new RollupMock(); + + // Set up executor and owner + address[] memory initialExecutors = new address[](1); + initialExecutors[0] = executor; + + // Create wallet and explicitly initialize with executor and owner + vm.prank(owner); + address walletAddress = creator.createWallet(initialExecutors); + wallet = ValidatorWallet(payable(walletAddress)); + } + + // Test wallet creation and executor setup + function testWalletCreation() public { + address[] memory newExecutors = new address[](1); + newExecutors[0] = executor; + bool[] memory isExecutor = new bool[](1); + isExecutor[0] = true; + + // Set executor and check if it is marked as executor + vm.expectEmit(true, false, false, false); + emit ExecutorUpdated(executor, true); + vm.prank(owner); + wallet.setExecutor(newExecutors, isExecutor); + require(wallet.executors(executor), "Executor should be marked as executor"); + require(wallet.allowedExecutorDestinations(executor), "Executor should be allowed"); + } + + // Test setting allowed executor destinations + function testSetAllowedExecutorDestinations() public { + address[] memory allowedAddrs = new address[](3); + allowedAddrs[0] = address(0x1234567812345678123456781234567812345678); + allowedAddrs[1] = address(0x0000000000000000000000000000000000000000); + allowedAddrs[2] = address(0x0123000000000000000000000000000000000000); + bool[] memory isSet = new bool[](3); + isSet[0] = true; + isSet[1] = true; + isSet[2] = true; + + // Set allowed executor destinations + vm.prank(owner); + wallet.setAllowedExecutorDestinations(allowedAddrs, isSet); + // Check if the set destinations are allowed + require(wallet.allowedExecutorDestinations(allowedAddrs[0]), "Address 0 should be allowed"); + require(wallet.allowedExecutorDestinations(allowedAddrs[1]), "Address 1 should be allowed"); + require(wallet.allowedExecutorDestinations(allowedAddrs[2]), "Address 2 should be allowed"); + + // Check if a non-set destination is not allowed + require( + !wallet.allowedExecutorDestinations( + address(0x1114567812345678123456781234567812341111) + ), + "Address 0x1114567812345678123456781234567812341111 should not be allowed" + ); + } + + function testAllowExecutorToExecuteTxs() public { + address[] memory newExecutors = new address[](1); + newExecutors[0] = executor; + bool[] memory isExecutor = new bool[](1); + isExecutor[0] = true; + address[] memory destinationAddrs = new address[](1); + destinationAddrs[0] = address(rollupMock1); + bool[] memory isSet = new bool[](1); + isSet[0] = true; + bytes memory data = abi.encodeWithSignature("withdrawStakerFunds()"); + + // Set executor + vm.prank(owner); + wallet.setExecutor(newExecutors, isExecutor); + // Expect the transaction to revert with a specific error message when called by the executor + vm.expectRevert( + abi.encodeWithSelector( + OnlyOwnerDestination.selector, + owner, + executor, + address(rollupMock1) + ) + ); + vm.prank(executor); + wallet.executeTransaction(data, address(rollupMock1), 0); + + vm.expectEmit(false, false, false, false); + // Expecet the transaction to go through when called by owenr + emit WithdrawTriggered(); + vm.prank(owner); + wallet.executeTransaction(data, address(rollupMock1), 0); + + vm.prank(owner); + // Set allowed executor destinations using the provided arrays + wallet.setAllowedExecutorDestinations(destinationAddrs, isSet); + + // Expect the transaction to go through when called by the executor + emit WithdrawTriggered(); + vm.prank(executor); + wallet.executeTransaction(data, address(rollupMock1), 0); + } + + function testRejectBatchIfSingleTxNotAllowed() external { + address[] memory addrs = new address[](1); + addrs[0] = executor; + bool[] memory isExecutor = new bool[](1); + isExecutor[0] = true; + + // Encode function data for 'withdrawStakerFunds' in RollupMock + bytes memory data1 = abi.encodeWithSignature("withdrawStakerFunds()"); + bytes memory data2 = abi.encodeWithSignature("withdrawStakerFunds()"); + + bytes[] memory data = new bytes[](2); + data[0] = data1; + data[1] = data2; + + uint256[] memory amount = new uint256[](2); + amount[0] = 0; + amount[1] = 0; + + // Set allowed executor destinations in wallet + address[] memory destination_addrs = new address[](2); + destination_addrs[0] = address(rollupMock1); + destination_addrs[1] = address(rollupMock2); + bool[] memory isSet = new bool[](2); + isSet[0] = true; + isSet[1] = false; + + // Set executor + vm.prank(owner); + wallet.setExecutor(addrs, isExecutor); + + // Set allowed executor destinations using the provided arrays + vm.prank(owner); + wallet.setAllowedExecutorDestinations(destination_addrs, isSet); + + // Expect the transaction to revert with a specific error message when called by the executor + vm.expectRevert( + abi.encodeWithSelector( + OnlyOwnerDestination.selector, + owner, + executor, + address(rollupMock2) + ) + ); + vm.prank(executor); + wallet.executeTransactions(data, destination_addrs, amount); + } + + /**** + **** Event declarations + ***/ + + event WithdrawTriggered(); + event ExecutorUpdated(address indexed executor, bool isExecutor); +} diff --git a/contracts/test/challengeV2/ArrayUtilsLib.t.sol b/contracts/test/challengeV2/ArrayUtilsLib.t.sol index 2052f71d7..11e9b003b 100644 --- a/contracts/test/challengeV2/ArrayUtilsLib.t.sol +++ b/contracts/test/challengeV2/ArrayUtilsLib.t.sol @@ -14,7 +14,7 @@ contract ArrayUtilsLibTest is Test { function areEqual(bytes32[] memory a, bytes32[] memory b) internal { assertEq(a.length, b.length, "Len unequal"); - for (uint i = 0; i < a.length; i++) { + for (uint256 i = 0; i < a.length; i++) { assertEq(a[i], b[i]); } } @@ -57,7 +57,7 @@ contract ArrayUtilsLibTest is Test { function testSliceAll() public { bytes32[] memory o = random.hashes(5); - + bytes32[] memory s = ArrayUtilsLib.slice(o, 0, o.length); areEqual(o, s); } diff --git a/contracts/test/challengeV2/ChallengeEdgeLib.t.sol b/contracts/test/challengeV2/ChallengeEdgeLib.t.sol index 6cea9dfe2..72c34add6 100644 --- a/contracts/test/challengeV2/ChallengeEdgeLib.t.sol +++ b/contracts/test/challengeV2/ChallengeEdgeLib.t.sol @@ -36,7 +36,14 @@ contract ChallengeEdgeLibAccess { bytes32 endHistoryRoot, uint256 endHeight ) public pure { - return ChallengeEdgeLib.newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); + return + ChallengeEdgeLib.newEdgeChecks( + originId, + startHistoryRoot, + startHeight, + endHistoryRoot, + endHeight + ); } function newLayerZeroEdge( @@ -49,9 +56,17 @@ contract ChallengeEdgeLibAccess { address staker, uint8 level ) public view returns (ChallengeEdge memory) { - return ChallengeEdgeLib.newLayerZeroEdge( - originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight, claimId, staker, level - ); + return + ChallengeEdgeLib.newLayerZeroEdge( + originId, + startHistoryRoot, + startHeight, + endHistoryRoot, + endHeight, + claimId, + staker, + level + ); } function newChildEdge( @@ -62,7 +77,15 @@ contract ChallengeEdgeLibAccess { uint256 endHeight, uint8 level ) public view returns (ChallengeEdge memory) { - return ChallengeEdgeLib.newChildEdge(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight, level); + return + ChallengeEdgeLib.newChildEdge( + originId, + startHistoryRoot, + startHeight, + endHistoryRoot, + endHeight, + level + ); } function mutualIdComponent( @@ -72,7 +95,14 @@ contract ChallengeEdgeLibAccess { bytes32 startHistoryRoot, uint256 endHeight ) public pure returns (bytes32) { - return ChallengeEdgeLib.mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight); + return + ChallengeEdgeLib.mutualIdComponent( + level, + originId, + startHeight, + startHistoryRoot, + endHeight + ); } function mutualId() public view returns (bytes32) { @@ -91,7 +121,15 @@ contract ChallengeEdgeLibAccess { uint256 endHeight, bytes32 endHistoryRoot ) public pure returns (bytes32) { - return ChallengeEdgeLib.idComponent(level, originId, startHeight, startHistoryRoot, endHeight, endHistoryRoot); + return + ChallengeEdgeLib.idComponent( + level, + originId, + startHeight, + startHistoryRoot, + endHeight, + endHistoryRoot + ); } function idMem(ChallengeEdge memory edge) public pure returns (bytes32) { @@ -135,7 +173,14 @@ contract ChallengeEdgeLibTest is Test { Random rand = new Random(); uint8 constant NUM_BIGSTEP_LEVEL = 3; - function randCheckArgs() internal returns (bytes32, bytes32, bytes32) { + function randCheckArgs() + internal + returns ( + bytes32, + bytes32, + bytes32 + ) + { return (rand.hash(), rand.hash(), rand.hash()); } @@ -152,14 +197,14 @@ contract ChallengeEdgeLibTest is Test { } function testEdgeChecksStartRoot() public { - (bytes32 originId,, bytes32 endRoot) = randCheckArgs(); + (bytes32 originId, , bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyStartRoot.selector)); access.newEdgeChecks(originId, 0, 10, endRoot, 15); } function testEdgeChecksEndRoot() public { - (bytes32 originId, bytes32 startRoot,) = randCheckArgs(); + (bytes32 originId, bytes32 startRoot, ) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyEndRoot.selector)); access.newEdgeChecks(originId, startRoot, 10, 0, 15); @@ -184,8 +229,16 @@ contract ChallengeEdgeLibTest is Test { bytes32 claimId = rand.hash(); address staker = rand.addr(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); - ChallengeEdge memory e = - access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory e = access.newLayerZeroEdge( + originId, + startRoot, + 10, + endRoot, + 15, + claimId, + staker, + NUM_BIGSTEP_LEVEL + 1 + ); assertEq(e.originId, originId, "Origin id"); assertEq(e.startHeight, 10, "Start height"); assertEq(e.startHistoryRoot, startRoot, "Start root"); @@ -201,7 +254,15 @@ contract ChallengeEdgeLibTest is Test { assertTrue(e.level == NUM_BIGSTEP_LEVEL + 1, "EType"); assertEq( access.mutualIdMem(e), - keccak256(abi.encodePacked(e.level, e.originId, e.startHeight, e.startHistoryRoot, e.endHeight)), + keccak256( + abi.encodePacked( + e.level, + e.originId, + e.startHeight, + e.startHistoryRoot, + e.endHeight + ) + ), "Id mem" ); } @@ -211,7 +272,16 @@ contract ChallengeEdgeLibTest is Test { bytes32 claimId = rand.hash(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyStaker.selector)); - access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, address(0), NUM_BIGSTEP_LEVEL + 1); + access.newLayerZeroEdge( + originId, + startRoot, + 10, + endRoot, + 15, + claimId, + address(0), + NUM_BIGSTEP_LEVEL + 1 + ); } function testNewLayerZeroEdgeZeroClaimId() public { @@ -219,13 +289,29 @@ contract ChallengeEdgeLibTest is Test { address staker = rand.addr(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyClaimId.selector)); - access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, 0, staker, NUM_BIGSTEP_LEVEL + 1); + access.newLayerZeroEdge( + originId, + startRoot, + 10, + endRoot, + 15, + 0, + staker, + NUM_BIGSTEP_LEVEL + 1 + ); } function testNewChildEdge() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); - ChallengeEdge memory e = access.newChildEdge(originId, startRoot, 10, endRoot, 15, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory e = access.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 15, + NUM_BIGSTEP_LEVEL + 1 + ); assertEq(e.originId, originId, "Origin id"); assertEq(e.startHeight, 10, "Start height"); assertEq(e.startHistoryRoot, startRoot, "Start root"); @@ -252,10 +338,25 @@ contract ChallengeEdgeLibTest is Test { assertFalse(layerZero.exists(), "Layer zero exists"); assertFalse(child.exists(), "Child exists"); - ChallengeEdge memory layerZeroEdge = - layerZero.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory layerZeroEdge = layerZero.newLayerZeroEdge( + originId, + startRoot, + 10, + endRoot, + 15, + claimId, + staker, + NUM_BIGSTEP_LEVEL + 1 + ); layerZero.setChallengeEdge(layerZeroEdge); - ChallengeEdge memory childEdge = child.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = child.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); assertTrue(layerZero.exists(), "Layer zero exists"); @@ -277,11 +378,24 @@ contract ChallengeEdgeLibTest is Test { ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); ChallengeEdge memory layerZeroEdge = ChallengeEdgeLib.newLayerZeroEdge( - originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1 + originId, + startRoot, + 10, + endRoot, + 15, + claimId, + staker, + NUM_BIGSTEP_LEVEL + 1 ); layerZero.setChallengeEdge(layerZeroEdge); - ChallengeEdge memory childEdge = - ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); assertEq(layerZero.length(), 5, "L-zero len"); @@ -300,8 +414,14 @@ contract ChallengeEdgeLibTest is Test { function testSetChildren() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = - ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); bytes32 lowerChildId = rand.hash(); @@ -317,22 +437,41 @@ contract ChallengeEdgeLibTest is Test { function testSetChildrenTwice() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = - ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); bytes32 lowerChildId = rand.hash(); bytes32 upperChildId = rand.hash(); child.setChildren(lowerChildId, upperChildId); - vm.expectRevert(abi.encodeWithSelector(ChildrenAlreadySet.selector, child.id(), lowerChildId, upperChildId)); + vm.expectRevert( + abi.encodeWithSelector( + ChildrenAlreadySet.selector, + child.id(), + lowerChildId, + upperChildId + ) + ); child.setChildren(lowerChildId, upperChildId); } function testSetConfirmed() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = - ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); vm.roll(137); @@ -345,12 +484,20 @@ contract ChallengeEdgeLibTest is Test { function testSetConfirmedTwice() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = - ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); + ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 10, + endRoot, + 17, + NUM_BIGSTEP_LEVEL + 1 + ); child.setChallengeEdge(childEdge); child.setConfirmed(); - vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, child.id(), EdgeStatus.Confirmed)); + vm.expectRevert( + abi.encodeWithSelector(EdgeNotPending.selector, child.id(), EdgeStatus.Confirmed) + ); child.setConfirmed(); } diff --git a/contracts/test/challengeV2/EdgeChallengeManager.t.sol b/contracts/test/challengeV2/EdgeChallengeManager.t.sol index 23e666061..56b2d02b1 100644 --- a/contracts/test/challengeV2/EdgeChallengeManager.t.sol +++ b/contracts/test/challengeV2/EdgeChallengeManager.t.sol @@ -14,15 +14,21 @@ import "../ERC20Mock.sol"; import "./StateTools.sol"; contract MockOneStepProofEntry is IOneStepProofEntry { - function proveOneStep(ExecutionContext calldata, uint256, bytes32, bytes calldata proof) - external - pure - returns (bytes32 afterHash) - { + function proveOneStep( + ExecutionContext calldata, + uint256, + bytes32, + bytes calldata proof + ) external pure returns (bytes32 afterHash) { return bytes32(proof); } - function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { + function getMachineHash(ExecutionState calldata execState) + external + pure + override + returns (bytes32) + { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return GlobalStateLib.hash(execState.globalState); } @@ -33,7 +39,8 @@ contract EdgeChallengeManagerTest is Test { Random rand = new Random(); bytes32 genesisBlockHash = rand.hash(); - ExecutionState genesisState = StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); + ExecutionState genesisState = + StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); bytes32 genesisStateHash = StateToolsLib.mockMachineHash(genesisState); bytes32 genesisAfterStateHash = RollupLib.executionStateHash(genesisState); ExecutionStateData genesisStateData = ExecutionStateData(genesisState, bytes32(0), bytes32(0)); @@ -76,7 +83,14 @@ contract EdgeChallengeManagerTest is Test { return (full, exp); } - function deploy() internal returns (MockAssertionChain, EdgeChallengeManager, bytes32) { + function deploy() + internal + returns ( + MockAssertionChain, + EdgeChallengeManager, + bytes32 + ) + { MockAssertionChain assertionChain = new MockAssertionChain(); EdgeChallengeManager challengeManagerTemplate = new EdgeChallengeManager(); EdgeChallengeManager challengeManager = EdgeChallengeManager( @@ -92,15 +106,10 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, new MockOneStepProofEntry(), - 2 ** 5, - 2 ** 5, - 2 ** 5, - new ERC20Mock( - "StakeToken", - "ST", - address(this), - 1000000 ether - ), + 2**5, + 2**5, + 2**5, + new ERC20Mock("StakeToken", "ST", address(this), 1000000 ether), miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL @@ -108,8 +117,13 @@ contract EdgeChallengeManagerTest is Test { challengeManager.stakeToken().approve(address(challengeManager), type(uint256).max); - genesisAssertionHash = - assertionChain.addAssertionUnsafe(0, genesisHeight, inboxMsgCountGenesis, genesisState, 0); + genesisAssertionHash = assertionChain.addAssertionUnsafe( + 0, + genesisHeight, + inboxMsgCountGenesis, + genesisState, + 0 + ); return (assertionChain, challengeManager, genesisAssertionHash); } @@ -117,30 +131,19 @@ contract EdgeChallengeManagerTest is Test { MockAssertionChain assertionChain = new MockAssertionChain(); EdgeChallengeManager emt = new EdgeChallengeManager(); EdgeChallengeManager ecm = EdgeChallengeManager( - address( - new TransparentUpgradeableProxy( - address(emt), - address(new ProxyAdmin()), - "" - ) - ) + address(new TransparentUpgradeableProxy(address(emt), address(new ProxyAdmin()), "")) ); MockOneStepProofEntry osp = new MockOneStepProofEntry(); - ERC20Mock erc20 = new ERC20Mock( - "StakeToken", - "ST", - address(this), - 1000000 ether - ); + ERC20Mock erc20 = new ERC20Mock("StakeToken", "ST", address(this), 1000000 ether); vm.expectRevert(abi.encodeWithSelector(EmptyAssertionChain.selector)); ecm.initialize( IAssertionChain(address(0)), challengePeriodBlock, osp, - 2 ** 5, - 2 ** 5, - 2 ** 5, + 2**5, + 2**5, + 2**5, erc20, miniStakeVal, excessStakeReceiver, @@ -152,9 +155,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, IOneStepProofEntry(address(0)), - 2 ** 5, - 2 ** 5, - 2 ** 5, + 2**5, + 2**5, + 2**5, erc20, miniStakeVal, excessStakeReceiver, @@ -163,7 +166,16 @@ contract EdgeChallengeManagerTest is Test { vm.expectRevert(abi.encodeWithSelector(EmptyChallengePeriod.selector)); ecm.initialize( - assertionChain, 0, osp, 2 ** 5, 2 ** 5, 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL + assertionChain, + 0, + osp, + 2**5, + 2**5, + 2**5, + erc20, + miniStakeVal, + excessStakeReceiver, + NUM_BIGSTEP_LEVEL ); vm.expectRevert(abi.encodeWithSelector(EmptyStakeReceiver.selector)); @@ -171,51 +183,51 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2 ** 5, - 2 ** 5, - 2 ** 5, + 2**5, + 2**5, + 2**5, erc20, miniStakeVal, address(0), NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - (2 ** 5) + 1, - 2 ** 5, - 2 ** 5, + (2**5) + 1, + 2**5, + 2**5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - 2 ** 5, - (2 ** 5) + 1, - 2 ** 5, + 2**5, + (2**5) + 1, + 2**5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - 2 ** 5, - 2 ** 5, - (2 ** 5) + 1, + 2**5, + 2**5, + (2**5) + 1, erc20, miniStakeVal, excessStakeReceiver, @@ -227,9 +239,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2 ** 5, - 2 ** 5, - 2 ** 5, + 2**5, + 2**5, + 2**5, erc20, miniStakeVal, excessStakeReceiver, @@ -241,9 +253,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2 ** 5, - 2 ** 5, - 2 ** 5, + 2**5, + 2**5, + 2**5, erc20, miniStakeVal, excessStakeReceiver, @@ -264,49 +276,85 @@ contract EdgeChallengeManagerTest is Test { } function deployAndInit() internal returns (EdgeInitData memory) { - (MockAssertionChain assertionChain, EdgeChallengeManager challengeManager, bytes32 genesis) = deploy(); + ( + MockAssertionChain assertionChain, + EdgeChallengeManager challengeManager, + bytes32 genesis + ) = deploy(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED + rand, + GlobalStateLib.getInboxPosition(genesisState.globalState), + h1, + MachineStatus.FINISHED ); ExecutionState memory a2State = StateToolsLib.randomState( - rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h2, MachineStatus.FINISHED + rand, + GlobalStateLib.getInboxPosition(genesisState.globalState), + h2, + MachineStatus.FINISHED ); // add one since heights are zero indexed in the history states bytes32 a1 = assertionChain.addAssertion( - genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a1State, 0 + genesis, + genesisHeight + height1, + inboxMsgCountAssertion, + genesisState, + a1State, + 0 ); bytes32 a2 = assertionChain.addAssertion( - genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a2State, 0 - ); - - return EdgeInitData({ - assertionChain: assertionChain, - challengeManager: challengeManager, - genesis: genesis, - a1: a1, - a2: a2, - a1State: a1State, - a2State: a2State, - a1Data: ExecutionStateData(a1State, genesis, bytes32(0)), - a2Data: ExecutionStateData(a2State, genesis, bytes32(0)) - }); + genesis, + genesisHeight + height1, + inboxMsgCountAssertion, + genesisState, + a2State, + 0 + ); + + return + EdgeInitData({ + assertionChain: assertionChain, + challengeManager: challengeManager, + genesis: genesis, + a1: a1, + a2: a2, + a1State: a1State, + a2State: a2State, + a1Data: ExecutionStateData(a1State, genesis, bytes32(0)), + a2Data: ExecutionStateData(a2State, genesis, bytes32(0)) + }); } function testRevertBlockNoFork() public { - (MockAssertionChain assertionChain, EdgeChallengeManager challengeManager, bytes32 genesis) = deploy(); + ( + MockAssertionChain assertionChain, + EdgeChallengeManager challengeManager, + bytes32 genesis + ) = deploy(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED + rand, + GlobalStateLib.getInboxPosition(genesisState.globalState), + h1, + MachineStatus.FINISHED ); bytes32 a1 = assertionChain.addAssertion( - genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a1State, 0 + genesis, + genesisHeight + height1, + inboxMsgCountAssertion, + genesisState, + a1State, + 0 ); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(a1State), + height1 + ); vm.expectRevert(abi.encodeWithSelector(AssertionNoSibling.selector)); challengeManager.createLayerZeroEdge( @@ -318,12 +366,15 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), genesisStateData, ExecutionStateData(a1State, genesisAssertionHash, bytes32(0)) - ) + ) }) ); } @@ -331,8 +382,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockInvalidHeight() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); ei.challengeManager.createLayerZeroEdge( @@ -344,12 +398,15 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), genesisStateData, ei.a1Data - ) + ) }) ); } @@ -357,8 +414,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockNoProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); vm.expectRevert(abi.encodeWithSelector(EmptyEdgeSpecificProof.selector)); ei.challengeManager.createLayerZeroEdge( @@ -370,7 +430,7 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: "" }) ); @@ -379,8 +439,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockInvalidProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -392,10 +455,12 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), genesisStateData, ei.a1Data - ) + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), + genesisStateData, + ei.a1Data + ) }) ); } @@ -403,8 +468,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidHash() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); vm.expectRevert("INVALID_ASSERTION_HASH"); ei.challengeManager.createLayerZeroEdge( @@ -416,10 +484,12 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), genesisStateData, ei.a1Data - ) + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), + genesisStateData, + ei.a1Data + ) }) ); } @@ -427,8 +497,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidHashPrev() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); vm.expectRevert("INVALID_ASSERTION_HASH"); ei.challengeManager.createLayerZeroEdge( @@ -440,22 +513,35 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), ei.a2Data, ei.a1Data - ) + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), + ei.a2Data, + ei.a1Data + ) }) ); } function testCanCreateEdgeWithStake() public - returns (EdgeInitData memory, bytes32[] memory, bytes32[] memory, bytes32) + returns ( + EdgeInitData memory, + bytes32[] memory, + bytes32[] memory, + bytes32 + ) { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a1State), + height1 + ); IERC20 stakeToken = ei.challengeManager.stakeToken(); uint256 beforeBalance = stakeToken.balanceOf(address(this)); @@ -468,12 +554,15 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + states.length - 1 + ), genesisStateData, ei.a1Data - ) + ) }) ); uint256 afterBalance = stakeToken.balanceOf(address(this)); @@ -484,14 +573,23 @@ contract EdgeChallengeManagerTest is Test { ChallengeEdge memory edge = ei.challengeManager.getEdge(edgeId); assertEq( ei.challengeManager.calculateMutualId( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight ), edge.mutualIdMem(), "Mutual id" ); assertEq( ei.challengeManager.calculateEdgeId( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight, + edge.endHistoryRoot ), edge.idMem(), "Mutual id" @@ -500,20 +598,27 @@ contract EdgeChallengeManagerTest is Test { assertEq(ei.challengeManager.hasRival(edgeId), false, "Edge has rival"); assertEq(ei.challengeManager.confirmedRival(edgeId), bytes32(0), "Confirmed rival"); assertEq(ei.challengeManager.hasLengthOneRival(edgeId), false, "Has length one rival"); - assertEq(ei.challengeManager.firstRival(edge.mutualIdMem()), EdgeChallengeManagerLib.UNRIVALED, "Unrivaled"); + assertEq( + ei.challengeManager.firstRival(edge.mutualIdMem()), + EdgeChallengeManagerLib.UNRIVALED, + "Unrivaled" + ); return (ei, states, exp, edgeId); } function testCanConfirmByTime() public { - (EdgeInitData memory ei,,, bytes32 edgeId) = testCanCreateEdgeWithStake(); + (EdgeInitData memory ei, , , bytes32 edgeId) = testCanCreateEdgeWithStake(); vm.roll(challengePeriodBlock + 2); bytes32[] memory ancestorEdges = new bytes32[](0); ei.challengeManager.confirmEdgeByTime(edgeId, ancestorEdges, ei.a1Data); - assertTrue(ei.challengeManager.getEdge(edgeId).status == EdgeStatus.Confirmed, "Edge confirmed"); + assertTrue( + ei.challengeManager.getEdge(edgeId).status == EdgeStatus.Confirmed, + "Edge confirmed" + ); } function testCanConfirmByTimeNotBlock() public { @@ -524,8 +629,15 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -545,13 +657,24 @@ contract EdgeChallengeManagerTest is Test { bytes32[] memory ancestorEdges = new bytes32[](0); vm.expectRevert(abi.encodeWithSelector(EdgeTypeNotBlock.selector, 1)); - ei.challengeManager.confirmEdgeByTime(bsbd.edges1[5].lowerChildId, ancestorEdges, ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + bsbd.edges1[5].lowerChildId, + ancestorEdges, + ei.a1Data + ); } function testCanConfirmByTimeLayerZero() public { EdgeInitData memory ei = deployAndInit(); - (,, BisectionChildren[6] memory blockEdges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + (, , BisectionChildren[6] memory blockEdges1, ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) ); vm.roll(challengePeriodBlock + 2); @@ -560,20 +683,37 @@ contract EdgeChallengeManagerTest is Test { ChallengeEdge memory ce = ei.challengeManager.getEdge(blockEdges1[0].lowerChildId); vm.expectRevert( - abi.encodeWithSelector(EdgeNotLayerZero.selector, blockEdges1[0].lowerChildId, ce.staker, ce.claimId) + abi.encodeWithSelector( + EdgeNotLayerZero.selector, + blockEdges1[0].lowerChildId, + ce.staker, + ce.claimId + ) + ); + ei.challengeManager.confirmEdgeByTime( + blockEdges1[0].lowerChildId, + ancestorEdges, + ei.a1Data ); - ei.challengeManager.confirmEdgeByTime(blockEdges1[0].lowerChildId, ancestorEdges, ei.a1Data); } function testCanConfirmByChildren() public returns (EdgeInitData memory, bytes32) { - (EdgeInitData memory ei, bytes32[] memory states1,, bytes32 edge1Id) = testCanCreateEdgeWithStake(); + ( + EdgeInitData memory ei, + bytes32[] memory states1, + , + bytes32 edge1Id + ) = testCanCreateEdgeWithStake(); vm.roll(block.number + 1); assertEq(ei.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); { - (bytes32[] memory states2, bytes32[] memory exp2) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a2State), height1); + (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a2State), + height1 + ); bytes32 edge2Id = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 0, @@ -582,13 +722,19 @@ contract EdgeChallengeManagerTest is Test { claimId: ei.a2, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states2, 1, states2.length) + ) + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states2), + states2.length - 1 + ), genesisStateData, ei.a2Data - ) + ) }) ); @@ -597,7 +743,13 @@ contract EdgeChallengeManagerTest is Test { assertEq(ei.challengeManager.timeUnrivaled(edge2Id), 0, "Edge2 timer"); } - BisectionChildren memory children = bisect(ei.challengeManager, edge1Id, states1, 16, states1.length - 1); + BisectionChildren memory children = bisect( + ei.challengeManager, + edge1Id, + states1, + 16, + states1.length - 1 + ); vm.roll(challengePeriodBlock + 5); @@ -607,7 +759,10 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByTime(children.upperChildId, ancestors, ei.a1Data); ei.challengeManager.confirmEdgeByChildren(edge1Id); - assertTrue(ei.challengeManager.getEdge(edge1Id).status == EdgeStatus.Confirmed, "Edge confirmed"); + assertTrue( + ei.challengeManager.getEdge(edge1Id).status == EdgeStatus.Confirmed, + "Edge confirmed" + ); return (ei, edge1Id); } @@ -615,8 +770,11 @@ contract EdgeChallengeManagerTest is Test { function testRevertConfirmAnotherRival() public { (EdgeInitData memory ei, bytes32 edge1Id) = testCanConfirmByChildren(); - (bytes32[] memory states2, bytes32[] memory exp2) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a2State), height1); + (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(ei.a2State), + height1 + ); bytes32 edge2Id = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 0, @@ -625,18 +783,36 @@ contract EdgeChallengeManagerTest is Test { claimId: ei.a2, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states2, 1, states2.length) + ) + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1), + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states2), + states2.length - 1 + ), genesisStateData, ei.a2Data - ) + ) }) ); - BisectionChildren memory children = bisect(ei.challengeManager, edge2Id, states2, 16, states2.length - 1); - BisectionChildren memory children2 = bisect(ei.challengeManager, children.lowerChildId, states2, 8, 16); + BisectionChildren memory children = bisect( + ei.challengeManager, + edge2Id, + states2, + 16, + states2.length - 1 + ); + BisectionChildren memory children2 = bisect( + ei.challengeManager, + children.lowerChildId, + states2, + 8, + 16 + ); vm.roll(block.number + challengePeriodBlock + 5); bytes32[] memory ancestors = new bytes32[](2); ancestors[0] = children.lowerChildId; @@ -650,7 +826,10 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByTime(children.upperChildId, ancestors, ei.a2Data); vm.expectRevert(); // should not be able to confirm when a rival is already confirmed ei.challengeManager.confirmEdgeByChildren(edge2Id); - assertFalse(ei.challengeManager.getEdge(edge1Id).status == ei.challengeManager.getEdge(edge2Id).status); + assertFalse( + ei.challengeManager.getEdge(edge1Id).status == + ei.challengeManager.getEdge(edge2Id).status + ); assertTrue(edge1Id != edge2Id, "Same edge"); assertEq( ei.challengeManager.getEdge(edge1Id).mutualIdMem(), @@ -704,43 +883,107 @@ contract EdgeChallengeManagerTest is Test { // height 16 winningEdges[4] = bisect( - args.challengeManager, winningEdges[5].lowerChildId, args.winningLeaves, 16, args.winningLeaves.length - 1 + args.challengeManager, + winningEdges[5].lowerChildId, + args.winningLeaves, + 16, + args.winningLeaves.length - 1 ); losingEdges[4] = bisect( - args.challengeManager, losingEdges[5].lowerChildId, args.losingLeaves, 16, args.losingLeaves.length - 1 + args.challengeManager, + losingEdges[5].lowerChildId, + args.losingLeaves, + 16, + args.losingLeaves.length - 1 ); // height 8 - winningEdges[3] = bisect(args.challengeManager, winningEdges[4].lowerChildId, args.winningLeaves, 8, 16); - losingEdges[3] = bisect(args.challengeManager, losingEdges[4].lowerChildId, args.losingLeaves, 8, 16); + winningEdges[3] = bisect( + args.challengeManager, + winningEdges[4].lowerChildId, + args.winningLeaves, + 8, + 16 + ); + losingEdges[3] = bisect( + args.challengeManager, + losingEdges[4].lowerChildId, + args.losingLeaves, + 8, + 16 + ); // height 4 - winningEdges[2] = bisect(args.challengeManager, winningEdges[3].lowerChildId, args.winningLeaves, 4, 8); - losingEdges[2] = bisect(args.challengeManager, losingEdges[3].lowerChildId, args.losingLeaves, 4, 8); - - winningEdges[1] = bisect(args.challengeManager, winningEdges[2].lowerChildId, args.winningLeaves, 2, 4); - losingEdges[1] = bisect(args.challengeManager, losingEdges[2].lowerChildId, args.losingLeaves, 2, 4); + winningEdges[2] = bisect( + args.challengeManager, + winningEdges[3].lowerChildId, + args.winningLeaves, + 4, + 8 + ); + losingEdges[2] = bisect( + args.challengeManager, + losingEdges[3].lowerChildId, + args.losingLeaves, + 4, + 8 + ); + + winningEdges[1] = bisect( + args.challengeManager, + winningEdges[2].lowerChildId, + args.winningLeaves, + 2, + 4 + ); + losingEdges[1] = bisect( + args.challengeManager, + losingEdges[2].lowerChildId, + args.losingLeaves, + 2, + 4 + ); // height 2 - winningEdges[0] = bisect(args.challengeManager, winningEdges[1].lowerChildId, args.winningLeaves, 1, 2); + winningEdges[0] = bisect( + args.challengeManager, + winningEdges[1].lowerChildId, + args.winningLeaves, + 1, + 2 + ); if (!args.skipLast) { - losingEdges[0] = bisect(args.challengeManager, losingEdges[1].lowerChildId, args.losingLeaves, 1, 2); + losingEdges[0] = bisect( + args.challengeManager, + losingEdges[1].lowerChildId, + args.losingLeaves, + 1, + 2 + ); } return (winningEdges, losingEdges); } - function appendRandomStatesBetween(bytes32[] memory currentStates, bytes32 endState, uint256 numStates) - internal - returns (bytes32[] memory, bytes32[] memory) - { - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates(currentStates, numStates - 1); + function appendRandomStatesBetween( + bytes32[] memory currentStates, + bytes32 endState, + uint256 numStates + ) internal returns (bytes32[] memory, bytes32[] memory) { + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates( + currentStates, + numStates - 1 + ); bytes32[] memory fullStates = ArrayUtilsLib.append(states, endState); bytes32[] memory fullExp = MerkleTreeLib.appendLeaf(exp, endState); return (fullStates, fullExp); } - function toDynamic(BisectionChildren[6] memory l) internal pure returns (BisectionChildren[] memory) { + function toDynamic(BisectionChildren[6] memory l) + internal + pure + returns (BisectionChildren[] memory) + { BisectionChildren[] memory d = new BisectionChildren[](6); for (uint256 i = 0; i < d.length; i++) { d[i] = l[i]; @@ -780,24 +1023,52 @@ contract EdgeChallengeManagerTest is Test { pure returns (bytes memory) { - bytes32[] memory claimStartInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); - return abi.encode(states1[0], states1[1], claimStartInclusionProof, claimEndInclusionProof, edgeInclusionProof); + bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(bigStepStates), + bigStepStates.length - 1 + ); + return + abi.encode( + states1[0], + states1[1], + claimStartInclusionProof, + claimEndInclusionProof, + edgeInclusionProof + ); } function testRevertEmptyPrefixProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); + + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(EmptyPrefixProof.selector)); ei.challengeManager.createLayerZeroEdge( @@ -815,12 +1086,27 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidPrefixProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, + + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); vm.expectRevert("Post expansion root not equal post"); ei.challengeManager.createLayerZeroEdge( @@ -831,8 +1117,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states1, 1, states1.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -841,7 +1130,7 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeNotOneStepFork() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + (bytes32[] memory states1, , BisectionChildren[6] memory edges1, ) = createBlockEdgesAndBisectToFork( CreateBlockEdgesBisectArgs( ei.challengeManager, ei.a1, @@ -852,10 +1141,15 @@ contract EdgeChallengeManagerTest is Test { ) ); - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); - vm.expectRevert(abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, edges1[0].lowerChildId)); + vm.expectRevert( + abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, edges1[0].lowerChildId) + ); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 1, @@ -864,8 +1158,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -874,12 +1171,27 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeNoProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); + + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(EmptyEdgeSpecificProof.selector)); ei.challengeManager.createLayerZeroEdge( @@ -890,8 +1202,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) + ) + ), proof: "" }) ); @@ -900,17 +1215,36 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidStartClaimProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); + + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(bigStepStates), + bigStepStates.length - 1 + ); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -921,11 +1255,18 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), - proof: abi.encode( - states1[0], states1[1], claimEndInclusionProof, claimEndInclusionProof, edgeInclusionProof + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) ) + ), + proof: abi.encode( + states1[0], + states1[1], + claimEndInclusionProof, + claimEndInclusionProof, + edgeInclusionProof + ) }) ); } @@ -933,17 +1274,36 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidEndClaimProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, + + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); - bytes32[] memory claimStartInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); + bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), + 0 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(bigStepStates), + bigStepStates.length - 1 + ); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -954,11 +1314,18 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), - proof: abi.encode( - states1[0], states1[1], claimStartInclusionProof, claimStartInclusionProof, edgeInclusionProof + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) ) + ), + proof: abi.encode( + states1[0], + states1[1], + claimStartInclusionProof, + claimStartInclusionProof, + edgeInclusionProof + ) }) ); } @@ -966,17 +1333,36 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidEdgeProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); + + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); - bytes32[] memory claimStartInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); + bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), + 1 + ); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -987,11 +1373,18 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), - proof: abi.encode( - states1[0], states1[1], claimStartInclusionProof, claimEndInclusionProof, claimStartInclusionProof + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) ) + ), + proof: abi.encode( + states1[0], + states1[1], + claimStartInclusionProof, + claimEndInclusionProof, + claimStartInclusionProof + ) }) ); } @@ -999,12 +1392,27 @@ contract EdgeChallengeManagerTest is Test { function testRevertBigStepInvalidHeight() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); + + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); ei.challengeManager.createLayerZeroEdge( @@ -1015,8 +1423,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1031,14 +1442,25 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1048,8 +1470,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1059,7 +1484,11 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge2BigStepId; { bytes32[] memory bigStepExp2; - (bigStepStates2, bigStepExp2) = appendRandomStatesBetween(genesisStates(), states2[1], height1); + (bigStepStates2, bigStepExp2) = appendRandomStatesBetween( + genesisStates(), + states2[1], + height1 + ); edge2BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1069,16 +1498,24 @@ contract EdgeChallengeManagerTest is Test { claimId: edges2[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length) + ) + ), proof: generateEdgeProof(states2, bigStepStates2) }) ); } - (BisectionChildren[6] memory bigstepedges1,) = bisectToForkOnly( + (BisectionChildren[6] memory bigstepedges1, ) = bisectToForkOnly( BisectToForkOnlyArgs( - ei.challengeManager, edge1BigStepId, edge2BigStepId, bigStepStates1, bigStepStates2, false + ei.challengeManager, + edge1BigStepId, + edge2BigStepId, + bigStepStates1, + bigStepStates2, + false ) ); @@ -1086,7 +1523,11 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge1SmallStepId; { bytes32[] memory smallStepExp1; - (smallStepStates1, smallStepExp1) = appendRandomStatesBetween(genesisStates(), bigStepStates1[1], height1); + (smallStepStates1, smallStepExp1) = appendRandomStatesBetween( + genesisStates(), + bigStepStates1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, 1, 1)); edge1SmallStepId = ei.challengeManager.createLayerZeroEdge( @@ -1097,8 +1538,11 @@ contract EdgeChallengeManagerTest is Test { claimId: bigstepedges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(smallStepStates1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length) + ) + ), proof: generateEdgeProof(bigStepStates1, smallStepStates1) }) ); @@ -1108,15 +1552,31 @@ contract EdgeChallengeManagerTest is Test { function testRevertSmallStepInvalidClaimType() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, + + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, 2, 0)); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( @@ -1127,8 +1587,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1144,14 +1607,25 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1161,8 +1635,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1172,7 +1649,11 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge2BigStepId; { bytes32[] memory bigStepExp2; - (bigStepStates2, bigStepExp2) = appendRandomStatesBetween(genesisStates(), states2[1], height1); + (bigStepStates2, bigStepExp2) = appendRandomStatesBetween( + genesisStates(), + states2[1], + height1 + ); edge2BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1182,16 +1663,24 @@ contract EdgeChallengeManagerTest is Test { claimId: edges2[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length) + ) + ), proof: generateEdgeProof(states2, bigStepStates2) }) ); } - (BisectionChildren[6] memory bigstepedges1,) = bisectToForkOnly( + (BisectionChildren[6] memory bigstepedges1, ) = bisectToForkOnly( BisectToForkOnlyArgs( - ei.challengeManager, edge1BigStepId, edge2BigStepId, bigStepStates1, bigStepStates2, false + ei.challengeManager, + edge1BigStepId, + edge2BigStepId, + bigStepStates1, + bigStepStates2, + false ) ); @@ -1199,7 +1688,11 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge1SmallStepId; { bytes32[] memory smallStepExp1; - (smallStepStates1, smallStepExp1) = appendRandomStatesBetween(genesisStates(), bigStepStates1[1], height1); + (smallStepStates1, smallStepExp1) = appendRandomStatesBetween( + genesisStates(), + bigStepStates1[1], + height1 + ); vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); edge1SmallStepId = ei.challengeManager.createLayerZeroEdge( @@ -1210,8 +1703,11 @@ contract EdgeChallengeManagerTest is Test { claimId: bigstepedges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(smallStepStates1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length) + ) + ), proof: generateEdgeProof(bigStepStates1, smallStepStates1) }) ); @@ -1221,12 +1717,27 @@ contract EdgeChallengeManagerTest is Test { function testCanConfirmByClaim() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + ( + bytes32[] memory states1, + , + BisectionChildren[6] memory edges1, + + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = - appendRandomStatesBetween(genesisStates(), states1[1], height1); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( + genesisStates(), + states1[1], + height1 + ); bytes32 edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1236,8 +1747,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) + ) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1252,27 +1766,38 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByClaim(edges1[0].lowerChildId, edge1BigStepId); ei.challengeManager.confirmEdgeByTime( - edges1[0].upperChildId, getAncestorsAbove(toDynamic(edges1), 0), ei.a1Data + edges1[0].upperChildId, + getAncestorsAbove(toDynamic(edges1), 0), + ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[1].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[1].upperChildId, getAncestorsAbove(toDynamic(edges1), 1), ei.a1Data + edges1[1].upperChildId, + getAncestorsAbove(toDynamic(edges1), 1), + ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[2].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[2].upperChildId, getAncestorsAbove(toDynamic(edges1), 2), ei.a1Data + edges1[2].upperChildId, + getAncestorsAbove(toDynamic(edges1), 2), + ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[3].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[3].upperChildId, getAncestorsAbove(toDynamic(edges1), 3), ei.a1Data + edges1[3].upperChildId, + getAncestorsAbove(toDynamic(edges1), 3), + ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[4].lowerChildId); - assertTrue(ei.challengeManager.getEdge(edges1[4].lowerChildId).status == EdgeStatus.Confirmed, "Edge confirmed"); + assertTrue( + ei.challengeManager.getEdge(edges1[4].lowerChildId).status == EdgeStatus.Confirmed, + "Edge confirmed" + ); } struct CreateBlockEdgesBisectArgs { @@ -1309,41 +1834,75 @@ contract EdgeChallengeManagerTest is Test { ExecutionStateData(endState, genesisAssertionHash, bytes32(0)) ); - return challengeManager.createLayerZeroEdge( - CreateEdgeArgs({ - level: 0, - endHistoryRoot: MerkleTreeLib.root(exp), - endHeight: height1, - claimId: claimId, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) + return + challengeManager.createLayerZeroEdge( + CreateEdgeArgs({ + level: 0, + endHistoryRoot: MerkleTreeLib.root(exp), + endHeight: height1, + claimId: claimId, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states, 0, 1), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states, 1, states.length) + ) ), - proof: typeSpecificProof1 - }) - ); + proof: typeSpecificProof1 + }) + ); } function createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs memory args) internal - returns (bytes32[] memory, bytes32[] memory, BisectionChildren[6] memory, BisectionChildren[6] memory) + returns ( + bytes32[] memory, + bytes32[] memory, + BisectionChildren[6] memory, + BisectionChildren[6] memory + ) { - (bytes32[] memory states1, bytes32[] memory exp1) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState1), height1); - bytes32 edge1Id = createLayerZeroEdge(args.challengeManager, args.claim1Id, args.endState1, states1, exp1); + (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(args.endState1), + height1 + ); + bytes32 edge1Id = createLayerZeroEdge( + args.challengeManager, + args.claim1Id, + args.endState1, + states1, + exp1 + ); vm.roll(block.number + 1); assertEq(args.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState2), height1); - bytes32 edge2Id = createLayerZeroEdge(args.challengeManager, args.claim2Id, args.endState2, states2, exp2); + (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(args.endState2), + height1 + ); + bytes32 edge2Id = createLayerZeroEdge( + args.challengeManager, + args.claim2Id, + args.endState2, + states2, + exp2 + ); vm.roll(block.number + 2); (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs(args.challengeManager, edge1Id, edge2Id, states1, states2, args.skipLast) + BisectToForkOnlyArgs( + args.challengeManager, + edge1Id, + edge2Id, + states1, + states2, + args.skipLast + ) ); return (states1, states2, edges1, edges2); @@ -1353,19 +1912,27 @@ contract EdgeChallengeManagerTest is Test { internal returns (BisectionData memory) { - (bytes32[] memory states1, bytes32[] memory exp1) = - appendRandomStatesBetween(genesisStates(), args.endState1, height1); + (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( + genesisStates(), + args.endState1, + height1 + ); bytes32 edge1Id; { bytes memory typeSpecificProof1; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), 0 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(args.forkStates1), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states1), + states1.length - 1 ); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates1), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), states1.length - 1); typeSpecificProof1 = abi.encode( genesisStateHash, args.endState1, @@ -1382,8 +1949,11 @@ contract EdgeChallengeManagerTest is Test { claimId: args.claim1Id, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states1, 1, states1.length) + ) + ), proof: typeSpecificProof1 }) ); @@ -1393,19 +1963,27 @@ contract EdgeChallengeManagerTest is Test { assertEq(args.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = - appendRandomStatesBetween(genesisStates(), args.endState2, height1); + (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( + genesisStates(), + args.endState2, + height1 + ); bytes32 edge2Id; { bytes memory typeSpecificProof2; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), 0 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(args.forkStates2), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states2), + states2.length - 1 ); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates2), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1); typeSpecificProof2 = abi.encode( genesisStateHash, args.endState2, @@ -1422,8 +2000,11 @@ contract EdgeChallengeManagerTest is Test { claimId: args.claim2Id, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) - ), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states2, 1, states2.length) + ) + ), proof: typeSpecificProof2 }) ); @@ -1432,7 +2013,14 @@ contract EdgeChallengeManagerTest is Test { vm.roll(block.number + 2); (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs(args.challengeManager, edge1Id, edge2Id, states1, states2, args.skipLast) + BisectToForkOnlyArgs( + args.challengeManager, + edge1Id, + edge2Id, + states1, + states2, + args.skipLast + ) ); return BisectionData(states1, states2, edges1, edges2); @@ -1446,8 +2034,15 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -1479,62 +2074,135 @@ contract EdgeChallengeManagerTest is Test { vm.roll(challengePeriodBlock + 11); - BisectionChildren[] memory allWinners = - concat(concat(toDynamic(ssbd.edges1), toDynamic(bsbd.edges1)), toDynamic(blockEdges1)); + BisectionChildren[] memory allWinners = concat( + concat(toDynamic(ssbd.edges1), toDynamic(bsbd.edges1)), + toDynamic(blockEdges1) + ); - ei.challengeManager.confirmEdgeByTime(allWinners[0].lowerChildId, getAncestorsAbove(allWinners, 0), ei.a1Data); - ei.challengeManager.confirmEdgeByTime(allWinners[0].upperChildId, getAncestorsAbove(allWinners, 0), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[0].lowerChildId, + getAncestorsAbove(allWinners, 0), + ei.a1Data + ); + ei.challengeManager.confirmEdgeByTime( + allWinners[0].upperChildId, + getAncestorsAbove(allWinners, 0), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[1].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[1].upperChildId, getAncestorsAbove(allWinners, 1), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[1].upperChildId, + getAncestorsAbove(allWinners, 1), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[2].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[2].upperChildId, getAncestorsAbove(allWinners, 2), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[2].upperChildId, + getAncestorsAbove(allWinners, 2), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[3].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[3].upperChildId, getAncestorsAbove(allWinners, 3), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[3].upperChildId, + getAncestorsAbove(allWinners, 3), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[4].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[4].upperChildId, getAncestorsAbove(allWinners, 4), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[4].upperChildId, + getAncestorsAbove(allWinners, 4), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[5].lowerChildId); - ei.challengeManager.confirmEdgeByClaim(allWinners[6].lowerChildId, allWinners[5].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[6].upperChildId, getAncestorsAbove(allWinners, 6), ei.a1Data); + ei.challengeManager.confirmEdgeByClaim( + allWinners[6].lowerChildId, + allWinners[5].lowerChildId + ); + ei.challengeManager.confirmEdgeByTime( + allWinners[6].upperChildId, + getAncestorsAbove(allWinners, 6), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[7].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[7].upperChildId, getAncestorsAbove(allWinners, 7), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[7].upperChildId, + getAncestorsAbove(allWinners, 7), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[8].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[8].upperChildId, getAncestorsAbove(allWinners, 8), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[8].upperChildId, + getAncestorsAbove(allWinners, 8), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[9].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[9].upperChildId, getAncestorsAbove(allWinners, 9), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[9].upperChildId, + getAncestorsAbove(allWinners, 9), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[10].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[10].upperChildId, getAncestorsAbove(allWinners, 10), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[10].upperChildId, + getAncestorsAbove(allWinners, 10), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[11].lowerChildId); - ei.challengeManager.confirmEdgeByClaim(allWinners[12].lowerChildId, allWinners[11].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[12].upperChildId, getAncestorsAbove(allWinners, 12), ei.a1Data); + ei.challengeManager.confirmEdgeByClaim( + allWinners[12].lowerChildId, + allWinners[11].lowerChildId + ); + ei.challengeManager.confirmEdgeByTime( + allWinners[12].upperChildId, + getAncestorsAbove(allWinners, 12), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[13].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[13].upperChildId, getAncestorsAbove(allWinners, 13), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[13].upperChildId, + getAncestorsAbove(allWinners, 13), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[14].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[14].upperChildId, getAncestorsAbove(allWinners, 14), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[14].upperChildId, + getAncestorsAbove(allWinners, 14), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[15].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[15].upperChildId, getAncestorsAbove(allWinners, 15), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[15].upperChildId, + getAncestorsAbove(allWinners, 15), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[16].lowerChildId); - ei.challengeManager.confirmEdgeByTime(allWinners[16].upperChildId, getAncestorsAbove(allWinners, 16), ei.a1Data); + ei.challengeManager.confirmEdgeByTime( + allWinners[16].upperChildId, + getAncestorsAbove(allWinners, 16), + ei.a1Data + ); ei.challengeManager.confirmEdgeByChildren(allWinners[17].lowerChildId); assertTrue( - ei.challengeManager.getEdge(allWinners[14].lowerChildId).status == EdgeStatus.Confirmed, "Edge confirmed" + ei.challengeManager.getEdge(allWinners[14].lowerChildId).status == EdgeStatus.Confirmed, + "Edge confirmed" ); } @@ -1554,12 +2222,27 @@ contract EdgeChallengeManagerTest is Test { BisectionData smallStepBisection; } - function testCanConfirmByOneStep() public returns (EdgeInitData memory, BisectionChildren[] memory) { + function testCanConfirmByOneStep() + public + returns (EdgeInitData memory, BisectionChildren[] memory) + { EdgeInitData memory ei = deployAndInit(); CanConfirmByOneStepData memory local; - (local.blockStates1, local.blockStates2, local.blockEdges1, local.blockEdges2) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ( + local.blockStates1, + local.blockStates2, + local.blockEdges1, + local.blockEdges2 + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) ); local.bigStepBisections[0] = createMachineEdgesAndBisectToFork( @@ -1611,7 +2294,10 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[] memory allWinners = toDynamic(local.smallStepBisection.edges1); for (uint256 i = 0; i < NUM_BIGSTEP_LEVEL; ++i) { - allWinners = concat(allWinners, toDynamic(local.bigStepBisections[NUM_BIGSTEP_LEVEL - i - 1].edges1)); + allWinners = concat( + allWinners, + toDynamic(local.bigStepBisections[NUM_BIGSTEP_LEVEL - i - 1].edges1) + ); } allWinners = concat(allWinners, toDynamic(local.blockEdges1)); @@ -1640,10 +2326,15 @@ contract EdgeChallengeManagerTest is Test { if (i % 6 != 0) { ei.challengeManager.confirmEdgeByChildren(allWinners[i].lowerChildId); } else { - ei.challengeManager.confirmEdgeByClaim(allWinners[i].lowerChildId, allWinners[i - 1].lowerChildId); + ei.challengeManager.confirmEdgeByClaim( + allWinners[i].lowerChildId, + allWinners[i - 1].lowerChildId + ); } ei.challengeManager.confirmEdgeByTime( - allWinners[i].upperChildId, getAncestorsAbove(allWinners, i), ei.a1Data + allWinners[i].upperChildId, + getAncestorsAbove(allWinners, i), + ei.a1Data ); } else { ei.challengeManager.confirmEdgeByChildren(allWinners[i].lowerChildId); @@ -1651,7 +2342,8 @@ contract EdgeChallengeManagerTest is Test { } assertTrue( - ei.challengeManager.getEdge(allWinners[allWinners.length - 1].lowerChildId).status == EdgeStatus.Confirmed, + ei.challengeManager.getEdge(allWinners[allWinners.length - 1].lowerChildId).status == + EdgeStatus.Confirmed, "Edge confirmed" ); @@ -1659,7 +2351,7 @@ contract EdgeChallengeManagerTest is Test { } function testExcessStakeReceived() external { - (EdgeInitData memory ei,) = testCanConfirmByOneStep(); + (EdgeInitData memory ei, ) = testCanConfirmByOneStep(); IERC20 stakeToken = ei.challengeManager.stakeToken(); assertEq( stakeToken.balanceOf(excessStakeReceiver), @@ -1683,7 +2375,10 @@ contract EdgeChallengeManagerTest is Test { (EdgeInitData memory ei, BisectionChildren[] memory allWinners) = testCanConfirmByOneStep(); ei.challengeManager.refundStake(allWinners[allWinners.length - 1].lowerChildId); vm.expectRevert( - abi.encodeWithSelector(EdgeAlreadyRefunded.selector, allWinners[allWinners.length - 1].lowerChildId) + abi.encodeWithSelector( + EdgeAlreadyRefunded.selector, + allWinners[allWinners.length - 1].lowerChildId + ) ); ei.challengeManager.refundStake(allWinners[allWinners.length - 1].lowerChildId); } @@ -1691,7 +2386,12 @@ contract EdgeChallengeManagerTest is Test { function testRevertRefundStakeNotLayerZero() external { (EdgeInitData memory ei, BisectionChildren[] memory allWinners) = testCanConfirmByOneStep(); vm.expectRevert( - abi.encodeWithSelector(EdgeNotLayerZero.selector, allWinners[allWinners.length - 2].lowerChildId, 0, 0) + abi.encodeWithSelector( + EdgeNotLayerZero.selector, + allWinners[allWinners.length - 2].lowerChildId, + 0, + 0 + ) ); ei.challengeManager.refundStake(allWinners[allWinners.length - 2].lowerChildId); } @@ -1719,9 +2419,11 @@ contract EdgeChallengeManagerTest is Test { } function testRevertRefundStakeNotConfirmed() external { - (EdgeInitData memory ei,,, bytes32 edgeId) = testCanCreateEdgeWithStake(); + (EdgeInitData memory ei, , , bytes32 edgeId) = testCanCreateEdgeWithStake(); - vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, edgeId, EdgeStatus.Pending)); + vm.expectRevert( + abi.encodeWithSelector(EdgeNotConfirmed.selector, edgeId, EdgeStatus.Pending) + ); ei.challengeManager.refundStake(edgeId); } @@ -1734,8 +2436,15 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) - ); + CreateBlockEdgesBisectArgs( + ei.challengeManager, + ei.a1, + ei.a2, + ei.a1State, + ei.a2State, + false + ) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( diff --git a/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol b/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol index 087d95598..d86f5990f 100644 --- a/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol +++ b/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol @@ -12,15 +12,21 @@ import "./Utils.sol"; contract MockOneStepProofEntry is IOneStepProofEntry { using GlobalStateLib for GlobalState; - function proveOneStep(ExecutionContext calldata, uint256, bytes32, bytes calldata proof) - external - pure - returns (bytes32 afterHash) - { + function proveOneStep( + ExecutionContext calldata, + uint256, + bytes32, + bytes calldata proof + ) external pure returns (bytes32 afterHash) { return bytes32(proof); } - function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { + function getMachineHash(ExecutionState calldata execState) + external + pure + override + returns (bytes32) + { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return GlobalStateLib.hash(execState.globalState); } @@ -59,7 +65,14 @@ contract EdgeChallengeManagerLibAccess { uint256 expectedEndHeight, uint8 numBigStepLevel ) public returns (EdgeAddedData memory) { - return store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, numBigStepLevel); + return + store.createLayerZeroEdge( + args, + ard, + oneStepProofEntry, + expectedEndHeight, + numBigStepLevel + ); } function getPrevAssertionHash(bytes32 edgeId) public view returns (bytes32) { @@ -86,9 +99,17 @@ contract EdgeChallengeManagerLibAccess { return EdgeChallengeManagerLib.mandatoryBisectionHeight(start, end); } - function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes memory prefixProof) + function bisectEdge( + bytes32 edgeId, + bytes32 bisectionHistoryRoot, + bytes memory prefixProof + ) public - returns (bytes32, EdgeAddedData memory, EdgeAddedData memory) + returns ( + bytes32, + EdgeAddedData memory, + EdgeAddedData memory + ) { return store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); } @@ -133,7 +154,11 @@ contract EdgeChallengeManagerLibAccess { return store.confirmedRivals[mutualId]; } - function confirmEdgeByClaim(bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) public { + function confirmEdgeByClaim( + bytes32 edgeId, + bytes32 claimingEdgeId, + uint8 numBigStepLevel + ) public { return store.confirmEdgeByClaim(edgeId, claimingEdgeId, numBigStepLevel); } @@ -144,9 +169,14 @@ contract EdgeChallengeManagerLibAccess { uint64 confirmationThresholdBlock, uint8 numBigStepLevel ) public returns (uint64) { - return store.confirmEdgeByTime( - edgeId, ancestorEdgeIds, claimedAssertionUnrivaledBlocks, confirmationThresholdBlock, numBigStepLevel - ); + return + store.confirmEdgeByTime( + edgeId, + ancestorEdgeIds, + claimedAssertionUnrivaledBlocks, + confirmationThresholdBlock, + numBigStepLevel + ); } function confirmEdgeByOneStepProof( @@ -158,15 +188,16 @@ contract EdgeChallengeManagerLibAccess { bytes32[] calldata afterHistoryInclusionProof, uint8 numBigStepLevel ) public { - return store.confirmEdgeByOneStepProof( - edgeId, - oneStepProofEntry, - oneStepData, - execCtx, - beforeHistoryInclusionProof, - afterHistoryInclusionProof, - numBigStepLevel - ); + return + store.confirmEdgeByOneStepProof( + edgeId, + oneStepProofEntry, + oneStepData, + execCtx, + beforeHistoryInclusionProof, + afterHistoryInclusionProof, + numBigStepLevel + ); } } @@ -186,8 +217,22 @@ contract EdgeChallengeManagerLibTest is Test { function twoNonRivals() internal returns (ChallengeEdge memory, ChallengeEdge memory) { bytes32 originId = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + rand.hash(), + 3, + rand.hash(), + 9, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + rand.hash(), + 3, + rand.hash(), + 9, + 0 + ); return (edge1, edge2); } @@ -196,16 +241,38 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 3, + rand.hash(), + 9, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 3, + rand.hash(), + 9, + 0 + ); return (edge1, edge2); } - function checkEdgeAddedData(ChallengeEdge memory edge, bool hasRival, EdgeAddedData memory d) internal { + function checkEdgeAddedData( + ChallengeEdge memory edge, + bool hasRival, + EdgeAddedData memory d + ) internal { bytes32 id = edge.idMem(); bytes32 mutualId = ChallengeEdgeLib.mutualIdComponent( - edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight + edge.level, + edge.originId, + edge.startHeight, + edge.startHistoryRoot, + edge.endHeight ); assertEq(id, d.edgeId, "invalid edge id"); assertEq(mutualId, d.mutualId, "invalid mutual id"); @@ -217,19 +284,22 @@ contract EdgeChallengeManagerLibTest is Test { } function testAdd() public { - (ChallengeEdge memory edge,) = twoNonRivals(); + (ChallengeEdge memory edge, ) = twoNonRivals(); EdgeAddedData memory d = store.add(edge); ChallengeEdge memory se = store.get(edge.idMem()); assertTrue(store.exists(edge.idMem()), "Edge exists"); - assertTrue(store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "NO_RIVAL first rival"); + assertTrue( + store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, + "NO_RIVAL first rival" + ); checkEdgeAddedData(se, false, d); } function testGet() public { - (ChallengeEdge memory edge,) = twoNonRivals(); + (ChallengeEdge memory edge, ) = twoNonRivals(); store.add(edge); @@ -238,7 +308,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testGetNotExist() public { - (ChallengeEdge memory edge,) = twoNonRivals(); + (ChallengeEdge memory edge, ) = twoNonRivals(); bytes32 edgeId = edge.idMem(); @@ -265,7 +335,12 @@ contract EdgeChallengeManagerLibTest is Test { function testAddMoreRivals() public { (ChallengeEdge memory edge1, ChallengeEdge memory edge2) = twoRivals(); ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( - edge1.originId, edge1.startHistoryRoot, edge1.startHeight, rand.hash(), edge1.endHeight, 0 + edge1.originId, + edge1.startHistoryRoot, + edge1.startHeight, + rand.hash(), + edge1.endHeight, + 0 ); store.add(edge1); @@ -290,12 +365,25 @@ contract EdgeChallengeManagerLibTest is Test { ChallengeEdge memory se = store.get(edge1.idMem()); ChallengeEdge memory se2 = store.get(edge2.idMem()); assertTrue(store.exists(se2.idMem()), "Edge exists"); - assertTrue(store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "First rival1"); - assertTrue(store.firstRivals(se2.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "First rival2"); + assertTrue( + store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, + "First rival1" + ); + assertTrue( + store.firstRivals(se2.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, + "First rival2" + ); } function testCannotAddSameEdgeTwice() public { - ChallengeEdge memory edge = ChallengeEdgeLib.newChildEdge(rand.hash(), rand.hash(), 0, rand.hash(), 10, 0); + ChallengeEdge memory edge = ChallengeEdgeLib.newChildEdge( + rand.hash(), + rand.hash(), + 0, + rand.hash(), + 10, + 0 + ); store.add(edge); @@ -328,7 +416,12 @@ contract EdgeChallengeManagerLibTest is Test { function testHasRivalMore() public { (ChallengeEdge memory edge1, ChallengeEdge memory edge2) = twoRivals(); ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( - edge1.originId, edge1.startHistoryRoot, edge1.startHeight, rand.hash(), edge1.endHeight, 0 + edge1.originId, + edge1.startHistoryRoot, + edge1.startHeight, + rand.hash(), + edge1.endHeight, + 0 ); store.add(edge1); @@ -362,8 +455,22 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotRival() public { bytes32 originId = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 9, rand.hash(), 10, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 9, rand.hash(), 10, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + rand.hash(), + 9, + rand.hash(), + 10, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + rand.hash(), + 9, + rand.hash(), + 10, + 0 + ); store.add(edge1); store.add(edge2); @@ -375,8 +482,22 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotHeight() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 8, rand.hash(), 10, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 8, rand.hash(), 10, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 8, + rand.hash(), + 10, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 8, + rand.hash(), + 10, + 0 + ); store.add(edge1); store.add(edge2); @@ -388,8 +509,22 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRival() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 9, + rand.hash(), + 10, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 9, + rand.hash(), + 10, + 0 + ); store.add(edge1); store.add(edge2); @@ -401,8 +536,22 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotExist() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 9, + rand.hash(), + 10, + 0 + ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 9, + rand.hash(), + 10, + 0 + ); store.add(edge1); @@ -412,7 +561,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaled() public { - (ChallengeEdge memory edge1,) = twoRivals(); + (ChallengeEdge memory edge1, ) = twoRivals(); store.add(edge1); vm.roll(block.number + 3); @@ -434,7 +583,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaledFirstRivalNotExist() public { - (ChallengeEdge memory edge1,) = twoRivals(); + (ChallengeEdge memory edge1, ) = twoRivals(); store.add(edge1); vm.roll(block.number + 3); @@ -445,7 +594,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaledNotExist() public { - (ChallengeEdge memory edge1,) = twoRivals(); + (ChallengeEdge memory edge1, ) = twoRivals(); vm.roll(block.number + 3); @@ -457,22 +606,50 @@ contract EdgeChallengeManagerLibTest is Test { function testTimeUnrivaledAfterRival() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 3, + rand.hash(), + 9, + 0 + ); store.add(edge1); vm.roll(block.number + 4); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 3, + rand.hash(), + 9, + 0 + ); store.add(edge2); vm.roll(block.number + 5); - ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); + ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( + originId, + startRoot, + 3, + rand.hash(), + 9, + 0 + ); store.add(edge3); vm.roll(block.number + 6); - ChallengeEdge memory edge4 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); + ChallengeEdge memory edge4 = ChallengeEdgeLib.newChildEdge( + originId, + rand.hash(), + 3, + rand.hash(), + 9, + 0 + ); store.add(edge4); vm.roll(block.number + 7); @@ -565,11 +742,15 @@ contract EdgeChallengeManagerLibTest is Test { return (full, exp); } - function appendRandomStatesBetween(bytes32[] memory currentStates, bytes32 endState, uint256 numStates) - internal - returns (bytes32[] memory, bytes32[] memory) - { - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates(currentStates, numStates - 1); + function appendRandomStatesBetween( + bytes32[] memory currentStates, + bytes32 endState, + uint256 numStates + ) internal returns (bytes32[] memory, bytes32[] memory) { + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates( + currentStates, + numStates - 1 + ); bytes32[] memory fullStates = ArrayUtilsLib.append(states, endState); bytes32[] memory fullExp = MerkleTreeLib.appendLeaf(exp, endState); return (fullStates, fullExp); @@ -581,37 +762,58 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end; } - function rivalStates(uint256 start, uint256 agreePoint, uint256 end) - internal - returns (bytes32[] memory, bytes32[] memory) - { + function rivalStates( + uint256 start, + uint256 agreePoint, + uint256 end + ) internal returns (bytes32[] memory, bytes32[] memory) { bytes32[] memory preStates = rand.hashes(start + 1); - (bytes32[] memory agreeStates,) = appendRandomStates(preStates, agreePoint - start); - (bytes32[] memory states1,) = appendRandomStates(agreeStates, end - agreePoint); + (bytes32[] memory agreeStates, ) = appendRandomStates(preStates, agreePoint - start); + (bytes32[] memory states1, ) = appendRandomStates(agreeStates, end - agreePoint); - (bytes32[] memory states2,) = appendRandomStates(agreeStates, end - agreePoint); + (bytes32[] memory states2, ) = appendRandomStates(agreeStates, end - agreePoint); return (states1, states2); } - function edgeFromStates(bytes32 originId, uint256 start, uint256 end, bytes32[] memory states) - internal - view - returns (ChallengeEdge memory) - { - bytes32 startRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, start + 1)); + function edgeFromStates( + bytes32 originId, + uint256 start, + uint256 end, + bytes32[] memory states + ) internal view returns (ChallengeEdge memory) { + bytes32 startRoot = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states, 0, start + 1) + ); bytes32 endRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, end + 1)); return ChallengeEdgeLib.newChildEdge(originId, startRoot, start, endRoot, end, 0); } - function proofGen(uint256 start, bytes32[] memory states) internal pure returns (bytes32[] memory) { - return ProofUtils.generatePrefixProof(start, ArrayUtilsLib.slice(states, start, states.length)); + function proofGen(uint256 start, bytes32[] memory states) + internal + pure + returns (bytes32[] memory) + { + return + ProofUtils.generatePrefixProof( + start, + ArrayUtilsLib.slice(states, start, states.length) + ); } - function twoRivalsFromLeaves(uint256 start, uint256 agreePoint, uint256 end) + function twoRivalsFromLeaves( + uint256 start, + uint256 agreePoint, + uint256 end + ) internal - returns (ChallengeEdge memory, ChallengeEdge memory, bytes32[] memory, bytes32[] memory) + returns ( + ChallengeEdge memory, + ChallengeEdge memory, + bytes32[] memory, + bytes32[] memory + ) { (bytes32[] memory states1, bytes32[] memory states2) = rivalStates(start, agreePoint, end); @@ -632,10 +834,20 @@ contract EdgeChallengeManagerLibTest is Test { EdgeAddedData memory upperChildAdded ) internal { ChallengeEdge memory lowerChild = ChallengeEdgeLib.newChildEdge( - edge.originId, edge.startHistoryRoot, edge.startHeight, bisectionRoot, bisectionHeight, edge.level + edge.originId, + edge.startHistoryRoot, + edge.startHeight, + bisectionRoot, + bisectionHeight, + edge.level ); ChallengeEdge memory upperChild = ChallengeEdgeLib.newChildEdge( - edge.originId, bisectionRoot, bisectionHeight, edge.endHistoryRoot, edge.endHeight, edge.level + edge.originId, + bisectionRoot, + bisectionHeight, + edge.endHistoryRoot, + edge.endHeight, + edge.level ); if (lowerChildAdded.edgeId != 0) { @@ -655,17 +867,21 @@ contract EdgeChallengeManagerLibTest is Test { bool lowerHasRival, bool upperHasRival ) internal { - (bytes32 lowerChildId, EdgeAddedData memory lowerChildAdded, EdgeAddedData memory upperChildAdded) = store - .bisectEdge( - edge.idMem(), - bisectionRoot, - abi.encode( - ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), - ProofUtils.generatePrefixProof( - bisectionPoint + 1, ArrayUtilsLib.slice(states, bisectionPoint + 1, states.length) + ( + bytes32 lowerChildId, + EdgeAddedData memory lowerChildAdded, + EdgeAddedData memory upperChildAdded + ) = store.bisectEdge( + edge.idMem(), + bisectionRoot, + abi.encode( + ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), + ProofUtils.generatePrefixProof( + bisectionPoint + 1, + ArrayUtilsLib.slice(states, bisectionPoint + 1, states.length) + ) ) - ) - ); + ); bisectEdgeEmitted( edge, bisectionRoot, @@ -684,13 +900,19 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + bytes32[] memory states2 + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bisectAndCheck(edge1, bisectionRoot1, bisectionPoint, states1, false, false); assertEq( @@ -712,7 +934,12 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge1.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge1.originId, bisectionRoot1, bisectionPoint, edge1.endHistoryRoot, edge1.endHeight, edge1.level + edge1.originId, + bisectionRoot1, + bisectionPoint, + edge1.endHistoryRoot, + edge1.endHeight, + edge1.level ) ).idMem(), "Lower child id" @@ -721,7 +948,9 @@ contract EdgeChallengeManagerLibTest is Test { assertFalse(store.hasRival(store.get(edge1.idMem()).lowerChildId), "Lower child rival"); assertFalse(store.hasRival(store.get(edge1.idMem()).upperChildId), "Upper child rival"); - bytes32 bisectionRoot2 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1)); + bytes32 bisectionRoot2 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1) + ); bisectAndCheck(edge2, bisectionRoot2, bisectionPoint, states2, true, false); assertEq( @@ -743,7 +972,12 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge2.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge2.originId, bisectionRoot2, bisectionPoint, edge2.endHistoryRoot, edge2.endHeight, edge2.level + edge2.originId, + bisectionRoot2, + bisectionPoint, + edge2.endHistoryRoot, + edge2.endHeight, + edge2.level ) ).idMem(), "Lower child id" @@ -758,13 +992,19 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + bytes32[] memory states2 + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bisectAndCheck(edge1, bisectionRoot1, bisectionPoint, states1, false, false); assertEq( @@ -786,7 +1026,12 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge1.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge1.originId, bisectionRoot1, bisectionPoint, edge1.endHistoryRoot, edge1.endHeight, edge1.level + edge1.originId, + bisectionRoot1, + bisectionPoint, + edge1.endHistoryRoot, + edge1.endHeight, + edge1.level ) ).idMem(), "Lower child id" @@ -795,7 +1040,9 @@ contract EdgeChallengeManagerLibTest is Test { assertFalse(store.hasRival(store.get(edge1.idMem()).lowerChildId), "Lower child rival"); assertFalse(store.hasRival(store.get(edge1.idMem()).upperChildId), "Upper child rival"); - bytes32 bisectionRoot2 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1)); + bytes32 bisectionRoot2 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1) + ); bisectAndCheck(edge2, bisectionRoot2, bisectionPoint, states2, false, true); assertEq( @@ -817,7 +1064,12 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge2.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge2.originId, bisectionRoot2, bisectionPoint, edge2.endHistoryRoot, edge2.endHeight, edge2.level + edge2.originId, + bisectionRoot2, + bisectionPoint, + edge2.endHistoryRoot, + edge2.endHeight, + edge2.level ) ).idMem(), "Lower child id" @@ -847,16 +1099,23 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1,, bytes32[] memory states1,) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, , bytes32[] memory states1, ) = twoRivalsFromLeaves( + start, + agree, + end + ); store.add(edge1); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, + ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); vm.expectRevert(abi.encodeWithSelector(EdgeUnrivaled.selector, edgeId)); @@ -869,23 +1128,32 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, + ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); store.bisectEdge(edgeId, bisectionRoot1, proof); - vm.expectRevert(abi.encodeWithSelector(EdgeAlreadyExists.selector, store.get(edgeId).upperChildId)); + vm.expectRevert( + abi.encodeWithSelector(EdgeAlreadyExists.selector, store.get(edgeId).upperChildId) + ); store.bisectEdge(edgeId, bisectionRoot1, proof); } @@ -895,18 +1163,25 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint), ProofUtils.generatePrefixProof( - bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, + ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); vm.expectRevert("Pre expansion root mismatch"); @@ -919,23 +1194,32 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + + ) = twoRivalsFromLeaves(start, agree, end); edge1.status = EdgeStatus.Confirmed; store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); + bytes32 bisectionRoot1 = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) + ); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, + ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); bytes32 edgeId = edge1.idMem(); - vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, edgeId, EdgeStatus.Confirmed)); + vm.expectRevert( + abi.encodeWithSelector(EdgeNotPending.selector, edgeId, EdgeStatus.Confirmed) + ); store.bisectEdge(edgeId, bisectionRoot1, proof); } @@ -960,40 +1244,72 @@ contract EdgeChallengeManagerLibTest is Test { store.bisectEdge(edgeId, edge1.endHistoryRoot, ""); } - function bisectArgs(bytes32[] memory states, uint256 start, uint256 end) + function bisectArgs( + bytes32[] memory states, + uint256 start, + uint256 end + ) internal view - returns (uint256, bytes32, bytes memory) + returns ( + uint256, + bytes32, + bytes memory + ) { uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - bytes32 bisectionRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1)); + bytes32 bisectionRoot = MerkleTreeLib.root( + ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1) + ); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), - ProofUtils.generatePrefixProof(bisectionPoint + 1, ArrayUtilsLib.slice(states, bisectionPoint + 1, end + 1)) + ProofUtils.generatePrefixProof( + bisectionPoint + 1, + ArrayUtilsLib.slice(states, bisectionPoint + 1, end + 1) + ) ); return (bisectionPoint, bisectionRoot, proof); } - function addParentAndChildren(uint256 start, uint256 agree, uint256 end) + function addParentAndChildren( + uint256 start, + uint256 agree, + uint256 end + ) internal - returns (bytes32, bytes32, bytes32) + returns ( + bytes32, + bytes32, + bytes32 + ) { - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = - twoRivalsFromLeaves(start, agree, end); + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(states1, start, end); - (bytes32 lowerChildId,, EdgeAddedData memory upperChildAdded) = - store.bisectEdge(edge1.idMem(), bisectionRoot, bisectionProof); + (bytes32 lowerChildId, , EdgeAddedData memory upperChildAdded) = store.bisectEdge( + edge1.idMem(), + bisectionRoot, + bisectionProof + ); return (edge1.idMem(), lowerChildId, upperChildAdded.edgeId); } function testConfirmEdgeByChildren() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1016,18 +1332,26 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(pc.upperChildId2); store.confirmEdgeByChildren(pc.edge1Id); - vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, pc.edge2Id, pc.edge1Id)); + vm.expectRevert( + abi.encodeWithSelector(RivalEdgeConfirmed.selector, pc.edge2Id, pc.edge1Id) + ); store.confirmEdgeByChildren(pc.edge2Id); } function testConfirmEdgeByChildrenAlreadyConfirmed() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); store.confirmEdgeByChildren(parentEdgeId); - vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, parentEdgeId, parentEdgeId)); + vm.expectRevert( + abi.encodeWithSelector(RivalEdgeConfirmed.selector, parentEdgeId, parentEdgeId) + ); store.confirmEdgeByChildren(parentEdgeId); } @@ -1039,7 +1363,11 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenLowerChildNotExist() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1050,7 +1378,11 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenUpperChildNotExist() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1061,27 +1393,43 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenLowerChildPending() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(upperChildId); - vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, lowerChildId, EdgeStatus.Pending)); + vm.expectRevert( + abi.encodeWithSelector(EdgeNotConfirmed.selector, lowerChildId, EdgeStatus.Pending) + ); store.confirmEdgeByChildren(parentEdgeId); } function testConfirmEdgeByChildrenUpperChildPending() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( + 3, + 5, + 11 + ); store.setConfirmed(lowerChildId); - vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, upperChildId, EdgeStatus.Pending)); + vm.expectRevert( + abi.encodeWithSelector(EdgeNotConfirmed.selector, upperChildId, EdgeStatus.Pending) + ); store.confirmEdgeByChildren(parentEdgeId); } function testNextlevel() public { assertTrue(store.nextEdgeLevel(0, NUM_BIGSTEP_LEVEL) == 1); - assertTrue(store.nextEdgeLevel(NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL) == NUM_BIGSTEP_LEVEL + 1); - vm.expectRevert(abi.encodeWithSelector(LevelTooHigh.selector, NUM_BIGSTEP_LEVEL + 2, NUM_BIGSTEP_LEVEL)); + assertTrue( + store.nextEdgeLevel(NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL) == NUM_BIGSTEP_LEVEL + 1 + ); + vm.expectRevert( + abi.encodeWithSelector(LevelTooHigh.selector, NUM_BIGSTEP_LEVEL + 2, NUM_BIGSTEP_LEVEL) + ); store.nextEdgeLevel(NUM_BIGSTEP_LEVEL + 1, NUM_BIGSTEP_LEVEL); } @@ -1107,7 +1455,9 @@ contract EdgeChallengeManagerLibTest is Test { assertTrue(store.get(bargs.upperChildId1).status == EdgeStatus.Confirmed, "Edge confirmed"); assertEq( - store.confirmedRivals(store.get(bargs.upperChildId1).mutualIdMem()), bargs.upperChildId1, "Confirmed rival" + store.confirmedRivals(store.get(bargs.upperChildId1).mutualIdMem()), + bargs.upperChildId1, + "Confirmed rival" ); } @@ -1133,7 +1483,13 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(bargs.upperChildId2); store.setConfirmedRival(bargs.upperChildId2); - vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, bargs.upperChildId1, bargs.upperChildId2)); + vm.expectRevert( + abi.encodeWithSelector( + RivalEdgeConfirmed.selector, + bargs.upperChildId1, + bargs.upperChildId2 + ) + ); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1141,7 +1497,14 @@ contract EdgeChallengeManagerLibTest is Test { BArgs memory bargs = addParentsAndChildren(2, 3, 4); ChallengeEdge memory ce = ChallengeEdgeLib.newLayerZeroEdge( - rand.hash(), rand.hash(), 3, rand.hash(), 4, bargs.upperChildId1, rand.addr(), NUM_BIGSTEP_LEVEL + rand.hash(), + rand.hash(), + 3, + rand.hash(), + 4, + bargs.upperChildId1, + rand.addr(), + NUM_BIGSTEP_LEVEL ); store.add(ce); @@ -1149,7 +1512,9 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(eid); vm.expectRevert( abi.encodeWithSelector( - OriginIdMutualIdMismatch.selector, store.get(bargs.upperChildId1).mutualIdMem(), store.get(eid).originId + OriginIdMutualIdMismatch.selector, + store.get(bargs.upperChildId1).mutualIdMem(), + store.get(eid).originId ) ); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); @@ -1188,13 +1553,26 @@ contract EdgeChallengeManagerLibTest is Test { BArgs memory bargs = addParentsAndChildren(2, 3, 4); ChallengeEdge memory ce = ChallengeEdgeLib.newLayerZeroEdge( - store.get(bargs.upperChildId1).mutualIdMem(), rand.hash(), 3, rand.hash(), 4, rand.hash(), rand.addr(), 1 + store.get(bargs.upperChildId1).mutualIdMem(), + rand.hash(), + 3, + rand.hash(), + 4, + rand.hash(), + rand.addr(), + 1 ); store.add(ce); bytes32 eid = ce.idMem(); store.setConfirmed(eid); - vm.expectRevert(abi.encodeWithSelector(EdgeClaimMismatch.selector, bargs.upperChildId1, store.get(eid).claimId)); + vm.expectRevert( + abi.encodeWithSelector( + EdgeClaimMismatch.selector, + bargs.upperChildId1, + store.get(eid).claimId + ) + ); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1236,7 +1614,13 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 eid = ce.idMem(); store.setConfirmed(eid); store.setConfirmed(bargs.upperChildId1); - vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, bargs.upperChildId1, EdgeStatus.Confirmed)); + vm.expectRevert( + abi.encodeWithSelector( + EdgeNotPending.selector, + bargs.upperChildId1, + EdgeStatus.Confirmed + ) + ); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1279,13 +1663,18 @@ contract EdgeChallengeManagerLibTest is Test { store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } - function bisect(ChallengeEdge memory edge, bytes32[] memory states, uint256 start, uint256 end) - internal - returns (bytes32, bytes32) - { + function bisect( + ChallengeEdge memory edge, + bytes32[] memory states, + uint256 start, + uint256 end + ) internal returns (bytes32, bytes32) { (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(states, start, end); - (bytes32 lowerChildId,, EdgeAddedData memory upperChildAdded) = - store.bisectEdge(edge.idMem(), bisectionRoot, bisectionProof); + (bytes32 lowerChildId, , EdgeAddedData memory upperChildAdded) = store.bisectEdge( + edge.idMem(), + bisectionRoot, + bisectionProof + ); return (lowerChildId, upperChildAdded.edgeId); } @@ -1300,9 +1689,17 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] states2; } - function addParentsAndChildren(uint256 start, uint256 agree, uint256 end) internal returns (BArgs memory) { - (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = - twoRivalsFromLeaves(start, agree, end); + function addParentsAndChildren( + uint256 start, + uint256 agree, + uint256 end + ) internal returns (BArgs memory) { + ( + ChallengeEdge memory edge1, + ChallengeEdge memory edge2, + bytes32[] memory states1, + bytes32[] memory states2 + ) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); @@ -1310,9 +1707,17 @@ contract EdgeChallengeManagerLibTest is Test { (bytes32 lowerChildId1, bytes32 upperChildId1) = bisect(edge1, states1, start, end); (bytes32 lowerChildId2, bytes32 upperChildId2) = bisect(edge2, states2, start, end); - return BArgs( - edge1.idMem(), edge2.idMem(), lowerChildId1, upperChildId1, lowerChildId2, upperChildId2, states1, states2 - ); + return + BArgs( + edge1.idMem(), + edge2.idMem(), + lowerChildId1, + upperChildId1, + lowerChildId2, + upperChildId2, + states1, + states2 + ); } function claimWithMixedAncestors( @@ -1327,7 +1732,11 @@ contract EdgeChallengeManagerLibTest is Test { bytes memory revertArg; { (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(pc.states1, 4, 8); - (bytes32 lowerChildId148,,) = store.bisectEdge(pc.upperChildId1, bisectionRoot, bisectionProof); + (bytes32 lowerChildId148, , ) = store.bisectEdge( + pc.upperChildId1, + bisectionRoot, + bisectionProof + ); ancestorIds[1] = lowerChildId148; } vm.roll(block.number + timeAfterParent1); @@ -1336,14 +1745,25 @@ contract EdgeChallengeManagerLibTest is Test { { bytes32 lowerChildId248; { - (, bytes32 bisectionRoot2, bytes memory bisectionProof2) = bisectArgs(pc.states2, 4, 8); - (bytes32 lowerChildId248X,,) = store.bisectEdge(pc.upperChildId2, bisectionRoot2, bisectionProof2); + (, bytes32 bisectionRoot2, bytes memory bisectionProof2) = bisectArgs( + pc.states2, + 4, + 8 + ); + (bytes32 lowerChildId248X, , ) = store.bisectEdge( + pc.upperChildId2, + bisectionRoot2, + bisectionProof2 + ); lowerChildId248 = lowerChildId248X; } (, bytes32 bisectionRoot3, bytes memory bisectionProof3) = bisectArgs(pc.states1, 4, 6); - (,, EdgeAddedData memory upperChildId146Data) = - store.bisectEdge(ancestorIds[1], bisectionRoot3, bisectionProof3); + (, , EdgeAddedData memory upperChildId146Data) = store.bisectEdge( + ancestorIds[1], + bisectionRoot3, + bisectionProof3 + ); upperChildId146 = upperChildId146Data.edgeId; vm.roll(block.number + timeAfterParent2); @@ -1377,8 +1797,14 @@ contract EdgeChallengeManagerLibTest is Test { ancestorIds[2] = pc.upperChildId1; if (timeAfterParent1 == 137) { - ChallengeEdge memory childE1 = - ChallengeEdgeLib.newChildEdge(rand.hash(), rand.hash(), 10, rand.hash(), 100, 0); + ChallengeEdge memory childE1 = ChallengeEdgeLib.newChildEdge( + rand.hash(), + rand.hash(), + 10, + rand.hash(), + 100, + 0 + ); store.add(childE1); @@ -1425,18 +1851,33 @@ contract EdgeChallengeManagerLibTest is Test { store.add(bigStepZero2); store.setConfirmed(bigStepZero2.idMem()); store.setConfirmedRival(bigStepZero2.idMem()); - revertArg = abi.encodeWithSelector(RivalEdgeConfirmed.selector, bsId, bigStepZero2.idMem()); + revertArg = abi.encodeWithSelector( + RivalEdgeConfirmed.selector, + bsId, + bigStepZero2.idMem() + ); } - if (timeAfterParent1 + timeAfterParent2 + timeAfterZeroLayer + claimedAssertionBlocks == 4) { - revertArg = abi.encodeWithSelector(InsufficientConfirmationBlocks.selector, 4, challengePeriodBlock); + if ( + timeAfterParent1 + timeAfterParent2 + timeAfterZeroLayer + claimedAssertionBlocks == 4 + ) { + revertArg = abi.encodeWithSelector( + InsufficientConfirmationBlocks.selector, + 4, + challengePeriodBlock + ); } if (revertArg.length != 0) { vm.expectRevert(revertArg); } - uint256 totalTime = - store.confirmEdgeByTime(bsId, ancestorIds, claimedAssertionBlocks, challengePeriodBlock, NUM_BIGSTEP_LEVEL); + uint256 totalTime = store.confirmEdgeByTime( + bsId, + ancestorIds, + claimedAssertionBlocks, + challengePeriodBlock, + NUM_BIGSTEP_LEVEL + ); if (revertArg.length == 0) { assertTrue(store.get(bsId).status == EdgeStatus.Confirmed, "Edge confirmed"); @@ -1505,7 +1946,11 @@ contract EdgeChallengeManagerLibTest is Test { function confirmByOneStep(uint256 flag) internal { uint256 startHeight = 5; - (bytes32[] memory states1, bytes32[] memory states2) = rivalStates(startHeight, startHeight, startHeight + 1); + (bytes32[] memory states1, bytes32[] memory states2) = rivalStates( + startHeight, + startHeight, + startHeight + 1 + ); ConfirmByOneStepData memory data; data.e1 = ChallengeEdgeLib.newChildEdge( @@ -1548,18 +1993,27 @@ contract EdgeChallengeManagerLibTest is Test { if (flag != 4) { store.add(data.e2); } - OneStepData memory d = - OneStepData({beforeHash: states1[startHeight], proof: abi.encodePacked(states1[startHeight + 1])}); - ExecutionContext memory e = - ExecutionContext({maxInboxMessagesRead: 0, bridge: IBridge(address(0)), initialWasmModuleRoot: bytes32(0)}); + OneStepData memory d = OneStepData({ + beforeHash: states1[startHeight], + proof: abi.encodePacked(states1[startHeight + 1]) + }); + ExecutionContext memory e = ExecutionContext({ + maxInboxMessagesRead: 0, + bridge: IBridge(address(0)), + initialWasmModuleRoot: bytes32(0) + }); bytes32[] memory beforeProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, startHeight + 1)), startHeight + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, startHeight + 1)), + startHeight ); if (flag == 6) { beforeProof[0] = rand.hash(); data.revertArg = "Invalid inclusion proof"; } - bytes32[] memory afterProof = ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), startHeight + 1); + bytes32[] memory afterProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states1), + startHeight + 1 + ); if (flag == 7) { afterProof[0] = rand.hash(); data.revertArg = "Invalid inclusion proof"; @@ -1571,13 +2025,25 @@ contract EdgeChallengeManagerLibTest is Test { if (flag == 9) { store.setConfirmed(data.e2.idMem()); store.setConfirmedRival(data.e2.idMem()); - data.revertArg = abi.encodeWithSelector(RivalEdgeConfirmed.selector, data.e1.idMem(), data.e2.idMem()); + data.revertArg = abi.encodeWithSelector( + RivalEdgeConfirmed.selector, + data.e1.idMem(), + data.e2.idMem() + ); } if (data.revertArg.length != 0) { vm.expectRevert(data.revertArg); } - store.confirmEdgeByOneStepProof(eid, entry, d, e, beforeProof, afterProof, NUM_BIGSTEP_LEVEL); + store.confirmEdgeByOneStepProof( + eid, + entry, + d, + e, + beforeProof, + afterProof, + NUM_BIGSTEP_LEVEL + ); if (bytes(data.revertArg).length != 0) { // for flag one the edge does not exist @@ -1587,7 +2053,11 @@ contract EdgeChallengeManagerLibTest is Test { } } else { assertTrue(store.get(eid).status == EdgeStatus.Confirmed, "Edge confirmed"); - assertEq(store.getConfirmedRival(ChallengeEdgeLib.mutualIdMem(data.e1)), eid, "Confirmed rival"); + assertEq( + store.getConfirmedRival(ChallengeEdgeLib.mutualIdMem(data.e1)), + eid, + "Confirmed rival" + ); } } @@ -1637,7 +2107,7 @@ contract EdgeChallengeManagerLibTest is Test { assertEq(store.isPowerOfTwo(6), false); assertEq(store.isPowerOfTwo(7), false); assertEq(store.isPowerOfTwo(8), true); - assertEq(store.isPowerOfTwo(2 ** 17), true); + assertEq(store.isPowerOfTwo(2**17), true); assertEq(store.isPowerOfTwo(1 << 255), true); } @@ -1650,10 +2120,12 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] prefixProof; } - function newRootsAndProofs(uint256 startHeight, uint256 endHeight, bytes32 startState, bytes32 endState) - internal - returns (ExpsAndProofs memory) - { + function newRootsAndProofs( + uint256 startHeight, + uint256 endHeight, + bytes32 startState, + bytes32 endState + ) internal returns (ExpsAndProofs memory) { bytes32[] memory states; { if (startState == 0) { @@ -1668,21 +2140,38 @@ contract EdgeChallengeManagerLibTest is Test { startStates[0] = startState; bytes32[] memory endStates = new bytes32[](1); endStates[0] = endState; - states = ArrayUtilsLib.concat(ArrayUtilsLib.concat(startStates, innerStates), endStates); + states = ArrayUtilsLib.concat( + ArrayUtilsLib.concat(startStates, innerStates), + endStates + ); } bytes32[] memory startExp = ProofUtils.expansionFromLeaves(states, 0, startHeight + 1); bytes32[] memory expansion = ProofUtils.expansionFromLeaves(states, 0, endHeight + 1); // inclusion in the start root bytes32[] memory startInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states, 0, startHeight + 1)), startHeight + ProofUtils.rehashed(ArrayUtilsLib.slice(states, 0, startHeight + 1)), + startHeight + ); + bytes32[] memory endInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states), + endHeight ); - bytes32[] memory endInclusionProof = ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), endHeight); - bytes32[] memory prefixProof = - ProofUtils.generatePrefixProof(startHeight + 1, ArrayUtilsLib.slice(states, startHeight + 1, endHeight + 1)); + bytes32[] memory prefixProof = ProofUtils.generatePrefixProof( + startHeight + 1, + ArrayUtilsLib.slice(states, startHeight + 1, endHeight + 1) + ); - return ExpsAndProofs(states, startExp, expansion, startInclusionProof, endInclusionProof, prefixProof); + return + ExpsAndProofs( + states, + startExp, + expansion, + startInclusionProof, + endInclusionProof, + prefixProof + ); } struct ExecStateVars { @@ -1692,7 +2181,10 @@ contract EdgeChallengeManagerLibTest is Test { function randomExecutionState(IOneStepProofEntry os) private returns (ExecStateVars memory) { ExecutionState memory execState = ExecutionState( - GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), + GlobalState( + [rand.hash(), rand.hash()], + [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] + ), MachineStatus.FINISHED ); @@ -1703,15 +2195,20 @@ contract EdgeChallengeManagerLibTest is Test { function createZeroBlockEdge(uint256 mode) internal { bytes memory revertArg; MockOneStepProofEntry entry = new MockOneStepProofEntry(); - uint256 expectedEndHeight = 2 ** 2; + uint256 expectedEndHeight = 2**2; if (mode == 139) { - expectedEndHeight = 2 ** 5 - 1; + expectedEndHeight = 2**5 - 1; revertArg = abi.encodeWithSelector(NotPowerOfTwo.selector, expectedEndHeight); } ExecStateVars memory startExec = randomExecutionState(entry); ExecStateVars memory endExec = randomExecutionState(entry); - ExpsAndProofs memory roots = newRootsAndProofs(0, expectedEndHeight, startExec.machineHash, endExec.machineHash); + ExpsAndProofs memory roots = newRootsAndProofs( + 0, + expectedEndHeight, + startExec.machineHash, + endExec.machineHash + ); bytes32 claimId = rand.hash(); bytes32 endRoot; if (mode == 137) { @@ -1732,7 +2229,11 @@ contract EdgeChallengeManagerLibTest is Test { }); if (mode == 141) { ard.assertionHash = rand.hash(); - revertArg = abi.encodeWithSelector(AssertionHashMismatch.selector, ard.assertionHash, claimId); + revertArg = abi.encodeWithSelector( + AssertionHashMismatch.selector, + ard.assertionHash, + claimId + ); } if (mode == 142) { ard.isPending = false; @@ -1776,8 +2277,8 @@ contract EdgeChallengeManagerLibTest is Test { proof: proof }); if (mode == 138) { - args.endHeight = 2 ** 4; - revertArg = abi.encodeWithSelector(InvalidEndHeight.selector, 2 ** 4, expectedEndHeight); + args.endHeight = 2**4; + revertArg = abi.encodeWithSelector(InvalidEndHeight.selector, 2**4, expectedEndHeight); } if (mode == 148) { args.prefixProof = ""; @@ -1787,13 +2288,21 @@ contract EdgeChallengeManagerLibTest is Test { if (revertArg.length != 0) { vm.expectRevert(revertArg); } - EdgeAddedData memory addedEdge = - store.createLayerZeroEdge(args, ard, entry, expectedEndHeight, NUM_BIGSTEP_LEVEL); + EdgeAddedData memory addedEdge = store.createLayerZeroEdge( + args, + ard, + entry, + expectedEndHeight, + NUM_BIGSTEP_LEVEL + ); if (revertArg.length == 0) { assertEq( store.get(addedEdge.edgeId).startHistoryRoot, MerkleTreeLib.root( - MerkleTreeLib.appendLeaf(new bytes32[](0), mockOsp.getMachineHash(startExec.execState)) + MerkleTreeLib.appendLeaf( + new bytes32[](0), + mockOsp.getMachineHash(startExec.execState) + ) ), "Start history root" ); @@ -1852,10 +2361,12 @@ contract EdgeChallengeManagerLibTest is Test { createZeroBlockEdge(148); } - function createClaimEdge(EdgeChallengeManagerLibAccess c, uint256 start, uint256 end, bool includeRival) - public - returns (bytes32, ExpsAndProofs memory) - { + function createClaimEdge( + EdgeChallengeManagerLibAccess c, + uint256 start, + uint256 end, + bool includeRival + ) public returns (bytes32, ExpsAndProofs memory) { // create a claim edge ExpsAndProofs memory claimRoots = newRootsAndProofs(start, end, 0, 0); ChallengeEdge memory ce = ChallengeEdgeLib.newChildEdge( @@ -1871,7 +2382,12 @@ contract EdgeChallengeManagerLibTest is Test { if (includeRival) { c.add( ChallengeEdgeLib.newChildEdge( - ce.originId, ce.startHistoryRoot, ce.startHeight, rand.hash(), ce.endHeight, ce.level + ce.originId, + ce.startHistoryRoot, + ce.startHeight, + rand.hash(), + ce.endHeight, + ce.level ) ); } @@ -1898,14 +2414,24 @@ contract EdgeChallengeManagerLibTest is Test { vars.claimStartHeight = 4; vars.claimEndHeight = mode == 161 ? 6 : 5; - vars.expectedEndHeight = 2 ** 5; - (vars.claimId, vars.claimRoots) = - createClaimEdge(store, vars.claimStartHeight, vars.claimEndHeight, mode == 160 ? false : true); + vars.expectedEndHeight = 2**5; + (vars.claimId, vars.claimRoots) = createClaimEdge( + store, + vars.claimStartHeight, + vars.claimEndHeight, + mode == 160 ? false : true + ); if (mode == 160) { - vars.revertArg = abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, vars.claimId); + vars.revertArg = abi.encodeWithSelector( + ClaimEdgeNotLengthOneRival.selector, + vars.claimId + ); } if (mode == 161) { - vars.revertArg = abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, vars.claimId); + vars.revertArg = abi.encodeWithSelector( + ClaimEdgeNotLengthOneRival.selector, + vars.claimId + ); } vars.roots = newRootsAndProofs( @@ -1917,13 +2443,19 @@ contract EdgeChallengeManagerLibTest is Test { if (mode == 164) { bytes32[] memory b = new bytes32[](1); b[0] = rand.hash(); - vars.claimRoots.startInclusionProof = ArrayUtilsLib.concat(vars.claimRoots.startInclusionProof, b); + vars.claimRoots.startInclusionProof = ArrayUtilsLib.concat( + vars.claimRoots.startInclusionProof, + b + ); vars.revertArg = "Invalid inclusion proof"; } if (mode == 165) { bytes32[] memory b = new bytes32[](1); b[0] = rand.hash(); - vars.claimRoots.endInclusionProof = ArrayUtilsLib.concat(vars.claimRoots.endInclusionProof, b); + vars.claimRoots.endInclusionProof = ArrayUtilsLib.concat( + vars.claimRoots.endInclusionProof, + b + ); vars.revertArg = "Invalid inclusion proof"; } vars.proof = abi.encode( @@ -1931,7 +2463,10 @@ contract EdgeChallengeManagerLibTest is Test { vars.roots.states[vars.expectedEndHeight], vars.claimRoots.startInclusionProof, vars.claimRoots.endInclusionProof, - ProofUtils.generateInclusionProof(ProofUtils.rehashed(vars.roots.states), vars.expectedEndHeight) + ProofUtils.generateInclusionProof( + ProofUtils.rehashed(vars.roots.states), + vars.expectedEndHeight + ) ); if (mode == 166) { vars.proof = ""; @@ -1946,8 +2481,11 @@ contract EdgeChallengeManagerLibTest is Test { vars.emptyArd; if (mode == 163) { - vars.revertArg = - abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL); + vars.revertArg = abi.encodeWithSelector( + ClaimEdgeInvalidLevel.selector, + NUM_BIGSTEP_LEVEL, + NUM_BIGSTEP_LEVEL + ); } if (vars.revertArg.length != 0) { vm.expectRevert(vars.revertArg); @@ -2009,7 +2547,8 @@ contract EdgeChallengeManagerLibTest is Test { } bytes32 genesisBlockHash = rand.hash(); - ExecutionState genesisState = StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); + ExecutionState genesisState = + StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); bytes32 genesisStateHash = StateToolsLib.mockMachineHash(genesisState); ExecutionStateData genesisStateData = ExecutionStateData(genesisState, bytes32(0), bytes32(0)); bytes32 genesisAssertionHash = rand.hash(); @@ -2040,20 +2579,23 @@ contract EdgeChallengeManagerLibTest is Test { ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) ); - return store.createLayerZeroEdge( - CreateEdgeArgs({ - level: 0, - endHistoryRoot: MerkleTreeLib.root(exp), - endHeight: height1, - claimId: claimId, - prefixProof: prefixProof, - proof: typeSpecificProof1 - }), - ard, - mockOsp, - expectedEndHeight, - numBigStepLevel - ).edgeId; + return + store + .createLayerZeroEdge( + CreateEdgeArgs({ + level: 0, + endHistoryRoot: MerkleTreeLib.root(exp), + endHeight: height1, + claimId: claimId, + prefixProof: prefixProof, + proof: typeSpecificProof1 + }), + ard, + mockOsp, + expectedEndHeight, + numBigStepLevel + ) + .edgeId; } struct BisectionChildren { @@ -2069,14 +2611,16 @@ contract EdgeChallengeManagerLibTest is Test { bool skipLast; } - function bisect(bytes32 edgeId, bytes32[] memory states, uint256 bisectionSize, uint256 endSize) - internal - returns (BisectionChildren memory) - { + function bisect( + bytes32 edgeId, + bytes32[] memory states, + uint256 bisectionSize, + uint256 endSize + ) internal returns (BisectionChildren memory) { bytes32[] memory middleExp = ProofUtils.expansionFromLeaves(states, 0, bisectionSize + 1); bytes32[] memory upperStates = ArrayUtilsLib.slice(states, bisectionSize + 1, endSize + 1); - (bytes32 lowerChildId,, EdgeAddedData memory upperChild) = store.bisectEdge( + (bytes32 lowerChildId, , EdgeAddedData memory upperChild) = store.bisectEdge( edgeId, MerkleTreeLib.root(middleExp), abi.encode(middleExp, ProofUtils.generatePrefixProof(bisectionSize + 1, upperStates)) @@ -2096,8 +2640,18 @@ contract EdgeChallengeManagerLibTest is Test { losingEdges[5] = BisectionChildren(args.losingId, 0); // height 16 - winningEdges[4] = bisect(winningEdges[5].lowerChildId, args.winningLeaves, 16, args.winningLeaves.length - 1); - losingEdges[4] = bisect(losingEdges[5].lowerChildId, args.losingLeaves, 16, args.losingLeaves.length - 1); + winningEdges[4] = bisect( + winningEdges[5].lowerChildId, + args.winningLeaves, + 16, + args.winningLeaves.length - 1 + ); + losingEdges[4] = bisect( + losingEdges[5].lowerChildId, + args.losingLeaves, + 16, + args.losingLeaves.length - 1 + ); // height 8 winningEdges[3] = bisect(winningEdges[4].lowerChildId, args.winningLeaves, 8, 16); @@ -2121,21 +2675,36 @@ contract EdgeChallengeManagerLibTest is Test { function createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs memory args) internal - returns (bytes32[] memory, bytes32[] memory, BisectionChildren[6] memory, BisectionChildren[6] memory) + returns ( + bytes32[] memory, + bytes32[] memory, + BisectionChildren[6] memory, + BisectionChildren[6] memory + ) { bytes32[] memory states1; bytes32 edge1Id; { bytes32[] memory exp1; - (states1, exp1) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState1), height1); + (states1, exp1) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(args.endState1), + height1 + ); edge1Id = createLayerZeroEdge( args.claim1Id, args.endState1, states1, exp1, - AssertionReferenceData(args.claim1Id, genesisAssertionHash, true, true, genesisState, args.endState1), + AssertionReferenceData( + args.claim1Id, + genesisAssertionHash, + true, + true, + genesisState, + args.endState1 + ), 32, 1 ); @@ -2149,11 +2718,28 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 edge2Id; { bytes32[] memory exp2; - (states2, exp2) = - appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState2), height1); - AssertionReferenceData memory ard2 = - AssertionReferenceData(args.claim2Id, genesisAssertionHash, true, true, genesisState, args.endState2); - edge2Id = createLayerZeroEdge(args.claim2Id, args.endState2, states2, exp2, ard2, 32, 1); + (states2, exp2) = appendRandomStatesBetween( + genesisStates(), + StateToolsLib.mockMachineHash(args.endState2), + height1 + ); + AssertionReferenceData memory ard2 = AssertionReferenceData( + args.claim2Id, + genesisAssertionHash, + true, + true, + genesisState, + args.endState2 + ); + edge2Id = createLayerZeroEdge( + args.claim2Id, + args.endState2, + states2, + exp2, + ard2, + 32, + 1 + ); vm.roll(block.number + 2); @@ -2161,8 +2747,9 @@ contract EdgeChallengeManagerLibTest is Test { assertEq(store.timeUnrivaled(edge2Id), 0, "Edge2 timer 2"); } - (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = - bisectToForkOnly(BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast)); + (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( + BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast) + ); return (states1, states2, edges1, edges2); } @@ -2191,19 +2778,27 @@ contract EdgeChallengeManagerLibTest is Test { internal returns (BisectionData memory) { - (bytes32[] memory states1, bytes32[] memory exp1) = - appendRandomStatesBetween(genesisStates(), args.endState1, height1); + (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( + genesisStates(), + args.endState1, + height1 + ); bytes32 edge1Id; { bytes memory typeSpecificProof1; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), 0 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(args.forkStates1), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states1), + states1.length - 1 ); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates1), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), states1.length - 1); typeSpecificProof1 = abi.encode( genesisStateHash, args.endState1, @@ -2212,42 +2807,55 @@ contract EdgeChallengeManagerLibTest is Test { edgeInclusionProof ); } - edge1Id = store.createLayerZeroEdge( - CreateEdgeArgs({ - level: args.eType, - endHistoryRoot: MerkleTreeLib.root(exp1), - endHeight: height1, - claimId: args.claim1Id, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) + edge1Id = store + .createLayerZeroEdge( + CreateEdgeArgs({ + level: args.eType, + endHistoryRoot: MerkleTreeLib.root(exp1), + endHeight: height1, + claimId: args.claim1Id, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states1, 0, 1), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states1, 1, states1.length) + ) ), - proof: typeSpecificProof1 - }), - emptyArd, - mockOsp, - 32, - 1 - ).edgeId; + proof: typeSpecificProof1 + }), + emptyArd, + mockOsp, + 32, + 1 + ) + .edgeId; } vm.roll(block.number + 1); assertEq(store.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = - appendRandomStatesBetween(genesisStates(), args.endState2, height1); + (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( + genesisStates(), + args.endState2, + height1 + ); bytes32 edge2Id; { bytes memory typeSpecificProof2; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), 0 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), + 0 + ); + bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(args.forkStates2), + 1 + ); + bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( + ProofUtils.rehashed(states2), + states2.length - 1 ); - bytes32[] memory claimEndInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates2), 1); - bytes32[] memory edgeInclusionProof = - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1); typeSpecificProof2 = abi.encode( genesisStateHash, args.endState2, @@ -2256,29 +2864,35 @@ contract EdgeChallengeManagerLibTest is Test { edgeInclusionProof ); } - edge2Id = store.createLayerZeroEdge( - CreateEdgeArgs({ - level: args.eType, - endHistoryRoot: MerkleTreeLib.root(exp2), - endHeight: height1, - claimId: args.claim2Id, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) + edge2Id = store + .createLayerZeroEdge( + CreateEdgeArgs({ + level: args.eType, + endHistoryRoot: MerkleTreeLib.root(exp2), + endHeight: height1, + claimId: args.claim2Id, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states2, 0, 1), + ProofUtils.generatePrefixProof( + 1, + ArrayUtilsLib.slice(states2, 1, states2.length) + ) ), - proof: typeSpecificProof2 - }), - emptyArd, - mockOsp, - 32, - 1 - ).edgeId; + proof: typeSpecificProof2 + }), + emptyArd, + mockOsp, + 32, + 1 + ) + .edgeId; } vm.roll(block.number + 2); - (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = - bisectToForkOnly(BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast)); + (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( + BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast) + ); return BisectionData(states1, states2, edges1, edges2); } @@ -2291,10 +2905,16 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 h1 = rand.hash(); bytes32 h2 = rand.hash(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED + rand, + GlobalStateLib.getInboxPosition(genesisState.globalState), + h1, + MachineStatus.FINISHED ); ExecutionState memory a2State = StateToolsLib.randomState( - rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h2, MachineStatus.FINISHED + rand, + GlobalStateLib.getInboxPosition(genesisState.globalState), + h2, + MachineStatus.FINISHED ); ( @@ -2302,7 +2922,9 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] memory blockStates2, BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 - ) = createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs(a1, a2, a1State, a2State, false)); + ) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(a1, a2, a1State, a2State, false) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -2331,10 +2953,14 @@ contract EdgeChallengeManagerLibTest is Test { ); assertEq( - store.getPrevAssertionHash(blockEdges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" + store.getPrevAssertionHash(blockEdges1[5].lowerChildId), + genesisAssertionHash, + "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(blockEdges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" + store.getPrevAssertionHash(blockEdges2[5].lowerChildId), + genesisAssertionHash, + "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { @@ -2361,10 +2987,14 @@ contract EdgeChallengeManagerLibTest is Test { } assertEq( - store.getPrevAssertionHash(bsbd.edges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" + store.getPrevAssertionHash(bsbd.edges1[5].lowerChildId), + genesisAssertionHash, + "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(bsbd.edges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" + store.getPrevAssertionHash(bsbd.edges2[5].lowerChildId), + genesisAssertionHash, + "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { @@ -2391,10 +3021,14 @@ contract EdgeChallengeManagerLibTest is Test { } assertEq( - store.getPrevAssertionHash(ssbd.edges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" + store.getPrevAssertionHash(ssbd.edges1[5].lowerChildId), + genesisAssertionHash, + "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(ssbd.edges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" + store.getPrevAssertionHash(ssbd.edges2[5].lowerChildId), + genesisAssertionHash, + "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { diff --git a/contracts/test/challengeV2/MerkleTreeLib.t.sol b/contracts/test/challengeV2/MerkleTreeLib.t.sol index 81ea0f793..db3cd70f2 100644 --- a/contracts/test/challengeV2/MerkleTreeLib.t.sol +++ b/contracts/test/challengeV2/MerkleTreeLib.t.sol @@ -48,7 +48,11 @@ contract MerkleTreeLibTest is Test { function expansionsFromLeaves(bytes32[] memory leaves, uint256 lowSize) public pure - returns (bytes32[] memory, bytes32[] memory, bytes32[] memory) + returns ( + bytes32[] memory, + bytes32[] memory, + bytes32[] memory + ) { bytes32[] memory lowExpansion = new bytes32[](0); bytes32[] memory highExpansion = new bytes32[](0); @@ -69,13 +73,21 @@ contract MerkleTreeLibTest is Test { function proveVerify(uint256 startSize, uint256 endSize) internal { bytes32[] memory leaves = random.hashes(endSize); - (bytes32[] memory lowExp, bytes32[] memory highExp, bytes32[] memory diff) = - expansionsFromLeaves(leaves, startSize); + ( + bytes32[] memory lowExp, + bytes32[] memory highExp, + bytes32[] memory diff + ) = expansionsFromLeaves(leaves, startSize); bytes32[] memory proof = ProofUtils.generatePrefixProof(startSize, diff); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(lowExp), startSize, MerkleTreeLib.root(highExp), endSize, lowExp, proof + MerkleTreeLib.root(lowExp), + startSize, + MerkleTreeLib.root(highExp), + endSize, + lowExp, + proof ); } @@ -140,7 +152,10 @@ contract MerkleTreeLibTest is Test { function testRoot5() public { bytes32[] memory expansion = getExpansion(5); - bytes32 expectedRoot = hashTogether(expansion[2], hashTogether(hashTogether(expansion[0], 0), 0)); + bytes32 expectedRoot = hashTogether( + expansion[2], + hashTogether(hashTogether(expansion[0], 0), 0) + ); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -152,7 +167,10 @@ contract MerkleTreeLibTest is Test { function testRoot7() public { bytes32[] memory expansion = getExpansion(7); - bytes32 expectedRoot = hashTogether(expansion[2], hashTogether(expansion[1], hashTogether(expansion[0], 0))); + bytes32 expectedRoot = hashTogether( + expansion[2], + hashTogether(expansion[1], hashTogether(expansion[0], 0)) + ); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -164,14 +182,19 @@ contract MerkleTreeLibTest is Test { function testRoot9() public { bytes32[] memory expansion = getExpansion(9); - bytes32 expectedRoot = - hashTogether(expansion[3], hashTogether(hashTogether(hashTogether(expansion[0], 0), 0), 0)); + bytes32 expectedRoot = hashTogether( + expansion[3], + hashTogether(hashTogether(hashTogether(expansion[0], 0), 0), 0) + ); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } function testRoot11() public { bytes32[] memory expansion = getExpansion(10); - bytes32 expectedRoot = hashTogether(expansion[3], hashTogether(hashTogether(expansion[1], 0), 0)); + bytes32 expectedRoot = hashTogether( + expansion[3], + hashTogether(hashTogether(expansion[1], 0), 0) + ); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -220,7 +243,7 @@ contract MerkleTreeLibTest is Test { uint256 preSize = MerkleTreeLib.treeSize(expansion); uint256 postSize = MerkleTreeLib.treeSize(post); - assertEq(postSize, preSize + (2 ** i), "Sizes"); + assertEq(postSize, preSize + (2**i), "Sizes"); } } @@ -259,7 +282,11 @@ contract MerkleTreeLibTest is Test { if (i == level || i == level + 1) { assertEq(post[i], 0, "Post level equal"); } else if (i == level + 2) { - assertEq(post[i], hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), "Post level plus 1 equal"); + assertEq( + post[i], + hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), + "Post level plus 1 equal" + ); } else { assertEq(pre[i], post[i], "Pre post equal"); } @@ -278,7 +305,11 @@ contract MerkleTreeLibTest is Test { if (i == level || i == level + 1) { assertEq(post[i], 0, "Post level equal"); } else if (i == level + 2) { - assertEq(post[i], hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), "Post level plus 1 equal"); + assertEq( + post[i], + hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), + "Post level plus 1 equal" + ); } else { assertEq(pre[i], post[i], "Pre post equal"); } @@ -499,7 +530,14 @@ contract MerkleTreeLibTest is Test { proof[0] = rehashedLeaves[0]; proof[1] = hashTogether(rehashedLeaves[1], rehashedLeaves[2]); proof[2] = rehashedLeaves[3]; - MerkleTreeLib.verifyPrefixProof(MerkleTreeLib.root(pre), 5, MerkleTreeLib.root(post), 9, pre, proof); + MerkleTreeLib.verifyPrefixProof( + MerkleTreeLib.root(pre), + 5, + MerkleTreeLib.root(post), + 9, + pre, + proof + ); } function testVerifyPrefixProofPreZero() public { @@ -516,7 +554,12 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Pre-size cannot be 0"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), 0, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof + MerkleTreeLib.root(pre), + 0, + MerkleTreeLib.root(post), + preSize + newLeavesCount, + pre, + proof ); } @@ -535,7 +578,12 @@ contract MerkleTreeLibTest is Test { bytes32 randomHash = random.hash(); vm.expectRevert("Pre expansion root mismatch"); MerkleTreeLib.verifyPrefixProof( - randomHash, preSize, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof + randomHash, + preSize, + MerkleTreeLib.root(post), + preSize + newLeavesCount, + pre, + proof ); } @@ -553,7 +601,14 @@ contract MerkleTreeLibTest is Test { bytes32[] memory proof = ProofUtils.generatePrefixProof(preSize, newLeaves); vm.expectRevert("Pre size not less than post size"); - MerkleTreeLib.verifyPrefixProof(MerkleTreeLib.root(pre), preSize, MerkleTreeLib.root(post), preSize, pre, proof); + MerkleTreeLib.verifyPrefixProof( + MerkleTreeLib.root(pre), + preSize, + MerkleTreeLib.root(post), + preSize, + pre, + proof + ); } function testVerifyPrefixProofInvalidProofSize() public { @@ -572,7 +627,12 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Incomplete proof usage"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), preSize, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof + MerkleTreeLib.root(pre), + preSize, + MerkleTreeLib.root(post), + preSize + newLeavesCount, + pre, + proof ); } @@ -591,7 +651,12 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Pre size does not match expansion"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), preSize - 1, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof + MerkleTreeLib.root(pre), + preSize - 1, + MerkleTreeLib.root(post), + preSize + newLeavesCount, + pre, + proof ); } @@ -607,7 +672,10 @@ contract MerkleTreeLibTest is Test { proof[0] = re[5]; proof[1] = hashTogether(re[6], re[7]); proof[2] = hashTogether(hashTogether(re[0], re[1]), hashTogether(re[2], re[3])); - proof[3] = hashTogether(hashTogether(hashTogether(re[8], re[9]), hashTogether(re[10], 0)), 0); + proof[3] = hashTogether( + hashTogether(hashTogether(re[8], re[9]), hashTogether(re[10], 0)), + 0 + ); MerkleTreeLib.verifyInclusionProof(MerkleTreeLib.root(me), leaves[index], index, proof); } diff --git a/contracts/test/challengeV2/StateTools.sol b/contracts/test/challengeV2/StateTools.sol index faacbf586..f0c00e19f 100644 --- a/contracts/test/challengeV2/StateTools.sol +++ b/contracts/test/challengeV2/StateTools.sol @@ -13,10 +13,12 @@ import "./Utils.sol"; library StateToolsLib { using GlobalStateLib for GlobalState; - function randomState(Random rand, uint256 inboxMsgCountProcessed, bytes32 blockHash, MachineStatus ms) - internal - returns (ExecutionState memory) - { + function randomState( + Random rand, + uint256 inboxMsgCountProcessed, + bytes32 blockHash, + MachineStatus ms + ) internal returns (ExecutionState memory) { bytes32[2] memory bytes32Vals = [blockHash, rand.hash()]; uint64[2] memory u64Vals = [uint64(inboxMsgCountProcessed), uint64(uint256(rand.hash()))]; diff --git a/contracts/test/challengeV2/UintUtilsLib.t.sol b/contracts/test/challengeV2/UintUtilsLib.t.sol index 172c982e7..d01b0cfb5 100644 --- a/contracts/test/challengeV2/UintUtilsLib.t.sol +++ b/contracts/test/challengeV2/UintUtilsLib.t.sol @@ -28,7 +28,10 @@ contract UintUtilsLibTest is Test { assertEq(UintUtilsLib.leastSignificantBit(10), 1); // 1010 assertEq(UintUtilsLib.leastSignificantBit(696320), 13); // 10101010000000000000 assertEq(UintUtilsLib.leastSignificantBit(696321), 0); // 10101010000000000001 - assertEq(UintUtilsLib.leastSignificantBit(236945758459398306981350710526416285671374848), 14); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 + assertEq( + UintUtilsLib.leastSignificantBit(236945758459398306981350710526416285671374848), + 14 + ); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 assertEq(UintUtilsLib.leastSignificantBit(type(uint256).max), 0); } @@ -58,7 +61,10 @@ contract UintUtilsLibTest is Test { assertEq(UintUtilsLib.mostSignificantBit(10), 3); // 1010 assertEq(UintUtilsLib.mostSignificantBit(696320), 19); // 10101010000000000000 assertEq(UintUtilsLib.mostSignificantBit(696321), 19); // 10101010000000000001 - assertEq(UintUtilsLib.mostSignificantBit(236945758459398306981350710526416285671374848), 147); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 + assertEq( + UintUtilsLib.mostSignificantBit(236945758459398306981350710526416285671374848), + 147 + ); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 assertEq(UintUtilsLib.mostSignificantBit(type(uint256).max), 255); } diff --git a/contracts/test/challengeV2/Utils.sol b/contracts/test/challengeV2/Utils.sol index 0a88cc311..c1606c47c 100644 --- a/contracts/test/challengeV2/Utils.sol +++ b/contracts/test/challengeV2/Utils.sol @@ -46,11 +46,11 @@ library ProofUtils { /// @param leaves The leaves to form into an expansion /// @param leafStartIndex The subset of the leaves to start the expansion from - inclusive /// @param leafEndIndex The subset of the leaves to end the expansion from - exclusive - function expansionFromLeaves(bytes32[] memory leaves, uint256 leafStartIndex, uint256 leafEndIndex) - internal - pure - returns (bytes32[] memory) - { + function expansionFromLeaves( + bytes32[] memory leaves, + uint256 leafStartIndex, + uint256 leafEndIndex + ) internal pure returns (bytes32[] memory) { require(leafStartIndex < leafEndIndex, "Leaf start not less than leaf end"); require(leafEndIndex <= leaves.length, "Leaf end not less than leaf length"); @@ -101,7 +101,11 @@ library ProofUtils { return proof; } - function generateInclusionProof(bytes32[] memory leaves, uint256 index) internal pure returns (bytes32[] memory) { + function generateInclusionProof(bytes32[] memory leaves, uint256 index) + internal + pure + returns (bytes32[] memory) + { require(leaves.length >= 1, "No leaves"); require(index < leaves.length, "Index too high"); bytes32[][] memory fullT = fullTree(leaves); @@ -116,7 +120,9 @@ library ProofUtils { uint256 counterpartIndex = levelIndex ^ 1; bytes32[] memory layer = fullT[level]; - bytes32 counterpart = counterpartIndex > layer.length - 1 ? bytes32(0) : layer[counterpartIndex]; + bytes32 counterpart = counterpartIndex > layer.length - 1 + ? bytes32(0) + : layer[counterpartIndex]; proof[level] = counterpart; } @@ -138,7 +144,9 @@ library ProofUtils { bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2); for (uint256 i = 0; i < nextLayer.length; i++) { if (2 * i + 1 < prevLayer.length) { - nextLayer[i] = keccak256(abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1])); + nextLayer[i] = keccak256( + abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1]) + ); } else { nextLayer[i] = keccak256(abi.encodePacked(prevLayer[2 * i], bytes32(0))); } diff --git a/contracts/test/contract/common/challengeLib.ts b/contracts/test/contract/common/challengeLib.ts index 6a3602d22..b3b66b165 100644 --- a/contracts/test/contract/common/challengeLib.ts +++ b/contracts/test/contract/common/challengeLib.ts @@ -7,10 +7,7 @@ export enum MachineStatus { ERRORED = 2, } -export function machineHash( - machineStatus: BigNumber, - globalStateHash: string -) { +export function machineHash(machineStatus: BigNumber, globalStateHash: string) { const machineStatusNum = machineStatus.toNumber() if (machineStatusNum === MachineStatus.FINISHED) { return solidityKeccak256( diff --git a/contracts/test/stakingPool/AssertionStakingPool.t.sol b/contracts/test/stakingPool/AssertionStakingPool.t.sol index 7605ef004..e41ca2f00 100644 --- a/contracts/test/stakingPool/AssertionStakingPool.t.sol +++ b/contracts/test/stakingPool/AssertionStakingPool.t.sol @@ -49,11 +49,12 @@ contract AssertinPoolTest is Test { GlobalState emptyGlobalState; ExecutionState emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); - bytes32 genesisHash = RollupLib.assertionHash({ - parentAssertionHash: bytes32(0), - afterState: emptyExecutionState, - inboxAcc: bytes32(0) - }); + bytes32 genesisHash = + RollupLib.assertionHash({ + parentAssertionHash: bytes32(0), + afterState: emptyExecutionState, + inboxAcc: bytes32(0) + }); ExecutionState firstState; AssertionStakingPool pool; @@ -78,7 +79,11 @@ contract AssertinPoolTest is Test { uint64 inboxcount; event RollupCreated( - address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge + address indexed rollupAddress, + address inboxAddress, + address adminProxy, + address sequencerInbox, + address bridge ); function setUp() public { @@ -106,8 +111,10 @@ contract AssertinPoolTest is Test { rollupUserLogicImpl, address(0) ); - ExecutionState memory emptyState = - ExecutionState(GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), MachineStatus.FINISHED); + ExecutionState memory emptyState = ExecutionState( + GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), + MachineStatus.FINISHED + ); token = new TestWETH9("Test", "TEST"); IWETH9(address(token)).deposit{value: 21 ether}(); @@ -129,9 +136,9 @@ contract AssertinPoolTest is Test { genesisExecutionState: emptyState, genesisInboxCount: 0, miniStakeValue: MINI_STAKE_VALUE, - layerZeroBlockEdgeHeight: 2 ** 5, - layerZeroBigStepEdgeHeight: 2 ** 5, - layerZeroSmallStepEdgeHeight: 2 ** 5, + layerZeroBlockEdgeHeight: 2**5, + layerZeroBigStepEdgeHeight: 2**5, + layerZeroSmallStepEdgeHeight: 2**5, numBigStepLevel: 2, anyTrustFastConfirmer: address(300001), challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS @@ -139,7 +146,13 @@ contract AssertinPoolTest is Test { vm.expectEmit(false, false, false, false); emit RollupCreated(address(0), address(0), address(0), address(0), address(0)); - rollupAddr = rollupCreator.createRollup(config, address(0), new address[](0), false, MAX_DATA_SIZE); + rollupAddr = rollupCreator.createRollup( + config, + address(0), + new address[](0), + false, + MAX_DATA_SIZE + ); userRollup = RollupUserLogic(address(rollupAddr)); adminRollup = RollupAdminLogic(address(rollupAddr)); @@ -188,8 +201,9 @@ contract AssertinPoolTest is Test { afterState: afterState }); aspcreator = new AssertionStakingPoolCreator(); - pool = - AssertionStakingPool(aspcreator.createPoolForAssertion(address(rollupAddr), assertionInputs, assertionHash)); + pool = AssertionStakingPool( + aspcreator.createPoolForAssertion(address(rollupAddr), assertionInputs, assertionHash) + ); token.transfer(staker1, staker1Bal); token.transfer(staker2, staker2Bal); @@ -260,7 +274,11 @@ contract AssertinPoolTest is Test { vm.prank(staker2); pool.depositIntoPool(staker2Bal); - assertEq(token.balanceOf(address(pool)), staker1Bal + staker2Bal, "tokens depositted into pool"); + assertEq( + token.balanceOf(address(pool)), + staker1Bal + staker2Bal, + "tokens depositted into pool" + ); assertEq(token.balanceOf(address(staker1)), uint256(0), "tokens depositted into pool"); assertEq(token.balanceOf(address(staker2)), uint256(0), "tokens depositted into pool"); diff --git a/contracts/test/util/TestUtil.sol b/contracts/test/util/TestUtil.sol new file mode 100644 index 000000000..27b326586 --- /dev/null +++ b/contracts/test/util/TestUtil.sol @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 +pragma solidity ^0.8.4; + +import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; +import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; + +library TestUtil { + function deployProxy(address logic) public returns (address) { + ProxyAdmin pa = new ProxyAdmin(); + return address(new TransparentUpgradeableProxy(address(logic), address(pa), "")); + } +} From 19f71f16de626cb53ee4dc2682cb8743b88b8e32 Mon Sep 17 00:00:00 2001 From: Mahsa Moosavi Date: Fri, 22 Dec 2023 13:49:21 -0500 Subject: [PATCH 2/4] undo yarn format --- contracts/hardhat.config.ts | 13 +- contracts/scripts/boldUpgradeFunctions.ts | 8 +- contracts/scripts/common.ts | 2 +- contracts/scripts/files/localConfig.json | 4 +- .../scripts/files/localDeployedContracts.json | 3 +- contracts/scripts/prepareBoldUpgrade.ts | 6 +- contracts/scripts/testLocalPrepareTestNode.ts | 4 +- contracts/src/bridge/IOutbox.sol | 2 +- contracts/src/bridge/Inbox.sol | 1 + .../src/challenge/OldChallengeManager.sol | 16 +- .../src/challengeV2/EdgeChallengeManager.sol | 113 +- contracts/src/challengeV2/IAssertionChain.sol | 6 - .../challengeV2/libraries/ArrayUtilsLib.sol | 24 +- .../libraries/ChallengeEdgeLib.sol | 141 +- .../challengeV2/libraries/ChallengeErrors.sol | 6 +- .../libraries/EdgeChallengeManagerLib.sol | 230 +-- .../challengeV2/libraries/MerkleTreeLib.sol | 49 +- .../challengeV2/libraries/UintUtilsLib.sol | 4 +- contracts/src/mocks/BridgeStub.sol | 3 +- contracts/src/mocks/ExecutionManager.sol | 5 +- contracts/src/mocks/MerkleTreeAccess.sol | 40 +- .../src/mocks/SimpleOneStepProofEntry.sol | 8 +- contracts/src/osp/OneStepProofEntry.sol | 13 +- contracts/src/rollup/Assertion.sol | 9 +- contracts/src/rollup/BOLDUpgradeAction.sol | 129 +- contracts/src/rollup/IRollupAdmin.sol | 3 +- contracts/src/rollup/IRollupCore.sol | 17 +- contracts/src/rollup/IRollupLogic.sol | 3 +- contracts/src/rollup/RollupAdminLogic.sol | 19 +- contracts/src/rollup/RollupCore.sol | 88 +- contracts/src/rollup/RollupCreator.sol | 64 +- contracts/src/rollup/RollupLib.sol | 24 +- contracts/src/rollup/RollupProxy.sol | 6 +- contracts/src/rollup/RollupUserLogic.sol | 92 +- contracts/src/rollup/ValidatorWallet.sol | 4 +- contracts/test/ERC20Mock.sol | 2 +- contracts/test/MockAssertionChain.sol | 44 +- contracts/test/Rollup.t.sol | 292 +--- .../test/challengeV2/ArrayUtilsLib.t.sol | 4 +- .../test/challengeV2/ChallengeEdgeLib.t.sol | 211 +-- .../challengeV2/EdgeChallengeManager.t.sol | 1429 +++++------------ .../challengeV2/EdgeChallengeManagerLib.t.sol | 1242 ++++---------- .../test/challengeV2/MerkleTreeLib.t.sol | 106 +- contracts/test/challengeV2/StateTools.sol | 10 +- contracts/test/challengeV2/UintUtilsLib.t.sol | 10 +- contracts/test/challengeV2/Utils.sol | 24 +- .../test/contract/common/challengeLib.ts | 5 +- .../stakingPool/AssertionStakingPool.t.sol | 48 +- contracts/test/util/TestUtil.sol | 12 - 49 files changed, 1193 insertions(+), 3405 deletions(-) delete mode 100644 contracts/test/util/TestUtil.sol diff --git a/contracts/hardhat.config.ts b/contracts/hardhat.config.ts index 9b7af4ce7..bd88f9580 100644 --- a/contracts/hardhat.config.ts +++ b/contracts/hardhat.config.ts @@ -18,15 +18,6 @@ const solidity = { }, }, }, - { - version: '0.8.0', - settings: { - optimizer: { - enabled: true, - runs: 2000, - }, - }, - }, ], overrides: { 'src/challengeV2/EdgeChallengeManager.sol': { @@ -185,6 +176,6 @@ module.exports = { target: 'ethers-v5', }, contractSizer: { - strict: process.env.STRICT ? true : false, - }, + strict: process.env.STRICT ? true : false + } } diff --git a/contracts/scripts/boldUpgradeFunctions.ts b/contracts/scripts/boldUpgradeFunctions.ts index a464aa4fe..53dcf67df 100644 --- a/contracts/scripts/boldUpgradeFunctions.ts +++ b/contracts/scripts/boldUpgradeFunctions.ts @@ -27,7 +27,7 @@ import { export const deployDependencies = async ( signer: Signer, maxDataSize: number, - log: boolean = false + log: boolean = false, ): Promise< Omit > => { @@ -147,11 +147,7 @@ export const deployBoldUpgrade = async ( config: Config, log: boolean = false ): Promise => { - const deployed = await deployDependencies( - wallet, - config.settings.maxDataSize, - log - ) + const deployed = await deployDependencies(wallet, config.settings.maxDataSize, log) const fac = new BOLDUpgradeAction__factory(wallet) const boldUpgradeAction = await fac.deploy( diff --git a/contracts/scripts/common.ts b/contracts/scripts/common.ts index 1985df1f5..bc2a83289 100644 --- a/contracts/scripts/common.ts +++ b/contracts/scripts/common.ts @@ -51,7 +51,7 @@ export interface Config { seqInbox: string } settings: { - challengeGracePeriodBlocks: number + challengeGracePeriodBlocks: number, confirmPeriodBlocks: number challengePeriodBlocks: number stakeToken: string diff --git a/contracts/scripts/files/localConfig.json b/contracts/scripts/files/localConfig.json index 29691b719..b9eab041e 100644 --- a/contracts/scripts/files/localConfig.json +++ b/contracts/scripts/files/localConfig.json @@ -30,5 +30,7 @@ "numBigStepLevel": 4, "maxDataSize": 117964 }, - "validators": ["0xf10EF80c6eF4930A62C5F9661c91339Df4dBB173"] + "validators": [ + "0xf10EF80c6eF4930A62C5F9661c91339Df4dBB173" + ] } diff --git a/contracts/scripts/files/localDeployedContracts.json b/contracts/scripts/files/localDeployedContracts.json index 0967ef424..7a73a41bf 100644 --- a/contracts/scripts/files/localDeployedContracts.json +++ b/contracts/scripts/files/localDeployedContracts.json @@ -1 +1,2 @@ -{} +{ +} \ No newline at end of file diff --git a/contracts/scripts/prepareBoldUpgrade.ts b/contracts/scripts/prepareBoldUpgrade.ts index b8aa96386..51171d63d 100644 --- a/contracts/scripts/prepareBoldUpgrade.ts +++ b/contracts/scripts/prepareBoldUpgrade.ts @@ -1,6 +1,10 @@ import { ethers, Wallet } from 'ethers' import fs from 'fs' -import { DeployedContracts, getConfig, getJsonFile } from './common' +import { + DeployedContracts, + getConfig, + getJsonFile, +} from './common' import { deployBoldUpgrade } from './boldUpgradeFunctions' import dotenv from 'dotenv' diff --git a/contracts/scripts/testLocalPrepareTestNode.ts b/contracts/scripts/testLocalPrepareTestNode.ts index 2660cc664..16c4d6109 100644 --- a/contracts/scripts/testLocalPrepareTestNode.ts +++ b/contracts/scripts/testLocalPrepareTestNode.ts @@ -23,7 +23,7 @@ dotenv.config() const transferToUpgradeExec = async ( rollupAdmin: Wallet, - rollupAddress: string + rollupAddress: string, ) => { const upgradeExecutorImpl = await new ContractFactory( UpgradeExecutorAbi, @@ -32,7 +32,7 @@ const transferToUpgradeExec = async ( ).deploy() await upgradeExecutorImpl.deployed() - const proxyAdminAddress = '0xa4884de60AEef09b1b35fa255F56ee37198A80B3' + const proxyAdminAddress = "0xa4884de60AEef09b1b35fa255F56ee37198A80B3" const upExecProxy = await new TransparentUpgradeableProxy__factory( rollupAdmin diff --git a/contracts/src/bridge/IOutbox.sol b/contracts/src/bridge/IOutbox.sol index 5565122d4..1a748401c 100644 --- a/contracts/src/bridge/IOutbox.sol +++ b/contracts/src/bridge/IOutbox.sol @@ -28,7 +28,7 @@ interface IOutbox { function OUTBOX_VERSION() external view returns (uint128); // the outbox version function updateSendRoot(bytes32 sendRoot, bytes32 l2BlockHash) external; - + function updateRollupAddress() external; /// @notice When l2ToL1Sender returns a nonzero address, the message was originated by an L2 account diff --git a/contracts/src/bridge/Inbox.sol b/contracts/src/bridge/Inbox.sol index 0ee7f1055..e39196b24 100644 --- a/contracts/src/bridge/Inbox.sol +++ b/contracts/src/bridge/Inbox.sol @@ -531,6 +531,7 @@ contract Inbox is DelegateCallAware, PausableUpgradeable, IInbox { ); } + function _deliverMessage( uint8 _kind, address _sender, diff --git a/contracts/src/challenge/OldChallengeManager.sol b/contracts/src/challenge/OldChallengeManager.sol index f66d413e6..585ccecc4 100644 --- a/contracts/src/challenge/OldChallengeManager.sol +++ b/contracts/src/challenge/OldChallengeManager.sol @@ -59,10 +59,7 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { } else if (expectedMode == ChallengeModeRequirement.BLOCK) { require(challenge.mode == OldChallengeLib.ChallengeMode.BLOCK, "CHAL_NOT_BLOCK"); } else if (expectedMode == ChallengeModeRequirement.EXECUTION) { - require( - challenge.mode == OldChallengeLib.ChallengeMode.EXECUTION, - "CHAL_NOT_EXECUTION" - ); + require(challenge.mode == OldChallengeLib.ChallengeMode.EXECUTION, "CHAL_NOT_EXECUTION"); } else { assert(false); } @@ -149,10 +146,7 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { maxInboxMessagesRead++; } challenge.maxInboxMessages = maxInboxMessagesRead; - challenge.next = OldChallengeLib.Participant({ - addr: asserter_, - timeLeft: asserterTimeLeft_ - }); + challenge.next = OldChallengeLib.Participant({addr: asserter_, timeLeft: asserterTimeLeft_}); challenge.current = OldChallengeLib.Participant({ addr: challenger_, timeLeft: challengerTimeLeft_ @@ -260,11 +254,7 @@ contract OldChallengeManager is DelegateCallAware, IOldChallengeManager { } bytes32 afterHash = osp.proveOneStep( - ExecutionContext({ - maxInboxMessagesRead: challenge.maxInboxMessages, - bridge: bridge, - initialWasmModuleRoot: challenge.wasmModuleRoot - }), + ExecutionContext({maxInboxMessagesRead: challenge.maxInboxMessages, bridge: bridge, initialWasmModuleRoot: challenge.wasmModuleRoot}), challengeStart, selection.oldSegments[selection.challengePosition], proof diff --git a/contracts/src/challengeV2/EdgeChallengeManager.sol b/contracts/src/challengeV2/EdgeChallengeManager.sol index 571a66c0a..3059bd3bf 100644 --- a/contracts/src/challengeV2/EdgeChallengeManager.sol +++ b/contracts/src/challengeV2/EdgeChallengeManager.sol @@ -65,11 +65,9 @@ interface IEdgeChallengeManager { /// @param prefixProof A proof to show that the bisectionHistoryRoot commits to a prefix of the current endHistoryRoot /// @return lowerChildId The id of the newly created lower child edge /// @return upperChildId The id of the newly created upper child edge - function bisectEdge( - bytes32 edgeId, - bytes32 bisectionHistoryRoot, - bytes calldata prefixProof - ) external returns (bytes32, bytes32); + function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes calldata prefixProof) + external + returns (bytes32, bytes32); /// @notice Confirm an edge if both its children are already confirmed function confirmEdgeByChildren(bytes32 edgeId) external; @@ -227,10 +225,7 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param upperChildId The id of the upper child created during bisection /// @param lowerChildAlreadyExists When an edge is bisected the lower child may already exist - created by a rival. event EdgeBisected( - bytes32 indexed edgeId, - bytes32 indexed lowerChildId, - bytes32 indexed upperChildId, - bool lowerChildAlreadyExists + bytes32 indexed edgeId, bytes32 indexed lowerChildId, bytes32 indexed upperChildId, bool lowerChildAlreadyExists ); /// @notice An edge can be confirmed if both of its children were already confirmed. @@ -242,21 +237,13 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param edgeId The edge that was confirmed /// @param mutualId The mutual id of the confirmed edge /// @param totalTimeUnrivaled The cumulative amount of time (in blocks) this edge spent unrivaled - event EdgeConfirmedByTime( - bytes32 indexed edgeId, - bytes32 indexed mutualId, - uint64 totalTimeUnrivaled - ); + event EdgeConfirmedByTime(bytes32 indexed edgeId, bytes32 indexed mutualId, uint64 totalTimeUnrivaled); /// @notice An edge can be confirmed if a zero layer edge in the level below claims this edge /// @param edgeId The edge that was confirmed /// @param mutualId The mutual id of the confirmed edge /// @param claimingEdgeId The id of the zero layer edge that claimed this edge - event EdgeConfirmedByClaim( - bytes32 indexed edgeId, - bytes32 indexed mutualId, - bytes32 claimingEdgeId - ); + event EdgeConfirmedByClaim(bytes32 indexed edgeId, bytes32 indexed mutualId, bytes32 claimingEdgeId); /// @notice A SmallStep edge of length 1 can be confirmed via a one step proof /// @param edgeId The edge that was confirmed @@ -268,12 +255,7 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { /// @param mutualId The mutual id of the confirmed edge /// @param stakeToken The ERC20 being refunded /// @param stakeAmount The amount of tokens being refunded - event EdgeRefunded( - bytes32 indexed edgeId, - bytes32 indexed mutualId, - address stakeToken, - uint256 stakeAmount - ); + event EdgeRefunded(bytes32 indexed edgeId, bytes32 indexed mutualId, address stakeToken, uint256 stakeAmount); /// @dev Store for all edges and rival data /// All edges, including edges from different challenges, are stored together in the same store @@ -391,17 +373,11 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { if (args.proof.length == 0) { revert EmptyEdgeSpecificProof(); } - ( - , - ExecutionStateData memory predecessorStateData, - ExecutionStateData memory claimStateData - ) = abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); + (, ExecutionStateData memory predecessorStateData, ExecutionStateData memory claimStateData) = + abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); assertionChain.validateAssertionHash( - args.claimId, - claimStateData.executionState, - claimStateData.prevAssertionHash, - claimStateData.inboxAcc + args.claimId, claimStateData.executionState, claimStateData.prevAssertionHash, claimStateData.inboxAcc ); assertionChain.validateAssertionHash( @@ -420,21 +396,9 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { claimStateData.executionState ); - edgeAdded = store.createLayerZeroEdge( - args, - ard, - oneStepProofEntry, - expectedEndHeight, - NUM_BIGSTEP_LEVEL - ); + edgeAdded = store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, NUM_BIGSTEP_LEVEL); } else { - edgeAdded = store.createLayerZeroEdge( - args, - ard, - oneStepProofEntry, - expectedEndHeight, - NUM_BIGSTEP_LEVEL - ); + edgeAdded = store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, NUM_BIGSTEP_LEVEL); } IERC20 st = stakeToken; @@ -467,16 +431,12 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { } /// @inheritdoc IEdgeChallengeManager - function bisectEdge( - bytes32 edgeId, - bytes32 bisectionHistoryRoot, - bytes calldata prefixProof - ) external returns (bytes32, bytes32) { - ( - bytes32 lowerChildId, - EdgeAddedData memory lowerChildAdded, - EdgeAddedData memory upperChildAdded - ) = store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); + function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes calldata prefixProof) + external + returns (bytes32, bytes32) + { + (bytes32 lowerChildId, EdgeAddedData memory lowerChildAdded, EdgeAddedData memory upperChildAdded) = + store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); bool lowerChildAlreadyExists = lowerChildAdded.edgeId == 0; // the lower child might already exist, if it didnt then a new @@ -531,9 +491,7 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { ExecutionStateData calldata claimStateData ) public { // if there are no ancestors provided, then the top edge is the edge we're confirming itself - bytes32 lastEdgeId = ancestorEdges.length > 0 - ? ancestorEdges[ancestorEdges.length - 1] - : edgeId; + bytes32 lastEdgeId = ancestorEdges.length > 0 ? ancestorEdges[ancestorEdges.length - 1] : edgeId; ChallengeEdge storage topEdge = store.get(lastEdgeId); EdgeType topLevelType = ChallengeEdgeLib.levelToType(topEdge.level, NUM_BIGSTEP_LEVEL); @@ -556,22 +514,16 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { claimStateData.prevAssertionHash, claimStateData.inboxAcc ); - assertionBlocks = - assertionChain.getSecondChildCreationBlock(claimStateData.prevAssertionHash) - - assertionChain.getFirstChildCreationBlock(claimStateData.prevAssertionHash); + assertionBlocks = assertionChain.getSecondChildCreationBlock(claimStateData.prevAssertionHash) + - assertionChain.getFirstChildCreationBlock(claimStateData.prevAssertionHash); } else { // if the assertion being claimed is not the first child, then it had siblings from the moment // it was created, so it has no time unrivaled assertionBlocks = 0; } - uint64 totalTimeUnrivaled = store.confirmEdgeByTime( - edgeId, - ancestorEdges, - assertionBlocks, - challengePeriodBlocks, - NUM_BIGSTEP_LEVEL - ); + uint64 totalTimeUnrivaled = + store.confirmEdgeByTime(edgeId, ancestorEdges, assertionBlocks, challengePeriodBlocks, NUM_BIGSTEP_LEVEL); emit EdgeConfirmedByTime(edgeId, store.edges[edgeId].mutualId(), totalTimeUnrivaled); } @@ -649,15 +601,7 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { uint256 endHeight, bytes32 endHistoryRoot ) public pure returns (bytes32) { - return - ChallengeEdgeLib.idComponent( - level, - originId, - startHeight, - startHistoryRoot, - endHeight, - endHistoryRoot - ); + return ChallengeEdgeLib.idComponent(level, originId, startHeight, startHistoryRoot, endHeight, endHistoryRoot); } /// @inheritdoc IEdgeChallengeManager @@ -668,14 +612,7 @@ contract EdgeChallengeManager is IEdgeChallengeManager, Initializable { bytes32 startHistoryRoot, uint256 endHeight ) public pure returns (bytes32) { - return - ChallengeEdgeLib.mutualIdComponent( - level, - originId, - startHeight, - startHistoryRoot, - endHeight - ); + return ChallengeEdgeLib.mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight); } /// @inheritdoc IEdgeChallengeManager diff --git a/contracts/src/challengeV2/IAssertionChain.sol b/contracts/src/challengeV2/IAssertionChain.sol index 4050f56c3..3420e22a9 100644 --- a/contracts/src/challengeV2/IAssertionChain.sol +++ b/contracts/src/challengeV2/IAssertionChain.sol @@ -12,21 +12,15 @@ import "../rollup/Assertion.sol"; /// @notice The interface required by the EdgeChallengeManager for requesting assertion data from the AssertionChain interface IAssertionChain { function bridge() external view returns (IBridge); - function validateAssertionHash( bytes32 assertionHash, ExecutionState calldata state, bytes32 prevAssertionHash, bytes32 inboxAcc ) external view; - function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view; - function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64); - function getSecondChildCreationBlock(bytes32 assertionHash) external view returns (uint64); - function isFirstChild(bytes32 assertionHash) external view returns (bool); - function isPending(bytes32 assertionHash) external view returns (bool); } diff --git a/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol b/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol index 25e3d52bf..957fe75b7 100644 --- a/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol +++ b/contracts/src/challengeV2/libraries/ArrayUtilsLib.sol @@ -10,11 +10,7 @@ library ArrayUtilsLib { /// @notice Append an item to the end of an array /// @param arr The array to append to /// @param newItem The item to append - function append(bytes32[] memory arr, bytes32 newItem) - internal - pure - returns (bytes32[] memory) - { + function append(bytes32[] memory arr, bytes32 newItem) internal pure returns (bytes32[] memory) { bytes32[] memory clone = new bytes32[](arr.length + 1); for (uint256 i = 0; i < arr.length; i++) { clone[i] = arr[i]; @@ -28,11 +24,11 @@ library ArrayUtilsLib { /// @param arr Array to slice /// @param startIndex The start index of the slice in the original array - inclusive /// @param endIndex The end index of the slice in the original array - exlusive - function slice( - bytes32[] memory arr, - uint256 startIndex, - uint256 endIndex - ) internal pure returns (bytes32[] memory) { + function slice(bytes32[] memory arr, uint256 startIndex, uint256 endIndex) + internal + pure + returns (bytes32[] memory) + { require(startIndex < endIndex, "Start not less than end"); require(endIndex <= arr.length, "End not less or equal than length"); @@ -46,11 +42,7 @@ library ArrayUtilsLib { /// @notice Concatenated to arrays /// @param arr1 First array /// @param arr1 Second array - function concat(bytes32[] memory arr1, bytes32[] memory arr2) - internal - pure - returns (bytes32[] memory) - { + function concat(bytes32[] memory arr1, bytes32[] memory arr2) internal pure returns (bytes32[] memory) { bytes32[] memory full = new bytes32[](arr1.length + arr2.length); for (uint256 i = 0; i < arr1.length; i++) { full[i] = arr1[i]; @@ -60,4 +52,4 @@ library ArrayUtilsLib { } return full; } -} +} \ No newline at end of file diff --git a/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol b/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol index f8d142073..42e8e26aa 100644 --- a/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol +++ b/contracts/src/challengeV2/libraries/ChallengeEdgeLib.sol @@ -107,23 +107,22 @@ library ChallengeEdgeLib { newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); - return - ChallengeEdge({ - originId: originId, - startHeight: startHeight, - startHistoryRoot: startHistoryRoot, - endHeight: endHeight, - endHistoryRoot: endHistoryRoot, - lowerChildId: 0, - upperChildId: 0, - createdAtBlock: uint64(block.number), - claimId: claimId, - staker: staker, - status: EdgeStatus.Pending, - level: level, - refunded: false, - confirmedAtBlock: 0 - }); + return ChallengeEdge({ + originId: originId, + startHeight: startHeight, + startHistoryRoot: startHistoryRoot, + endHeight: endHeight, + endHistoryRoot: endHistoryRoot, + lowerChildId: 0, + upperChildId: 0, + createdAtBlock: uint64(block.number), + claimId: claimId, + staker: staker, + status: EdgeStatus.Pending, + level: level, + refunded: false, + confirmedAtBlock: 0 + }); } /// @notice Creates a new child edge. All edges except layer zero edges are child edges. @@ -138,23 +137,22 @@ library ChallengeEdgeLib { ) internal view returns (ChallengeEdge memory) { newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); - return - ChallengeEdge({ - originId: originId, - startHeight: startHeight, - startHistoryRoot: startHistoryRoot, - endHeight: endHeight, - endHistoryRoot: endHistoryRoot, - lowerChildId: 0, - upperChildId: 0, - createdAtBlock: uint64(block.number), - claimId: 0, - staker: address(0), - status: EdgeStatus.Pending, - level: level, - refunded: false, - confirmedAtBlock: 0 - }); + return ChallengeEdge({ + originId: originId, + startHeight: startHeight, + startHistoryRoot: startHistoryRoot, + endHeight: endHeight, + endHistoryRoot: endHistoryRoot, + lowerChildId: 0, + upperChildId: 0, + createdAtBlock: uint64(block.number), + claimId: 0, + staker: address(0), + status: EdgeStatus.Pending, + level: level, + refunded: false, + confirmedAtBlock: 0 + }); } /// @notice The "mutualId" of an edge. A mutual id is a hash of all the data that is shared by rivals. @@ -168,8 +166,7 @@ library ChallengeEdgeLib { bytes32 startHistoryRoot, uint256 endHeight ) internal pure returns (bytes32) { - return - keccak256(abi.encodePacked(level, originId, startHeight, startHistoryRoot, endHeight)); + return keccak256(abi.encodePacked(level, originId, startHeight, startHistoryRoot, endHeight)); } /// @notice The "mutualId" of an edge. A mutual id is a hash of all the data that is shared by rivals. @@ -177,25 +174,11 @@ library ChallengeEdgeLib { /// The difference between rivals is that they have a different endHistoryRoot, so that information /// is not included in this hash. function mutualId(ChallengeEdge storage ce) internal view returns (bytes32) { - return - mutualIdComponent( - ce.level, - ce.originId, - ce.startHeight, - ce.startHistoryRoot, - ce.endHeight - ); + return mutualIdComponent(ce.level, ce.originId, ce.startHeight, ce.startHistoryRoot, ce.endHeight); } function mutualIdMem(ChallengeEdge memory ce) internal pure returns (bytes32) { - return - mutualIdComponent( - ce.level, - ce.originId, - ce.startHeight, - ce.startHistoryRoot, - ce.endHeight - ); + return mutualIdComponent(ce.level, ce.originId, ce.startHeight, ce.startHistoryRoot, ce.endHeight); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information @@ -207,13 +190,11 @@ library ChallengeEdgeLib { uint256 endHeight, bytes32 endHistoryRoot ) internal pure returns (bytes32) { - return - keccak256( - abi.encodePacked( - mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight), - endHistoryRoot - ) - ); + return keccak256( + abi.encodePacked( + mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight), endHistoryRoot + ) + ); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information @@ -221,28 +202,16 @@ library ChallengeEdgeLib { /// possible to pass a storage edge to this method and the id be computed correctly, but that would load /// the whole struct into memory, so we're explicit here that this should be used for edges already in memory. function idMem(ChallengeEdge memory edge) internal pure returns (bytes32) { - return - idComponent( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight, - edge.endHistoryRoot - ); + return idComponent( + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot + ); } /// @notice The id of an edge. Edges are uniquely identified by their id, and commit to the same information function id(ChallengeEdge storage edge) internal view returns (bytes32) { - return - idComponent( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight, - edge.endHistoryRoot - ); + return idComponent( + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot + ); } /// @notice Does this edge exist in storage @@ -263,17 +232,9 @@ library ChallengeEdgeLib { /// @notice Set the children of an edge /// @dev Children can only be set once - function setChildren( - ChallengeEdge storage edge, - bytes32 lowerChildId, - bytes32 upperChildId - ) internal { + function setChildren(ChallengeEdge storage edge, bytes32 lowerChildId, bytes32 upperChildId) internal { if (edge.lowerChildId != 0 || edge.upperChildId != 0) { - revert ChildrenAlreadySet( - ChallengeEdgeLib.id(edge), - edge.lowerChildId, - edge.upperChildId - ); + revert ChildrenAlreadySet(ChallengeEdgeLib.id(edge), edge.lowerChildId, edge.upperChildId); } edge.lowerChildId = lowerChildId; edge.upperChildId = upperChildId; @@ -311,11 +272,7 @@ library ChallengeEdgeLib { } /// @notice Returns the edge type for a given level, given the total number of big step levels - function levelToType(uint8 level, uint8 numBigStepLevels) - internal - pure - returns (EdgeType eType) - { + function levelToType(uint8 level, uint8 numBigStepLevels) internal pure returns (EdgeType eType) { if (level == 0) { return EdgeType.Block; } else if (level <= numBigStepLevels) { diff --git a/contracts/src/challengeV2/libraries/ChallengeErrors.sol b/contracts/src/challengeV2/libraries/ChallengeErrors.sol index f46cac572..d8c7dd565 100644 --- a/contracts/src/challengeV2/libraries/ChallengeErrors.sol +++ b/contracts/src/challengeV2/libraries/ChallengeErrors.sol @@ -58,11 +58,7 @@ error EdgeClaimMismatch(bytes32 edgeId, bytes32 claimingEdgeId); error OriginIdMutualIdMismatch(bytes32 mutualId, bytes32 originId); /// @dev The edge does not have a valid ancestor link error EdgeNotAncestor( - bytes32 edgeId, - bytes32 lowerChildId, - bytes32 upperChildId, - bytes32 ancestorEdgeId, - bytes32 claimId + bytes32 edgeId, bytes32 lowerChildId, bytes32 upperChildId, bytes32 ancestorEdgeId, bytes32 claimId ); /// @dev The total number of blocks is not above the threshold error InsufficientConfirmationBlocks(uint256 totalBlocks, uint256 thresholdBlocks); diff --git a/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol b/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol index 8afe99236..0d3526858 100644 --- a/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol +++ b/contracts/src/challengeV2/libraries/EdgeChallengeManagerLib.sol @@ -134,11 +134,7 @@ library EdgeChallengeManagerLib { /// @dev Throws if the edge does not exist in the store /// @param store The edge store to fetch an id from /// @param edgeId The id of the edge to fetch - function get(EdgeStore storage store, bytes32 edgeId) - internal - view - returns (ChallengeEdge storage) - { + function get(EdgeStore storage store, bytes32 edgeId) internal view returns (ChallengeEdge storage) { if (!store.edges[edgeId].exists()) { revert EdgeNotExists(edgeId); } @@ -149,11 +145,7 @@ library EdgeChallengeManagerLib { /// @dev Useful where you already know the edge exists in the store - avoid a storage lookup /// @param store The edge store to fetch an id from /// @param edgeId The id of the edge to fetch - function getNoCheck(EdgeStore storage store, bytes32 edgeId) - internal - view - returns (ChallengeEdge storage) - { + function getNoCheck(EdgeStore storage store, bytes32 edgeId) internal view returns (ChallengeEdge storage) { return store.edges[edgeId]; } @@ -161,10 +153,7 @@ library EdgeChallengeManagerLib { /// @dev Updates first rival info for later use in calculating time unrivaled /// @param store The store to add the edge to /// @param edge The edge to add - function add(EdgeStore storage store, ChallengeEdge memory edge) - internal - returns (EdgeAddedData memory) - { + function add(EdgeStore storage store, ChallengeEdge memory edge) internal returns (EdgeAddedData memory) { bytes32 eId = edge.idMem(); // add the edge if it doesnt exist already if (store.edges[eId].exists()) { @@ -177,11 +166,7 @@ library EdgeChallengeManagerLib { // the new edge is a rival. This will later allow us to calculate time an edge // stayed unrivaled bytes32 mutualId = ChallengeEdgeLib.mutualIdComponent( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight ); bytes32 firstRival = store.firstRivals[mutualId]; @@ -199,17 +184,16 @@ library EdgeChallengeManagerLib { // other rival edges - they will all have a zero time unrivaled } - return - EdgeAddedData( - eId, - mutualId, - edge.originId, - edge.claimId, - store.edges[eId].length(), - edge.level, - firstRival != 0, - edge.claimId != 0 - ); + return EdgeAddedData( + eId, + mutualId, + edge.originId, + edge.claimId, + store.edges[eId].length(), + edge.level, + firstRival != 0, + edge.claimId != 0 + ); } /// @notice Conduct checks that are specific to the edge type. @@ -260,10 +244,8 @@ library EdgeChallengeManagerLib { if (args.proof.length == 0) { revert EmptyEdgeSpecificProof(); } - (bytes32[] memory inclusionProof, , ) = abi.decode( - args.proof, - (bytes32[], ExecutionStateData, ExecutionStateData) - ); + (bytes32[] memory inclusionProof,,) = + abi.decode(args.proof, (bytes32[], ExecutionStateData, ExecutionStateData)); // check the start and end execution states exist, the block hash entry should be non zero if (ard.startState.machineStatus == MachineStatus.RUNNING) { @@ -320,10 +302,7 @@ library EdgeChallengeManagerLib { // this guarantees that the edge we're creating is a 'continuation' of the claim edge, it is // a commitment to the states that between start and end states of the claim MerkleTreeLib.verifyInclusionProof( - claimEdge.startHistoryRoot, - startState, - claimEdge.startHeight, - claimStartInclusionProof + claimEdge.startHistoryRoot, startState, claimEdge.startHeight, claimStartInclusionProof ); // it's doubly important to check the end state since if the end state since the claim id is @@ -333,10 +312,7 @@ library EdgeChallengeManagerLib { // that the end history root of the new edge will be different for different claim ids, and therefore // the edge ids will be different MerkleTreeLib.verifyInclusionProof( - claimEdge.endHistoryRoot, - endState, - claimEdge.endHeight, - claimEndInclusionProof + claimEdge.endHistoryRoot, endState, claimEdge.endHeight, claimEndInclusionProof ); return (ProofData(startState, endState, edgeInclusionProof), originId); @@ -361,16 +337,14 @@ library EdgeChallengeManagerLib { /// @param proofData Data extracted from supplied proof /// @param args The edge creation args /// @param expectedEndHeight Edges have a deterministic end height dependent on their level - function layerZeroCommonChecks( - ProofData memory proofData, - CreateEdgeArgs calldata args, - uint256 expectedEndHeight - ) private pure returns (bytes32) { + function layerZeroCommonChecks(ProofData memory proofData, CreateEdgeArgs calldata args, uint256 expectedEndHeight) + private + pure + returns (bytes32) + { // since zero layer edges have a start height of zero, we know that they are a size // one tree containing only the start state. We can then compute the history root directly - bytes32 startHistoryRoot = MerkleTreeLib.root( - MerkleTreeLib.appendLeaf(new bytes32[](0), proofData.startState) - ); + bytes32 startHistoryRoot = MerkleTreeLib.root(MerkleTreeLib.appendLeaf(new bytes32[](0), proofData.startState)); // all end heights are expected to be a power of 2, the specific power is defined by the // edge challenge manager itself @@ -391,10 +365,7 @@ library EdgeChallengeManagerLib { // This ensures continuity of states between levels - the state is present in both this // level and the one below MerkleTreeLib.verifyInclusionProof( - args.endHistoryRoot, - proofData.endState, - args.endHeight, - proofData.inclusionProof + args.endHistoryRoot, proofData.endState, args.endHeight, proofData.inclusionProof ); // start root must always be a prefix of end root, we ensure that @@ -403,39 +374,24 @@ library EdgeChallengeManagerLib { if (args.prefixProof.length == 0) { revert EmptyPrefixProof(); } - (bytes32[] memory preExpansion, bytes32[] memory preProof) = abi.decode( - args.prefixProof, - (bytes32[], bytes32[]) - ); + (bytes32[] memory preExpansion, bytes32[] memory preProof) = + abi.decode(args.prefixProof, (bytes32[], bytes32[])); MerkleTreeLib.verifyPrefixProof( - startHistoryRoot, - 1, - args.endHistoryRoot, - args.endHeight + 1, - preExpansion, - preProof + startHistoryRoot, 1, args.endHistoryRoot, args.endHeight + 1, preExpansion, preProof ); return (startHistoryRoot); } /// @notice Creates a new layer zero edges from edge creation args - function toLayerZeroEdge( - bytes32 originId, - bytes32 startHistoryRoot, - CreateEdgeArgs calldata args - ) private view returns (ChallengeEdge memory) { - return - ChallengeEdgeLib.newLayerZeroEdge( - originId, - startHistoryRoot, - 0, - args.endHistoryRoot, - args.endHeight, - args.claimId, - msg.sender, - args.level - ); + function toLayerZeroEdge(bytes32 originId, bytes32 startHistoryRoot, CreateEdgeArgs calldata args) + private + view + returns (ChallengeEdge memory) + { + return ChallengeEdgeLib.newLayerZeroEdge( + originId, startHistoryRoot, 0, args.endHistoryRoot, args.endHeight, args.claimId, msg.sender, args.level + ); } /// @notice Performs necessary checks and creates a new layer zero edge @@ -457,15 +413,10 @@ library EdgeChallengeManagerLib { uint8 numBigStepLevel ) internal returns (EdgeAddedData memory) { // each edge type requires some specific checks - (ProofData memory proofData, bytes32 originId) = layerZeroTypeSpecificChecks( - store, - args, - ard, - oneStepProofEntry, - numBigStepLevel - ); + (ProofData memory proofData, bytes32 originId) = + layerZeroTypeSpecificChecks(store, args, ard, oneStepProofEntry, numBigStepLevel); // all edge types share some common checks - bytes32 startHistoryRoot = layerZeroCommonChecks(proofData, args, expectedEndHeight); + (bytes32 startHistoryRoot) = layerZeroCommonChecks(proofData, args, expectedEndHeight); // we only wrap the struct creation in a function as doing so with exceeds the stack limit ChallengeEdge memory ce = toLayerZeroEdge(originId, startHistoryRoot, args); return add(store, ce); @@ -473,11 +424,7 @@ library EdgeChallengeManagerLib { /// @notice From any given edge, get the id of the previous assertion /// @param edgeId The edge to get the prev assertion hash - function getPrevAssertionHash(EdgeStore storage store, bytes32 edgeId) - internal - view - returns (bytes32) - { + function getPrevAssertionHash(EdgeStore storage store, bytes32 edgeId) internal view returns (bytes32) { ChallengeEdge storage edge = get(store, edgeId); while (edge.level > 0) { // the origin id gives us a link to the lower level @@ -517,11 +464,7 @@ library EdgeChallengeManagerLib { /// @notice Is the edge a single step in length, and does it have at least one rival. /// @param store The edge store containing the edge /// @param edgeId The edge id to test for single step and rivaled - function hasLengthOneRival(EdgeStore storage store, bytes32 edgeId) - internal - view - returns (bool) - { + function hasLengthOneRival(EdgeStore storage store, bytes32 edgeId) internal view returns (bool) { // must be length 1 and have rivals - all rivals have the same length return (hasRival(store, edgeId) && store.edges[edgeId].length() == 1); } @@ -597,18 +540,9 @@ library EdgeChallengeManagerLib { /// @return lowerChildId The id of the newly created lower child edge /// @return lowerChildAdded Data about the lower child edge, empty if the lower child already existed /// @return upperChildAdded Data about the upper child edge, never empty - function bisectEdge( - EdgeStore storage store, - bytes32 edgeId, - bytes32 bisectionHistoryRoot, - bytes memory prefixProof - ) + function bisectEdge(EdgeStore storage store, bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes memory prefixProof) internal - returns ( - bytes32, - EdgeAddedData memory, - EdgeAddedData memory - ) + returns (bytes32, EdgeAddedData memory, EdgeAddedData memory) { if (store.edges[edgeId].status != EdgeStatus.Pending) { revert EdgeNotPending(edgeId, store.edges[edgeId].status); @@ -625,17 +559,9 @@ library EdgeChallengeManagerLib { // rival edges bisect at the same height, and create the same child if they agree uint256 middleHeight = mandatoryBisectionHeight(ce.startHeight, ce.endHeight); { - (bytes32[] memory preExpansion, bytes32[] memory proof) = abi.decode( - prefixProof, - (bytes32[], bytes32[]) - ); + (bytes32[] memory preExpansion, bytes32[] memory proof) = abi.decode(prefixProof, (bytes32[], bytes32[])); MerkleTreeLib.verifyPrefixProof( - bisectionHistoryRoot, - middleHeight + 1, - ce.endHistoryRoot, - ce.endHeight + 1, - preExpansion, - proof + bisectionHistoryRoot, middleHeight + 1, ce.endHistoryRoot, ce.endHeight + 1, preExpansion, proof ); } @@ -644,12 +570,7 @@ library EdgeChallengeManagerLib { { // midpoint proof it valid, create and store the children ChallengeEdge memory lowerChild = ChallengeEdgeLib.newChildEdge( - ce.originId, - ce.startHistoryRoot, - ce.startHeight, - bisectionHistoryRoot, - middleHeight, - ce.level + ce.originId, ce.startHistoryRoot, ce.startHeight, bisectionHistoryRoot, middleHeight, ce.level ); lowerChildId = lowerChild.idMem(); // it's possible that the store already has the lower child if it was created by a rival @@ -662,12 +583,7 @@ library EdgeChallengeManagerLib { EdgeAddedData memory upperChildAdded; { ChallengeEdge memory upperChild = ChallengeEdgeLib.newChildEdge( - ce.originId, - bisectionHistoryRoot, - middleHeight, - ce.endHistoryRoot, - ce.endHeight, - ce.level + ce.originId, bisectionHistoryRoot, middleHeight, ce.endHistoryRoot, ce.endHeight, ce.level ); // add checks existence and throws if the id already exists @@ -740,28 +656,20 @@ library EdgeChallengeManagerLib { /// @param edgeId The edge being claimed /// @param claimingEdgeId The edge with a claim id equal to edge id /// @param numBigStepLevel The number of big step levels in this challenge - function checkClaimIdLink( - EdgeStore storage store, - bytes32 edgeId, - bytes32 claimingEdgeId, - uint8 numBigStepLevel - ) private view { + function checkClaimIdLink(EdgeStore storage store, bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) + private + view + { // we do some extra checks that edge being claimed is eligible to be claimed by the claiming edge // these shouldn't be necessary since it should be impossible to add layer zero edges that do not // satisfy the checks below, but we conduct these checks anyway for double safety // the origin id of an edge should be the mutual id of the edge in the level below if (store.edges[edgeId].mutualId() != store.edges[claimingEdgeId].originId) { - revert OriginIdMutualIdMismatch( - store.edges[edgeId].mutualId(), - store.edges[claimingEdgeId].originId - ); + revert OriginIdMutualIdMismatch(store.edges[edgeId].mutualId(), store.edges[claimingEdgeId].originId); } // the claiming edge must be exactly one level below - if ( - nextEdgeLevel(store.edges[edgeId].level, numBigStepLevel) != - store.edges[claimingEdgeId].level - ) { + if (nextEdgeLevel(store.edges[edgeId].level, numBigStepLevel) != store.edges[claimingEdgeId].level) { revert EdgeLevelInvalid( edgeId, claimingEdgeId, @@ -778,12 +686,9 @@ library EdgeChallengeManagerLib { /// @param edgeId The id of the edge to confirm /// @param claimingEdgeId The id of the edge which has a claimId equal to edgeId /// @param numBigStepLevel The number of big step levels in this challenge - function confirmEdgeByClaim( - EdgeStore storage store, - bytes32 edgeId, - bytes32 claimingEdgeId, - uint8 numBigStepLevel - ) internal { + function confirmEdgeByClaim(EdgeStore storage store, bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) + internal + { if (!store.edges[edgeId].exists()) { revert EdgeNotExists(edgeId); } @@ -902,10 +807,7 @@ library EdgeChallengeManagerLib { uint256 machineStep = get(store, edgeId).startHeight; // edge must be length one and be of type SmallStep - if ( - ChallengeEdgeLib.levelToType(store.edges[edgeId].level, numBigStepLevel) != - EdgeType.SmallStep - ) { + if (ChallengeEdgeLib.levelToType(store.edges[edgeId].level, numBigStepLevel) != EdgeType.SmallStep) { revert EdgeTypeNotSmallStep(store.edges[edgeId].level); } if (store.edges[edgeId].length() != 1) { @@ -914,26 +816,16 @@ library EdgeChallengeManagerLib { // the state in the onestep data must be committed to by the startHistoryRoot MerkleTreeLib.verifyInclusionProof( - store.edges[edgeId].startHistoryRoot, - oneStepData.beforeHash, - machineStep, - beforeHistoryInclusionProof + store.edges[edgeId].startHistoryRoot, oneStepData.beforeHash, machineStep, beforeHistoryInclusionProof ); // execute the single step to produce the after state - bytes32 afterHash = oneStepProofEntry.proveOneStep( - execCtx, - machineStep, - oneStepData.beforeHash, - oneStepData.proof - ); + bytes32 afterHash = + oneStepProofEntry.proveOneStep(execCtx, machineStep, oneStepData.beforeHash, oneStepData.proof); // check that the after state was indeed committed to by the endHistoryRoot MerkleTreeLib.verifyInclusionProof( - store.edges[edgeId].endHistoryRoot, - afterHash, - machineStep + 1, - afterHistoryInclusionProof + store.edges[edgeId].endHistoryRoot, afterHash, machineStep + 1, afterHistoryInclusionProof ); // also checks that no other rival has been confirmed diff --git a/contracts/src/challengeV2/libraries/MerkleTreeLib.sol b/contracts/src/challengeV2/libraries/MerkleTreeLib.sol index 1341da1dd..dfaa1260d 100644 --- a/contracts/src/challengeV2/libraries/MerkleTreeLib.sol +++ b/contracts/src/challengeV2/libraries/MerkleTreeLib.sol @@ -148,11 +148,11 @@ library MerkleTreeLib { /// @param me The merkle expansion to append a complete sub tree to /// @param level The level at which to append the complete subtree /// @param subtreeRoot The root of the complete subtree to be appended - function appendCompleteSubTree( - bytes32[] memory me, - uint256 level, - bytes32 subtreeRoot - ) internal pure returns (bytes32[] memory) { + function appendCompleteSubTree(bytes32[] memory me, uint256 level, bytes32 subtreeRoot) + internal + pure + returns (bytes32[] memory) + { // we use number representations of the levels elsewhere, so we need to ensure we're appending a leve // that's too high to use in uint require(level < MAX_LEVEL, "Level too high"); @@ -171,14 +171,13 @@ library MerkleTreeLib { bytes32 accumHash = subtreeRoot; uint256 meSize = treeSize(me); - uint256 postSize = meSize + 2**level; + uint256 postSize = meSize + 2 ** level; // if by appending the sub tree we increase the numbe of most sig bits of the size, that means // we'll need more space in the expansion to describe the tree, so we enlarge by one - bytes32[] memory next = UintUtilsLib.mostSignificantBit(postSize) > - UintUtilsLib.mostSignificantBit(meSize) + bytes32[] memory next = UintUtilsLib.mostSignificantBit(postSize) > UintUtilsLib.mostSignificantBit(meSize) ? new bytes32[](me.length + 1) - : new bytes32[](me.length); + : new bytes32[](me.length ); // ensure we're never creating an expansion that's too big require(next.length <= MAX_LEVEL, "Append creates oversize tree"); @@ -236,11 +235,7 @@ library MerkleTreeLib { /// into the tree to avoid root collisions. /// @param me The merkle expansion to append a leaf to /// @param leaf The leaf to append - will be hashed in here before appending - function appendLeaf(bytes32[] memory me, bytes32 leaf) - internal - pure - returns (bytes32[] memory) - { + function appendLeaf(bytes32[] memory me, bytes32 leaf) internal pure returns (bytes32[] memory) { // it's important that we hash the leaf, this ensures that this leaf cannot be a collision with any other non leaf // or root node, since these are always the hash of 64 bytes of data, and we're hashing 32 bytes return appendCompleteSubTree(me, 0, keccak256(abi.encodePacked(leaf))); @@ -253,11 +248,7 @@ library MerkleTreeLib { /// subtree in the expansion /// @param startSize The size of the start tree to find the maximum append to /// @param endSize The size of the end tree to find a maximum append under - function maximumAppendBetween(uint256 startSize, uint256 endSize) - internal - pure - returns (uint256) - { + function maximumAppendBetween(uint256 startSize, uint256 endSize) internal pure returns (uint256) { // Since the tree is binary we can represent it using the binary representation of a number // As described above, subtrees can only be appended to a tree if they are at the same level, or below, // the current lowest subtree. @@ -275,7 +266,7 @@ library MerkleTreeLib { // remove the high order bits that are shared uint256 msb = UintUtilsLib.mostSignificantBit(startSize ^ endSize); - uint256 mask = (1 << ((msb) + 1)) - 1; + uint256 mask = (1 << (msb) + 1) - 1; uint256 y = startSize & mask; uint256 z = endSize & mask; @@ -302,7 +293,7 @@ library MerkleTreeLib { uint256 sum = 0; for (uint256 i = 0; i < me.length; i++) { if (me[i] != 0) { - sum += 2**i; + sum += 2 ** i; } } return sum; @@ -365,17 +356,11 @@ library MerkleTreeLib { /// @param leaf The leaf preimage to prove inclusion - will be hashed in here before checking inclusion /// @param index The index of the leaf in the tree /// @param proof The path from the leaf to the root - function verifyInclusionProof( - bytes32 rootHash, - bytes32 leaf, - uint256 index, - bytes32[] memory proof - ) internal pure { - bytes32 calculatedRoot = MerkleLib.calculateRoot( - proof, - index, - keccak256(abi.encodePacked(leaf)) - ); + function verifyInclusionProof(bytes32 rootHash, bytes32 leaf, uint256 index, bytes32[] memory proof) + internal + pure + { + bytes32 calculatedRoot = MerkleLib.calculateRoot(proof, index, keccak256(abi.encodePacked(leaf))); require(rootHash == calculatedRoot, "Invalid inclusion proof"); } } diff --git a/contracts/src/challengeV2/libraries/UintUtilsLib.sol b/contracts/src/challengeV2/libraries/UintUtilsLib.sol index ad9d84331..82cd5423f 100644 --- a/contracts/src/challengeV2/libraries/UintUtilsLib.sol +++ b/contracts/src/challengeV2/libraries/UintUtilsLib.sol @@ -16,7 +16,7 @@ library UintUtilsLib { // isolate the least sig bit uint256 isolated = ((x - 1) & x) ^ x; - + // since we removed all higher bits, least sig == most sig return mostSignificantBit(isolated); } @@ -67,4 +67,4 @@ library UintUtilsLib { // x >= 2 ** 1 if (x >= 0x2) msb += 1; } -} +} \ No newline at end of file diff --git a/contracts/src/mocks/BridgeStub.sol b/contracts/src/mocks/BridgeStub.sol index 72b0d5b3f..6b183bd68 100644 --- a/contracts/src/mocks/BridgeStub.sol +++ b/contracts/src/mocks/BridgeStub.sol @@ -163,7 +163,8 @@ contract BridgeStub is IBridge { function setOutbox( address, /* outbox */ bool /* enabled*/ - ) external pure override {} + ) external pure override { + } function delayedMessageCount() external view override returns (uint256) { return delayedInboxAccs.length; diff --git a/contracts/src/mocks/ExecutionManager.sol b/contracts/src/mocks/ExecutionManager.sol index 38a920913..df8b7287c 100644 --- a/contracts/src/mocks/ExecutionManager.sol +++ b/contracts/src/mocks/ExecutionManager.sol @@ -28,10 +28,7 @@ contract SingleExecutionChallenge is OldChallengeManager { segments[1] = startAndEndHashes[1]; bytes32 challengeStateHash = OldChallengeLib.hashChallengeState(0, numSteps_, segments); challenge.challengeStateHash = challengeStateHash; - challenge.next = OldChallengeLib.Participant({ - addr: asserter_, - timeLeft: asserterTimeLeft_ - }); + challenge.next = OldChallengeLib.Participant({addr: asserter_, timeLeft: asserterTimeLeft_}); challenge.current = OldChallengeLib.Participant({ addr: challenger_, timeLeft: challengerTimeLeft_ diff --git a/contracts/src/mocks/MerkleTreeAccess.sol b/contracts/src/mocks/MerkleTreeAccess.sol index 6d7a47429..b885fc8ff 100644 --- a/contracts/src/mocks/MerkleTreeAccess.sol +++ b/contracts/src/mocks/MerkleTreeAccess.sol @@ -20,27 +20,19 @@ contract MerkleTreeAccess { return MerkleTreeLib.root(me); } - function appendCompleteSubTree( - bytes32[] memory me, - uint256 level, - bytes32 subtreeRoot - ) external pure returns (bytes32[] memory) { - return MerkleTreeLib.appendCompleteSubTree(me, level, subtreeRoot); - } - - function appendLeaf(bytes32[] memory me, bytes32 leaf) + function appendCompleteSubTree(bytes32[] memory me, uint256 level, bytes32 subtreeRoot) external pure returns (bytes32[] memory) { + return MerkleTreeLib.appendCompleteSubTree(me, level, subtreeRoot); + } + + function appendLeaf(bytes32[] memory me, bytes32 leaf) external pure returns (bytes32[] memory) { return MerkleTreeLib.appendLeaf(me, leaf); } - function maximumAppendBetween(uint256 startSize, uint256 endSize) - external - pure - returns (uint256) - { + function maximumAppendBetween(uint256 startSize, uint256 endSize) external pure returns (uint256) { return MerkleTreeLib.maximumAppendBetween(startSize, endSize); } @@ -52,23 +44,13 @@ contract MerkleTreeAccess { bytes32[] memory preExpansion, bytes32[] memory proof ) external pure { - return - MerkleTreeLib.verifyPrefixProof( - preRoot, - preSize, - postRoot, - postSize, - preExpansion, - proof - ); + return MerkleTreeLib.verifyPrefixProof(preRoot, preSize, postRoot, postSize, preExpansion, proof); } - function verifyInclusionProof( - bytes32 rootHash, - bytes32 leaf, - uint256 index, - bytes32[] memory proof - ) external pure { + function verifyInclusionProof(bytes32 rootHash, bytes32 leaf, uint256 index, bytes32[] memory proof) + external + pure + { MerkleTreeLib.verifyInclusionProof(rootHash, leaf, index, proof); } } diff --git a/contracts/src/mocks/SimpleOneStepProofEntry.sol b/contracts/src/mocks/SimpleOneStepProofEntry.sol index b583e5b7f..3916feb86 100644 --- a/contracts/src/mocks/SimpleOneStepProofEntry.sol +++ b/contracts/src/mocks/SimpleOneStepProofEntry.sol @@ -44,13 +44,9 @@ contract SimpleOneStepProofEntry is IOneStepProofEntry { return globalState.hash(); } - function getMachineHash(ExecutionState calldata execState) - external - pure - override - returns (bytes32) - { + function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return execState.globalState.hash(); + } } diff --git a/contracts/src/osp/OneStepProofEntry.sol b/contracts/src/osp/OneStepProofEntry.sol index ae05fd559..88d2104e7 100644 --- a/contracts/src/osp/OneStepProofEntry.sol +++ b/contracts/src/osp/OneStepProofEntry.sol @@ -62,12 +62,7 @@ contract OneStepProofEntry is IOneStepProofEntry { return mach.hash(); } - function getMachineHash(ExecutionState calldata execState) - external - pure - override - returns (bytes32) - { + function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { if (execState.machineStatus == MachineStatus.FINISHED) { return keccak256(abi.encodePacked("Machine finished:", execState.globalState.hash())); } else if (execState.machineStatus == MachineStatus.ERRORED) { @@ -98,11 +93,7 @@ contract OneStepProofEntry is IOneStepProofEntry { GlobalState memory globalState; (globalState, offset) = Deserialize.globalState(proof, offset); require(globalState.hash() == mach.globalStateHash, "BAD_GLOBAL_STATE"); - if ( - mach.status == MachineStatus.FINISHED && - machineStep == 0 && - globalState.getInboxPosition() < execCtx.maxInboxMessagesRead - ) { + if (mach.status == MachineStatus.FINISHED && machineStep == 0 && globalState.getInboxPosition() < execCtx.maxInboxMessagesRead) { // Kickstart the machine return getStartMachineHash(mach.globalStateHash, execCtx.initialWasmModuleRoot); } diff --git a/contracts/src/rollup/Assertion.sol b/contracts/src/rollup/Assertion.sol index 9364d43b3..0a3881c70 100644 --- a/contracts/src/rollup/Assertion.sol +++ b/contracts/src/rollup/Assertion.sol @@ -69,11 +69,10 @@ library AssertionNodeLib { /** * @notice Initialize a Assertion */ - function createAssertion(bool _isFirstChild, bytes32 _configHash) - internal - view - returns (AssertionNode memory) - { + function createAssertion( + bool _isFirstChild, + bytes32 _configHash + ) internal view returns (AssertionNode memory) { AssertionNode memory assertion; assertion.createdAtBlock = uint64(block.number); assertion.isFirstChild = _isFirstChild; diff --git a/contracts/src/rollup/BOLDUpgradeAction.sol b/contracts/src/rollup/BOLDUpgradeAction.sol index 82cf694b4..4d848d1e0 100644 --- a/contracts/src/rollup/BOLDUpgradeAction.sol +++ b/contracts/src/rollup/BOLDUpgradeAction.sol @@ -65,27 +65,18 @@ interface IOldRollup { ); function wasmModuleRoot() external view returns (bytes32); - function latestConfirmed() external view returns (uint64); - function getNode(uint64 nodeNum) external view returns (Node memory); - function getStakerAddress(uint64 stakerNum) external view returns (address); - function stakerCount() external view returns (uint64); - function getStaker(address staker) external view returns (OldStaker memory); - function isValidator(address validator) external view returns (bool); - function validatorWalletCreator() external view returns (address); } interface IOldRollupAdmin { function forceRefundStaker(address[] memory stacker) external; - function pause() external; - function resume() external; } @@ -103,36 +94,17 @@ contract StateHashPreImageLookup { mapping(bytes32 => bytes) internal preImages; - function stateHash(ExecutionState calldata execState, uint256 inboxMaxCount) - public - pure - returns (bytes32) - { - return - keccak256( - abi.encodePacked( - execState.globalState.hash(), - inboxMaxCount, - execState.machineStatus - ) - ); + function stateHash(ExecutionState calldata execState, uint256 inboxMaxCount) public pure returns (bytes32) { + return keccak256(abi.encodePacked(execState.globalState.hash(), inboxMaxCount, execState.machineStatus)); } - function set( - bytes32 h, - ExecutionState calldata execState, - uint256 inboxMaxCount - ) public { + function set(bytes32 h, ExecutionState calldata execState, uint256 inboxMaxCount) public { require(h == stateHash(execState, inboxMaxCount), "Invalid hash"); preImages[h] = abi.encode(execState, inboxMaxCount); emit HashSet(h, execState, inboxMaxCount); } - function get(bytes32 h) - public - view - returns (ExecutionState memory execState, uint256 inboxMaxCount) - { + function get(bytes32 h) public view returns (ExecutionState memory execState, uint256 inboxMaxCount) { (execState, inboxMaxCount) = abi.decode(preImages[h], (ExecutionState, uint256)); require(inboxMaxCount != 0, "Hash not yet set"); } @@ -348,21 +320,15 @@ contract BOLDUpgradeAction { } // upgrade the rollup to one that allows validators to withdraw even whilst paused - DoubleLogicUUPSUpgradeable(address(OLD_ROLLUP)).upgradeSecondaryTo( - IMPL_PATCHED_OLD_ROLLUP_USER - ); + DoubleLogicUUPSUpgradeable(address(OLD_ROLLUP)).upgradeSecondaryTo(IMPL_PATCHED_OLD_ROLLUP_USER); } /// @dev Create a config for the new rollup - fetches the latest confirmed /// assertion from the old rollup and uses it as genesis function createConfig() private view returns (Config memory) { // fetch the assertion associated with the latest confirmed state - bytes32 latestConfirmedStateHash = ROLLUP_READER - .getNode(ROLLUP_READER.latestConfirmed()) - .stateHash; - (ExecutionState memory genesisExecState, uint256 inboxMaxCount) = PREIMAGE_LOOKUP.get( - latestConfirmedStateHash - ); + bytes32 latestConfirmedStateHash = ROLLUP_READER.getNode(ROLLUP_READER.latestConfirmed()).stateHash; + (ExecutionState memory genesisExecState, uint256 inboxMaxCount) = PREIMAGE_LOOKUP.get(latestConfirmedStateHash); // double check the hash require( PREIMAGE_LOOKUP.stateHash(genesisExecState, inboxMaxCount) == latestConfirmedStateHash, @@ -372,27 +338,26 @@ contract BOLDUpgradeAction { // this isnt used during rollup creation, so we can pass in empty ISequencerInbox.MaxTimeVariation memory maxTimeVariation; - return - Config({ - confirmPeriodBlocks: CONFIRM_PERIOD_BLOCKS, - stakeToken: STAKE_TOKEN, - baseStake: STAKE_AMOUNT, - wasmModuleRoot: ROLLUP_READER.wasmModuleRoot(), - owner: address(this), // upgrade executor is the owner - loserStakeEscrow: L1_TIMELOCK, // additional funds get sent to the l1 timelock - chainId: CHAIN_ID, - chainConfig: "", // we can use an empty chain config it wont be used in the rollup initialization because we check if the rei is already connected there - miniStakeValue: MINI_STAKE_AMOUNT, - sequencerInboxMaxTimeVariation: maxTimeVariation, - layerZeroBlockEdgeHeight: BLOCK_LEAF_SIZE, - layerZeroBigStepEdgeHeight: BIGSTEP_LEAF_SIZE, - layerZeroSmallStepEdgeHeight: SMALLSTEP_LEAF_SIZE, - genesisExecutionState: genesisExecState, - genesisInboxCount: inboxMaxCount, - anyTrustFastConfirmer: ANY_TRUST_FAST_CONFIRMER, - numBigStepLevel: NUM_BIGSTEP_LEVEL, - challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS - }); + return Config({ + confirmPeriodBlocks: CONFIRM_PERIOD_BLOCKS, + stakeToken: STAKE_TOKEN, + baseStake: STAKE_AMOUNT, + wasmModuleRoot: ROLLUP_READER.wasmModuleRoot(), + owner: address(this), // upgrade executor is the owner + loserStakeEscrow: L1_TIMELOCK, // additional funds get sent to the l1 timelock + chainId: CHAIN_ID, + chainConfig: "", // we can use an empty chain config it wont be used in the rollup initialization because we check if the rei is already connected there + miniStakeValue: MINI_STAKE_AMOUNT, + sequencerInboxMaxTimeVariation: maxTimeVariation, + layerZeroBlockEdgeHeight: BLOCK_LEAF_SIZE, + layerZeroBigStepEdgeHeight: BIGSTEP_LEAF_SIZE, + layerZeroSmallStepEdgeHeight: SMALLSTEP_LEAF_SIZE, + genesisExecutionState: genesisExecState, + genesisInboxCount: inboxMaxCount, + anyTrustFastConfirmer: ANY_TRUST_FAST_CONFIRMER, + numBigStepLevel: NUM_BIGSTEP_LEVEL, + challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS + }); } function upgradeSurroundingContracts(address newRollupAddress) private { @@ -402,42 +367,28 @@ contract BOLDUpgradeAction { TransparentUpgradeableProxy bridge = TransparentUpgradeableProxy(payable(BRIDGE)); address currentBridgeImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation(bridge); PROXY_ADMIN_BRIDGE.upgradeAndCall( - bridge, - IMPL_BRIDGE, - abi.encodeWithSelector(IBridge.updateRollupAddress.selector, newRollupAddress) + bridge, IMPL_BRIDGE, abi.encodeWithSelector(IBridge.updateRollupAddress.selector, newRollupAddress) ); PROXY_ADMIN_BRIDGE.upgrade(bridge, currentBridgeImpl); - TransparentUpgradeableProxy sequencerInbox = TransparentUpgradeableProxy( - payable(SEQ_INBOX) - ); - address currentSequencerInboxImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation( - sequencerInbox - ); + TransparentUpgradeableProxy sequencerInbox = TransparentUpgradeableProxy(payable(SEQ_INBOX)); + address currentSequencerInboxImpl = PROXY_ADMIN_BRIDGE.getProxyImplementation(sequencerInbox); PROXY_ADMIN_SEQUENCER_INBOX.upgradeAndCall( - sequencerInbox, - IMPL_SEQUENCER_INBOX, - abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + sequencerInbox, IMPL_SEQUENCER_INBOX, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_SEQUENCER_INBOX.upgrade(sequencerInbox, currentSequencerInboxImpl); TransparentUpgradeableProxy rollupEventInbox = TransparentUpgradeableProxy(payable(REI)); - address currentRollupEventInboxImpl = PROXY_ADMIN_REI.getProxyImplementation( - rollupEventInbox - ); + address currentRollupEventInboxImpl = PROXY_ADMIN_REI.getProxyImplementation(rollupEventInbox); PROXY_ADMIN_REI.upgradeAndCall( - rollupEventInbox, - IMPL_REI, - abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + rollupEventInbox, IMPL_REI, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_REI.upgrade(rollupEventInbox, currentRollupEventInboxImpl); TransparentUpgradeableProxy outbox = TransparentUpgradeableProxy(payable(OUTBOX)); address currentOutboxImpl = PROXY_ADMIN_REI.getProxyImplementation(outbox); PROXY_ADMIN_OUTBOX.upgradeAndCall( - outbox, - IMPL_OUTBOX, - abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) + outbox, IMPL_OUTBOX, abi.encodeWithSelector(IOutbox.updateRollupAddress.selector) ); PROXY_ADMIN_OUTBOX.upgrade(outbox, currentOutboxImpl); } @@ -477,10 +428,8 @@ contract BOLDUpgradeAction { // upgrade the surrounding contracts eg bridge, outbox, seq inbox, rollup event inbox // to set of the new rollup address bytes32 rollupSalt = keccak256(abi.encode(config)); - address expectedRollupAddress = Create2Upgradeable.computeAddress( - rollupSalt, - keccak256(type(RollupProxy).creationCode) - ); + address expectedRollupAddress = + Create2Upgradeable.computeAddress(rollupSalt, keccak256(type(RollupProxy).creationCode)); upgradeSurroundingContracts(expectedRollupAddress); challengeManager.initialize({ @@ -496,7 +445,7 @@ contract BOLDUpgradeAction { _numBigStepLevel: config.numBigStepLevel }); - RollupProxy rollup = new RollupProxy{salt: rollupSalt}(); + RollupProxy rollup = new RollupProxy{ salt: rollupSalt}(); require(address(rollup) == expectedRollupAddress, "UNEXPCTED_ROLLUP_ADDR"); // initialize the rollup with this contract as owner to set batch poster and validators @@ -515,9 +464,7 @@ contract BOLDUpgradeAction { IRollupAdmin(address(rollup)).setValidator(validators, _vals); } if (DISABLE_VALIDATOR_WHITELIST) { - IRollupAdmin(address(rollup)).setValidatorWhitelistDisabled( - DISABLE_VALIDATOR_WHITELIST - ); + IRollupAdmin(address(rollup)).setValidatorWhitelistDisabled(DISABLE_VALIDATOR_WHITELIST); } IRollupAdmin(address(rollup)).setOwner(actualOwner); diff --git a/contracts/src/rollup/IRollupAdmin.sol b/contracts/src/rollup/IRollupAdmin.sol index 5ec67c9c3..bd1d288ad 100644 --- a/contracts/src/rollup/IRollupAdmin.sol +++ b/contracts/src/rollup/IRollupAdmin.sol @@ -13,8 +13,7 @@ import "./Config.sol"; interface IRollupAdmin { event OwnerFunctionCalled(uint256 indexed id); - function initialize(Config calldata config, ContractDependencies calldata connectedContracts) - external; + function initialize(Config calldata config, ContractDependencies calldata connectedContracts) external; /** * @notice Add a contract authorized to put messages into this rollup's inbox diff --git a/contracts/src/rollup/IRollupCore.sol b/contracts/src/rollup/IRollupCore.sol index ab832a920..156c9c926 100644 --- a/contracts/src/rollup/IRollupCore.sol +++ b/contracts/src/rollup/IRollupCore.sol @@ -36,19 +36,12 @@ interface IRollupCore is IAssertionChain { event AssertionConfirmed(bytes32 indexed assertionHash, bytes32 blockHash, bytes32 sendRoot); event RollupChallengeStarted( - uint64 indexed challengeIndex, - address asserter, - address challenger, - uint64 challengedAssertion + uint64 indexed challengeIndex, address asserter, address challenger, uint64 challengedAssertion ); event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); - event UserWithdrawableFundsUpdated( - address indexed user, - uint256 initialBalance, - uint256 finalBalance - ); + event UserWithdrawableFundsUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); function confirmPeriodBlocks() external view returns (uint64); @@ -90,10 +83,7 @@ interface IRollupCore is IAssertionChain { * This function will revert if the given assertion hash does not exist. * @dev This function is meant for internal use only and has no stability guarantees. */ - function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) - external - view - returns (uint256); + function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) external view returns (uint256); /** * @notice Get the address of the staker at the given index @@ -136,7 +126,6 @@ interface IRollupCore is IAssertionChain { * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view returns (uint256); - /// @return Index of the latest confirmed assertion function latestConfirmed() external view returns (bytes32); diff --git a/contracts/src/rollup/IRollupLogic.sol b/contracts/src/rollup/IRollupLogic.sol index 9221f870c..d1e2f5de9 100644 --- a/contracts/src/rollup/IRollupLogic.sol +++ b/contracts/src/rollup/IRollupLogic.sol @@ -27,8 +27,7 @@ interface IRollupUser is IRollupCore, IOwnable { bytes32 inboxAcc ) external; - function stakeOnNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) - external; + function stakeOnNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) external; function returnOldDeposit() external; diff --git a/contracts/src/rollup/RollupAdminLogic.sol b/contracts/src/rollup/RollupAdminLogic.sol index 647c19214..7b383b2ad 100644 --- a/contracts/src/rollup/RollupAdminLogic.sol +++ b/contracts/src/rollup/RollupAdminLogic.sol @@ -31,25 +31,12 @@ contract RollupAdminLogic is RollupCore, IRollupAdmin, DoubleLogicUUPSUpgradeabl // dont need to connect and initialize the event inbox if it's already been initialized if (!bridge.allowedDelayedInboxes(address(connectedContracts.rollupEventInbox))) { - connectedContracts.bridge.setDelayedInbox( - address(connectedContracts.rollupEventInbox), - true - ); - connectedContracts.rollupEventInbox.rollupInitialized( - config.chainId, - config.chainConfig - ); + connectedContracts.bridge.setDelayedInbox(address(connectedContracts.rollupEventInbox), true); + connectedContracts.rollupEventInbox.rollupInitialized(config.chainId, config.chainConfig); } if (connectedContracts.sequencerInbox.totalDelayedMessagesRead() == 0) { - connectedContracts.sequencerInbox.addSequencerL2Batch( - 0, - "", - 1, - IGasRefunder(address(0)), - 0, - 1 - ); + connectedContracts.sequencerInbox.addSequencerL2Batch(0, "", 1, IGasRefunder(address(0)), 0, 1); } validatorWalletCreator = connectedContracts.validatorWalletCreator; diff --git a/contracts/src/rollup/RollupCore.sol b/contracts/src/rollup/RollupCore.sol index 6a2bf5b97..d8ea8020c 100644 --- a/contracts/src/rollup/RollupCore.sol +++ b/contracts/src/rollup/RollupCore.sol @@ -123,11 +123,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { * @param assertionHash Id of the assertion * @return Assertion struct */ - function getAssertionStorage(bytes32 assertionHash) - internal - view - returns (AssertionNode storage) - { + function getAssertionStorage(bytes32 assertionHash) internal view returns (AssertionNode storage) { require(assertionHash != bytes32(0), "ASSERTION_ID_CANNOT_BE_ZERO"); return _assertions[assertionHash]; } @@ -135,12 +131,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { /** * @notice Get the Assertion for the given index. */ - function getAssertion(bytes32 assertionHash) - public - view - override - returns (AssertionNode memory) - { + function getAssertion(bytes32 assertionHash) public view override returns (AssertionNode memory) { return getAssertionStorage(assertionHash); } @@ -151,12 +142,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { * This function will revert if the given assertion hash does not exist. * @dev This function is meant for internal use only and has no stability guarantees. */ - function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) - external - view - override - returns (uint256) - { + function getAssertionCreationBlockForLogLookup(bytes32 assertionHash) external view override returns (uint256) { if (_hostChainIsArbitrum) { uint256 blockNum = _assertionCreatedAtArbSysBlock[assertionHash]; require(blockNum > 0, "NO_ASSERTION"); @@ -259,8 +245,8 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // Authenticate data against assertionHash pre-image require( - assertionHash == - RollupLib.assertionHash({ + assertionHash + == RollupLib.assertionHash({ parentAssertionHash: parentAssertionHash, afterState: confirmState, inboxAcc: inboxAcc @@ -381,16 +367,15 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { ) internal returns (bytes32) { // Validate the config hash RollupLib.validateConfigHash( - assertion.beforeStateData.configData, - getAssertionStorage(prevAssertionHash).configHash + assertion.beforeStateData.configData, getAssertionStorage(prevAssertionHash).configHash ); // reading inbox messages always terminates in either a finished or errored state // although the challenge protocol that any invalid terminal state will be proven incorrect // we can do a quick sanity check here require( - assertion.afterState.machineStatus == MachineStatus.FINISHED || - assertion.afterState.machineStatus == MachineStatus.ERRORED, + assertion.afterState.machineStatus == MachineStatus.FINISHED + || assertion.afterState.machineStatus == MachineStatus.ERRORED, "BAD_AFTER_STATUS" ); @@ -428,10 +413,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // All types of assertion must have inbox position in the range prev.inboxPosition <= x <= prev.nextInboxPosition require(afterInboxPosition >= prevInboxPosition, "INBOX_BACKWARDS"); - require( - afterInboxPosition <= assertion.beforeStateData.configData.nextInboxPosition, - "INBOX_TOO_FAR" - ); + require(afterInboxPosition <= assertion.beforeStateData.configData.nextInboxPosition, "INBOX_TOO_FAR"); // SANITY CHECK: the next inbox position did indeed move forward // this is enforced by code in a later section that artificially increases the nextInboxPosition @@ -439,19 +421,14 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // this ensures that assertions will continue to advance. // It also means that below, where we check that afterInboxPosition equals prev.nextInboxPosition // in the FINISHED state, we can be sure that it processed at least one message - require( - assertion.beforeStateData.configData.nextInboxPosition > prevInboxPosition, - "NEXT_INBOX_BACKWARDS" - ); + require(assertion.beforeStateData.configData.nextInboxPosition > prevInboxPosition, "NEXT_INBOX_BACKWARDS"); // if the position in the message is > 0, then the afterInboxPosition cannot be the nextInboxPosition // as this would be outside the range - this can only occur for ERRORED states if (assertion.afterState.machineStatus == MachineStatus.ERRORED) { if (assertion.afterState.globalState.getPositionInMessage() > 0) { require( - afterInboxPosition != - assertion.beforeStateData.configData.nextInboxPosition, - "POSITION_TOO_FAR" + afterInboxPosition != assertion.beforeStateData.configData.nextInboxPosition, "POSITION_TOO_FAR" ); } } else if (assertion.afterState.machineStatus == MachineStatus.FINISHED) { @@ -461,10 +438,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { "INVALID_FINISHED_INBOX" ); // and it should have position in message == 0, ready to start reading the next message - require( - assertion.afterState.globalState.getPositionInMessage() == 0, - "NON_ZERO_FINISHED_POS_IN_MSG" - ); + require(assertion.afterState.globalState.getPositionInMessage() == 0, "NON_ZERO_FINISHED_POS_IN_MSG"); } else { // we checked this above, but include a safety check here in case of refactoring revert("INVALID_STATUS"); @@ -480,8 +454,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // in this case we need to ensure when the assertion is made the inbox messages are available // to ensure that a valid assertion can actually be made. require( - assertion.beforeStateData.configData.nextInboxPosition <= currentInboxPosition, - "INBOX_NOT_POPULATED" + assertion.beforeStateData.configData.nextInboxPosition <= currentInboxPosition, "INBOX_NOT_POPULATED" ); // The next assertion must consume all the messages that are currently found in the inbox @@ -508,11 +481,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { sequencerBatchAcc = bridge.sequencerInboxAccs(afterInboxPosition - 1); } - bytes32 newAssertionHash = RollupLib.assertionHash( - prevAssertionHash, - assertion.afterState, - sequencerBatchAcc - ); + bytes32 newAssertionHash = RollupLib.assertionHash(prevAssertionHash, assertion.afterState, sequencerBatchAcc); // allow an assertion creator to ensure that they're creating their assertion against the expected state require( @@ -523,10 +492,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { // the assertion hash is unique - it's only possible to have one correct assertion hash // per assertion. Therefore we can check if this assertion has already been made, and if so // we can revert - require( - getAssertionStorage(newAssertionHash).status == AssertionStatus.NoAssertion, - "ASSERTION_SEEN" - ); + require(getAssertionStorage(newAssertionHash).status == AssertionStatus.NoAssertion, "ASSERTION_SEEN"); // state updates AssertionNode memory newAssertion = AssertionNodeLib.createAssertion( @@ -557,8 +523,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { confirmPeriodBlocks ); if (_hostChainIsArbitrum) { - _assertionCreatedAtArbSysBlock[newAssertionHash] = ArbSys(address(100)) - .arbBlockNumber(); + _assertionCreatedAtArbSysBlock[newAssertionHash] = ArbSys(address(100)).arbBlockNumber(); } return newAssertionHash; @@ -566,18 +531,14 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { function genesisAssertionHash() external pure returns (bytes32) { GlobalState memory emptyGlobalState; - ExecutionState memory emptyExecutionState = ExecutionState( - emptyGlobalState, - MachineStatus.FINISHED - ); + ExecutionState memory emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); bytes32 parentAssertionHash = bytes32(0); bytes32 inboxAcc = bytes32(0); - return - RollupLib.assertionHash({ - parentAssertionHash: parentAssertionHash, - afterState: emptyExecutionState, - inboxAcc: inboxAcc - }); + return RollupLib.assertionHash({ + parentAssertionHash: parentAssertionHash, + afterState: emptyExecutionState, + inboxAcc: inboxAcc + }); } function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64) { @@ -594,10 +555,7 @@ abstract contract RollupCore is IRollupCore, PausableUpgradeable { bytes32 prevAssertionHash, bytes32 inboxAcc ) external pure { - require( - assertionHash == RollupLib.assertionHash(prevAssertionHash, state, inboxAcc), - "INVALID_ASSERTION_HASH" - ); + require(assertionHash == RollupLib.assertionHash(prevAssertionHash, state, inboxAcc), "INVALID_ASSERTION_HASH"); } function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view { diff --git a/contracts/src/rollup/RollupCreator.sol b/contracts/src/rollup/RollupCreator.sol index 62a80670e..293ec3e34 100644 --- a/contracts/src/rollup/RollupCreator.sol +++ b/contracts/src/rollup/RollupCreator.sol @@ -15,11 +15,7 @@ import "./IRollupAdmin.sol"; contract RollupCreator is Ownable { event RollupCreated( - address indexed rollupAddress, - address inboxAddress, - address adminProxy, - address sequencerInbox, - address bridge + address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge ); event TemplatesUpdated(); @@ -51,11 +47,10 @@ contract RollupCreator is Ownable { } // internal function to workaround stack limit - function createChallengeManager( - address rollupAddr, - address proxyAdminAddr, - Config memory config - ) internal returns (IEdgeChallengeManager) { + function createChallengeManager(address rollupAddr, address proxyAdminAddr, Config memory config) + internal + returns (IEdgeChallengeManager) + { IEdgeChallengeManager challengeManager = IEdgeChallengeManager( address( new TransparentUpgradeableProxy( @@ -114,50 +109,25 @@ contract RollupCreator is Ownable { uint256 maxDataSize ) public returns (address) { // Make sure the immutable maxDataSize is as expected - require( - maxDataSize == bridgeCreator.sequencerInboxTemplate().maxDataSize(), - "SI_MAX_DATA_SIZE_MISMATCH" - ); - require( - maxDataSize == bridgeCreator.inboxTemplate().maxDataSize(), - "I_MAX_DATA_SIZE_MISMATCH" - ); + require(maxDataSize == bridgeCreator.sequencerInboxTemplate().maxDataSize(), "SI_MAX_DATA_SIZE_MISMATCH"); + require(maxDataSize == bridgeCreator.inboxTemplate().maxDataSize(), "I_MAX_DATA_SIZE_MISMATCH"); DeployedContracts memory deployed; deployed.proxyAdmin = new ProxyAdmin(); deployed.proxyAdmin.transferOwnership(config.owner); // Create the rollup proxy to figure out the address and initialize it later - deployed.rollup = new RollupProxy{ - salt: keccak256( - abi.encode( - config, - _batchPoster, - _validators, - disableValidatorWhitelist, - maxDataSize - ) - ) - }(); - - ( - deployed.bridge, - deployed.sequencerInbox, - deployed.inbox, - deployed.rollupEventInbox, - deployed.outbox - ) = bridgeCreator.createBridge( - address(deployed.proxyAdmin), - address(deployed.rollup), - config.sequencerInboxMaxTimeVariation - ); + deployed.rollup = + new RollupProxy{salt: keccak256(abi.encode(config, _batchPoster, _validators, disableValidatorWhitelist, maxDataSize))}(); - deployed.challengeManager = createChallengeManager( - address(deployed.rollup), - address(deployed.proxyAdmin), - config + (deployed.bridge, deployed.sequencerInbox, deployed.inbox, deployed.rollupEventInbox, deployed.outbox) = + bridgeCreator.createBridge( + address(deployed.proxyAdmin), address(deployed.rollup), config.sequencerInboxMaxTimeVariation ); + deployed.challengeManager = + createChallengeManager(address(deployed.rollup), address(deployed.proxyAdmin), config); + // initialize the rollup with this contract as owner to set batch poster and validators // it will transfer the ownership back to the actual owner later address actualOwner = config.owner; @@ -191,9 +161,7 @@ contract RollupCreator is Ownable { IRollupAdmin(address(deployed.rollup)).setValidator(_validators, _vals); } if (disableValidatorWhitelist == true) { - IRollupAdmin(address(deployed.rollup)).setValidatorWhitelistDisabled( - disableValidatorWhitelist - ); + IRollupAdmin(address(deployed.rollup)).setValidatorWhitelistDisabled(disableValidatorWhitelist); } IRollupAdmin(address(deployed.rollup)).setOwner(actualOwner); diff --git a/contracts/src/rollup/RollupLib.sol b/contracts/src/rollup/RollupLib.sol index 61baf2d2f..be62d6e66 100644 --- a/contracts/src/rollup/RollupLib.sol +++ b/contracts/src/rollup/RollupLib.sol @@ -31,7 +31,11 @@ library RollupLib { bytes32 inboxAcc ) internal pure returns (bytes32) { // we can no longer have `hasSibling` in the assertion hash as it would allow identical assertions - return assertionHash(parentAssertionHash, executionStateHash(afterState), inboxAcc); + return assertionHash( + parentAssertionHash, + executionStateHash(afterState), + inboxAcc + ); } // Takes in a hash of the afterState instead of the afterState itself @@ -41,7 +45,14 @@ library RollupLib { bytes32 inboxAcc ) internal pure returns (bytes32) { // we can no longer have `hasSibling` in the assertion hash as it would allow identical assertions - return keccak256(abi.encodePacked(parentAssertionHash, afterStateHash, inboxAcc)); + return + keccak256( + abi.encodePacked( + parentAssertionHash, + afterStateHash, + inboxAcc + ) + ); } // All these should be emited in AssertionCreated event @@ -64,10 +75,13 @@ library RollupLib { ); } - function validateConfigHash(ConfigData calldata configData, bytes32 _configHash) internal pure { + function validateConfigHash( + ConfigData calldata configData, + bytes32 _configHash + ) internal pure { require( - _configHash == - configHash( + _configHash + == configHash( configData.wasmModuleRoot, configData.requiredStake, configData.challengeManager, diff --git a/contracts/src/rollup/RollupProxy.sol b/contracts/src/rollup/RollupProxy.sol index 28bf3aa1f..aa490fc83 100644 --- a/contracts/src/rollup/RollupProxy.sol +++ b/contracts/src/rollup/RollupProxy.sol @@ -19,7 +19,11 @@ contract RollupProxy is AdminFallbackProxy { ) { _initialize( address(connectedContracts.rollupAdminLogic), - abi.encodeCall(IRollupAdmin.initialize, (config, connectedContracts)), + abi.encodeCall( + IRollupAdmin.initialize, + (config, + connectedContracts) + ), address(connectedContracts.rollupUserLogic), abi.encodeCall(IRollupUser.initialize, (config.stakeToken)), config.owner diff --git a/contracts/src/rollup/RollupUserLogic.sol b/contracts/src/rollup/RollupUserLogic.sol index 9ba088d11..a23500b6b 100644 --- a/contracts/src/rollup/RollupUserLogic.sol +++ b/contracts/src/rollup/RollupUserLogic.sol @@ -88,16 +88,16 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { bytes32 inboxAcc ) external onlyValidator whenNotPaused { /* - * To confirm an assertion, the following must be true: - * 1. The assertion must be pending - * 2. The assertion's deadline must have passed - * 3. The assertion's prev must be latest confirmed - * 4. The assertion's prev's child confirm deadline must have passed - * 5. If the assertion's prev has more than 1 child, the assertion must be the winner of the challenge - * - * Note that we do not need to ever reject invalid assertion because they can never confirm - * and the stake on them is swept to the loserStakeEscrow as soon as the leaf is created - */ + * To confirm an assertion, the following must be true: + * 1. The assertion must be pending + * 2. The assertion's deadline must have passed + * 3. The assertion's prev must be latest confirmed + * 4. The assertion's prev's child confirm deadline must have passed + * 5. If the assertion's prev has more than 1 child, the assertion must be the winner of the challenge + * + * Note that we do not need to ever reject invalid assertion because they can never confirm + * and the stake on them is swept to the loserStakeEscrow as soon as the leaf is created + */ // The assertion's must exists and be pending and will be validated in RollupCore.confirmAssertionInternal AssertionNode storage assertion = getAssertionStorage(assertionHash); @@ -107,18 +107,14 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { RollupLib.validateConfigHash(prevConfig, prevAssertion.configHash); // Check that deadline has passed - require( - block.number >= assertion.createdAtBlock + prevConfig.confirmPeriodBlocks, - "BEFORE_DEADLINE" - ); + require(block.number >= assertion.createdAtBlock + prevConfig.confirmPeriodBlocks, "BEFORE_DEADLINE"); // Check that prev is latest confirmed require(prevAssertionHash == latestConfirmed(), "PREV_NOT_LATEST_CONFIRMED"); if (prevAssertion.secondChildBlock > 0) { // if the prev has more than 1 child, check if this assertion is the challenge winner - ChallengeEdge memory winningEdge = IEdgeChallengeManager(prevConfig.challengeManager) - .getEdge(winningEdgeId); + ChallengeEdge memory winningEdge = IEdgeChallengeManager(prevConfig.challengeManager).getEdge(winningEdgeId); require(winningEdge.claimId == assertionHash, "NOT_WINNER"); require(winningEdge.status == EdgeStatus.Confirmed, "EDGE_NOT_CONFIRMED"); require(winningEdge.confirmedAtBlock != 0, "ZERO_CONFIRMED_AT_BLOCK"); @@ -151,11 +147,11 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param prevAssertionHash The hash of the assertion's parent * @param inboxAcc The inbox batch accumulator */ - function computeAssertionHash( - bytes32 prevAssertionHash, - ExecutionState calldata state, - bytes32 inboxAcc - ) external pure returns (bytes32) { + function computeAssertionHash(bytes32 prevAssertionHash, ExecutionState calldata state, bytes32 inboxAcc) + external + pure + returns (bytes32) + { return RollupLib.assertionHash(prevAssertionHash, state, inboxAcc); } @@ -171,8 +167,8 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { { // Early revert on duplicated assertion if expectedAssertionHash is set require( - expectedAssertionHash == bytes32(0) || - getAssertionStorage(expectedAssertionHash).status == AssertionStatus.NoAssertion, + expectedAssertionHash == bytes32(0) + || getAssertionStorage(expectedAssertionHash).status == AssertionStatus.NoAssertion, "EXPECTED_ASSERTION_SEEN" ); @@ -183,10 +179,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // the staker may have more than enough stake, and the entire stake will be locked // we cannot do a refund here because the staker may be staker on an unconfirmed ancestor that requires more stake // excess stake can be removed by calling reduceDeposit when the staker is inactive - require( - amountStaked(msg.sender) >= assertion.beforeStateData.configData.requiredStake, - "INSUFFICIENT_STAKE" - ); + require(amountStaked(msg.sender) >= assertion.beforeStateData.configData.requiredStake, "INSUFFICIENT_STAKE"); bytes32 prevAssertion = RollupLib.assertionHash( assertion.beforeStateData.prevPrevAssertionHash, @@ -200,8 +193,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // b) its last staked assertion have a child bytes32 lastAssertion = latestStakedAssertion(msg.sender); require( - lastAssertion == prevAssertion || - getAssertionStorage(lastAssertion).firstChildBlock > 0, + lastAssertion == prevAssertion || getAssertionStorage(lastAssertion).firstChildBlock > 0, "STAKED_ON_ANOTHER_BRANCH" ); @@ -209,11 +201,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // Verify that assertion meets the minimum Delta time requirement require(timeSincePrev >= minimumAssertionPeriod, "TIME_DELTA"); - bytes32 newAssertionHash = createNewAssertion( - assertion, - prevAssertion, - expectedAssertionHash - ); + bytes32 newAssertionHash = createNewAssertion(assertion, prevAssertion, expectedAssertionHash); _stakerMap[msg.sender].latestStakedAssertion = newAssertionHash; if (!getAssertionStorage(newAssertionHash).isFirstChild) { @@ -221,10 +209,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { // only 1 of the children can be confirmed and get their stake refunded // so we send the other children's stake to the loserStakeEscrow // NOTE: if the losing staker have staked more than requiredStake, the excess stake will be stuck - increaseWithdrawableFunds( - loserStakeEscrow, - assertion.beforeStateData.configData.requiredStake - ); + increaseWithdrawableFunds(loserStakeEscrow, assertion.beforeStateData.configData.requiredStake); } } @@ -241,11 +226,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param stakerAddress Address of the staker whose stake is increased * @param depositAmount The amount of either eth or tokens deposited */ - function _addToDeposit(address stakerAddress, uint256 depositAmount) - internal - onlyValidator - whenNotPaused - { + function _addToDeposit(address stakerAddress, uint256 depositAmount) internal onlyValidator whenNotPaused { require(isStaked(stakerAddress), "NOT_STAKED"); increaseStakeBy(stakerAddress, depositAmount); } @@ -286,10 +267,10 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * as doing so would result in incorrect accounting of withdrawable funds in the loserStakeEscrow. * This is because the protocol assume there is only 1 unique confirmable child assertion. */ - function fastConfirmNewAssertion( - AssertionInputs calldata assertion, - bytes32 expectedAssertionHash - ) external whenNotPaused { + function fastConfirmNewAssertion(AssertionInputs calldata assertion, bytes32 expectedAssertionHash) + external + whenNotPaused + { // Must supply expectedAssertionHash to fastConfirmNewAssertion require(expectedAssertionHash != bytes32(0), "EXPECTED_ASSERTION_HASH"); AssertionStatus status = getAssertionStorage(expectedAssertionHash).status; @@ -303,19 +284,12 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { if (status == AssertionStatus.NoAssertion) { // If not exists, we create the new assertion - bytes32 newAssertionHash = createNewAssertion( - assertion, - prevAssertion, - expectedAssertionHash - ); + bytes32 newAssertionHash = createNewAssertion(assertion, prevAssertion, expectedAssertionHash); if (!getAssertionStorage(newAssertionHash).isFirstChild) { // only 1 of the children can be confirmed and get their stake refunded // so we send the other children's stake to the loserStakeEscrow // NOTE: if the losing staker have staked more than requiredStake, the excess stake will be stuck - increaseWithdrawableFunds( - loserStakeEscrow, - assertion.beforeStateData.configData.requiredStake - ); + increaseWithdrawableFunds(loserStakeEscrow, assertion.beforeStateData.configData.requiredStake); } } @@ -354,11 +328,7 @@ contract RollupUserLogic is RollupCore, UUPSNotUpgradeable, IRollupUser { * @param stakerAddress Address of the staker whose stake is increased * @param tokenAmount the amount of tokens staked */ - function addToDeposit(address stakerAddress, uint256 tokenAmount) - external - onlyValidator - whenNotPaused - { + function addToDeposit(address stakerAddress, uint256 tokenAmount) external onlyValidator whenNotPaused { _addToDeposit(stakerAddress, tokenAmount); /// @dev This is an external call, safe because it's at the end of the function receiveTokens(tokenAmount); diff --git a/contracts/src/rollup/ValidatorWallet.sol b/contracts/src/rollup/ValidatorWallet.sol index 0a56c2598..f064710f5 100644 --- a/contracts/src/rollup/ValidatorWallet.sol +++ b/contracts/src/rollup/ValidatorWallet.sol @@ -160,9 +160,7 @@ contract ValidatorWallet is OwnableUpgradeable, DelegateCallAware, GasRefundEnab } } - function timeoutChallenges(IOldChallengeManager manager, uint64[] calldata challenges) - external - { + function timeoutChallenges(IOldChallengeManager manager, uint64[] calldata challenges) external { timeoutChallengesWithGasRefunder(IGasRefunder(address(0)), manager, challenges); } diff --git a/contracts/test/ERC20Mock.sol b/contracts/test/ERC20Mock.sol index f114b92d1..b271b30c1 100644 --- a/contracts/test/ERC20Mock.sol +++ b/contracts/test/ERC20Mock.sol @@ -38,4 +38,4 @@ contract ERC20Mock is ERC20 { ) public { _approve(owner, spender, value); } -} +} \ No newline at end of file diff --git a/contracts/test/MockAssertionChain.sol b/contracts/test/MockAssertionChain.sol index 84588c5da..af9e21af8 100644 --- a/contracts/test/MockAssertionChain.sol +++ b/contracts/test/MockAssertionChain.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.17; import "forge-std/Test.sol"; import {IAssertionChain} from "../src/challengeV2/IAssertionChain.sol"; -import {IEdgeChallengeManager} from "../src/challengeV2/EdgeChallengeManager.sol"; +import { IEdgeChallengeManager } from "../src/challengeV2/EdgeChallengeManager.sol"; import "../src/bridge/IBridge.sol"; import "../src/rollup/RollupLib.sol"; import "./challengeV2/StateTools.sol"; @@ -32,7 +32,7 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].height != 0; } - function stakeToken() public view returns (address) { + function stakeToken() public view returns(address) { return address(0); } @@ -44,10 +44,7 @@ contract MockAssertionChain is IAssertionChain { ) external view { require(assertionExists(assertionHash), "Assertion does not exist"); // TODO: HN: This is not how the real assertion chain calculate assertion hash - require( - assertionHash == calculateAssertionHash(prevAssertionHash, state), - "INVALID_ASSERTION_HASH" - ); + require(assertionHash == calculateAssertionHash(prevAssertionHash, state), "INVALID_ASSERTION_HASH"); } function getFirstChildCreationBlock(bytes32 assertionHash) external view returns (uint64) { @@ -60,7 +57,10 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].secondChildCreationBlock; } - function validateConfig(bytes32 assertionHash, ConfigData calldata configData) external view { + function validateConfig( + bytes32 assertionHash, + ConfigData calldata configData + ) external view { require( RollupLib.configHash({ wasmModuleRoot: configData.wasmModuleRoot, @@ -83,17 +83,19 @@ contract MockAssertionChain is IAssertionChain { return assertions[assertionHash].isPending; } - function calculateAssertionHash(bytes32 predecessorId, ExecutionState memory afterState) + function calculateAssertionHash( + bytes32 predecessorId, + ExecutionState memory afterState + ) public view returns (bytes32) { - return - RollupLib.assertionHash({ - parentAssertionHash: predecessorId, - afterState: afterState, - inboxAcc: keccak256(abi.encode(afterState.globalState.u64Vals[0])) // mock accumulator based on inbox count - }); + return RollupLib.assertionHash({ + parentAssertionHash: predecessorId, + afterState: afterState, + inboxAcc: keccak256(abi.encode(afterState.globalState.u64Vals[0])) // mock accumulator based on inbox count + }); } function childCreated(bytes32 assertionHash) internal { @@ -146,18 +148,8 @@ contract MockAssertionChain is IAssertionChain { require(!assertionExists(assertionHash), "Assertion already exists"); require(assertionExists(predecessorId), "Predecessor does not exists"); require(height > assertions[predecessorId].height, "Height too low"); - require( - beforeStateHash == StateToolsLib.hash(assertions[predecessorId].state), - "Before state hash does not match predecessor" - ); + require(beforeStateHash == StateToolsLib.hash(assertions[predecessorId].state), "Before state hash does not match predecessor"); - return - addAssertionUnsafe( - predecessorId, - height, - nextInboxPosition, - afterState, - successionChallenge - ); + return addAssertionUnsafe(predecessorId, height, nextInboxPosition, afterState, successionChallenge); } } diff --git a/contracts/test/Rollup.t.sol b/contracts/test/Rollup.t.sol index 6eaebef44..aee3f4eca 100644 --- a/contracts/test/Rollup.t.sol +++ b/contracts/test/Rollup.t.sol @@ -47,7 +47,7 @@ contract RollupTest is Test { bytes32 constant FIRST_ASSERTION_BLOCKHASH = keccak256("FIRST_ASSERTION_BLOCKHASH"); bytes32 constant FIRST_ASSERTION_SENDROOT = keccak256("FIRST_ASSERTION_SENDROOT"); - uint256 constant LAYERZERO_BLOCKEDGE_HEIGHT = 2**5; + uint256 constant LAYERZERO_BLOCKEDGE_HEIGHT = 2 ** 5; IERC20 token; RollupProxy rollup; @@ -61,20 +61,15 @@ contract RollupTest is Test { GlobalState emptyGlobalState; ExecutionState emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); - bytes32 genesisHash = - RollupLib.assertionHash({ - parentAssertionHash: bytes32(0), - afterState: emptyExecutionState, - inboxAcc: bytes32(0) - }); + bytes32 genesisHash = RollupLib.assertionHash({ + parentAssertionHash: bytes32(0), + afterState: emptyExecutionState, + inboxAcc: bytes32(0) + }); ExecutionState firstState; event RollupCreated( - address indexed rollupAddress, - address inboxAddress, - address adminProxy, - address sequencerInbox, - address bridge + address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge ); function setUp() public { @@ -103,10 +98,8 @@ contract RollupTest is Test { address(0) ); - ExecutionState memory emptyState = ExecutionState( - GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), - MachineStatus.FINISHED - ); + ExecutionState memory emptyState = + ExecutionState(GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), MachineStatus.FINISHED); token = new TestWETH9("Test", "TEST"); IWETH9(address(token)).deposit{value: 10 ether}(); @@ -128,9 +121,9 @@ contract RollupTest is Test { genesisExecutionState: emptyState, genesisInboxCount: 0, miniStakeValue: MINI_STAKE_VALUE, - layerZeroBlockEdgeHeight: 2**5, - layerZeroBigStepEdgeHeight: 2**5, - layerZeroSmallStepEdgeHeight: 2**5, + layerZeroBlockEdgeHeight: 2 ** 5, + layerZeroBigStepEdgeHeight: 2 ** 5, + layerZeroSmallStepEdgeHeight: 2 ** 5, anyTrustFastConfirmer: anyTrustFastConfirmer, numBigStepLevel: 3, challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS @@ -138,20 +131,10 @@ contract RollupTest is Test { vm.expectEmit(false, false, false, false); emit RollupCreated(address(0), address(0), address(0), address(0), address(0)); - address rollupAddr = rollupCreator.createRollup( - config, - address(0), - new address[](0), - false, - MAX_DATA_SIZE - ); - bytes32 rollupSalt = keccak256( - abi.encode(config, address(0), new address[](0), false, MAX_DATA_SIZE) - ); + address rollupAddr = rollupCreator.createRollup(config, address(0), new address[](0), false, MAX_DATA_SIZE); + bytes32 rollupSalt = keccak256(abi.encode(config, address(0), new address[](0), false, MAX_DATA_SIZE)); address expectedRollupAddress = Create2Upgradeable.computeAddress( - rollupSalt, - keccak256(type(RollupProxy).creationCode), - address(rollupCreator) + rollupSalt, keccak256(type(RollupProxy).creationCode), address(rollupCreator) ); assertEq(expectedRollupAddress, rollupAddr, "Unexpected rollup address"); @@ -227,10 +210,7 @@ contract RollupTest is Test { function testGenesisAssertionConfirmed() external { bytes32 latestConfirmed = userRollup.latestConfirmed(); assertEq(latestConfirmed, genesisHash); - assertEq( - userRollup.getAssertion(latestConfirmed).status == AssertionStatus.Confirmed, - true - ); + assertEq(userRollup.getAssertion(latestConfirmed).status == AssertionStatus.Confirmed, true); } function testSuccessPause() public { @@ -239,11 +219,7 @@ contract RollupTest is Test { } function testConfirmAssertionWhenPaused() public { - ( - bytes32 assertionHash, - ExecutionState memory state, - uint64 inboxcount - ) = testSuccessCreateAssertion(); + (bytes32 assertionHash, ExecutionState memory state, uint64 inboxcount) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(owner); @@ -292,14 +268,7 @@ contract RollupTest is Test { userRollup.removeWhitelistAfterFork(); } - function testSuccessCreateAssertion() - public - returns ( - bytes32, - ExecutionState memory, - uint64 - ) - { + function testSuccessCreateAssertion() public returns (bytes32, ExecutionState memory, uint64) { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -347,14 +316,7 @@ contract RollupTest is Test { assertEq(userRollup.getStakerAddress(userRollup.getStaker(validator1).index), validator1); } - function testSuccessCreateErroredAssertions() - public - returns ( - bytes32, - ExecutionState memory, - uint64 - ) - { + function testSuccessCreateErroredAssertions() public returns (bytes32, ExecutionState memory, uint64) { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -575,12 +537,8 @@ contract RollupTest is Test { ExecutionState memory afterState2; afterState2.machineStatus = MachineStatus.FINISHED; - afterState2.globalState.bytes32Vals[0] = keccak256( - abi.encodePacked(FIRST_ASSERTION_BLOCKHASH) - ); // blockhash - afterState2.globalState.bytes32Vals[1] = keccak256( - abi.encodePacked(FIRST_ASSERTION_SENDROOT) - ); // sendroot + afterState2.globalState.bytes32Vals[0] = keccak256(abi.encodePacked(FIRST_ASSERTION_BLOCKHASH)); // blockhash + afterState2.globalState.bytes32Vals[1] = keccak256(abi.encodePacked(FIRST_ASSERTION_SENDROOT)); // sendroot afterState2.globalState.u64Vals[0] = 1; // inbox count afterState2.globalState.u64Vals[1] = 0; // modify the state @@ -624,7 +582,7 @@ contract RollupTest is Test { } function testRevertConfirmWrongInput() public { - (bytes32 assertionHash1, , ) = testSuccessCreateAssertion(); + (bytes32 assertionHash1,,) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -645,19 +603,8 @@ contract RollupTest is Test { ); } - function testSuccessConfirmUnchallengedAssertions() - public - returns ( - bytes32, - ExecutionState memory, - uint64 - ) - { - ( - bytes32 assertionHash, - ExecutionState memory state, - uint64 inboxcount - ) = testSuccessCreateAssertion(); + function testSuccessConfirmUnchallengedAssertions() public returns (bytes32, ExecutionState memory, uint64) { + (bytes32 assertionHash, ExecutionState memory state, uint64 inboxcount) = testSuccessCreateAssertion(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -679,12 +626,8 @@ contract RollupTest is Test { } function testSuccessRemoveWhitelistAfterValidatorAfk() public { - (bytes32 assertionHash, , ) = testSuccessConfirmUnchallengedAssertions(); - vm.roll( - userRollup.getAssertion(assertionHash).createdAtBlock + - userRollup.VALIDATOR_AFK_BLOCKS() + - 1 - ); + (bytes32 assertionHash,,) = testSuccessConfirmUnchallengedAssertions(); + vm.roll(userRollup.getAssertion(assertionHash).createdAtBlock + userRollup.VALIDATOR_AFK_BLOCKS() + 1); userRollup.removeWhitelistAfterValidatorAfk(); } @@ -694,7 +637,7 @@ contract RollupTest is Test { } function testRevertConfirmSiblingedAssertions() public { - (, , , , , bytes32 assertionHash, ) = testSuccessCreateSecondChild(); + (,,,,, bytes32 assertionHash,) = testSuccessCreateSecondChild(); vm.roll(userRollup.getAssertion(genesisHash).firstChildBlock + CONFIRM_PERIOD_BLOCKS + 1); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.prank(validator1); @@ -746,9 +689,7 @@ contract RollupTest is Test { states = fillStatesInBetween(h0, h1, LAYERZERO_BLOCKEDGE_HEIGHT + 1); } - bytes32 root = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1) - ); + bytes32 root = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1)); data.e1Id = challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -759,19 +700,12 @@ contract RollupTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), ExecutionStateData(data.beforeState, bytes32(0), bytes32(0)), - ExecutionStateData( - data.afterState1, - genesisHash, - userRollup.bridge().sequencerInboxAccs(0) + ExecutionStateData(data.afterState1, genesisHash, userRollup.bridge().sequencerInboxAccs(0)) ) - ) }) ); } @@ -789,9 +723,7 @@ contract RollupTest is Test { states = fillStatesInBetween(h0, h1, LAYERZERO_BLOCKEDGE_HEIGHT + 1); } - bytes32 root = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1) - ); + bytes32 root = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, LAYERZERO_BLOCKEDGE_HEIGHT + 1)); bytes32 e2Id = challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -802,30 +734,19 @@ contract RollupTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), ExecutionStateData(data.beforeState, bytes32(0), bytes32(0)), - ExecutionStateData( - data.afterState2, - genesisHash, - userRollup.bridge().sequencerInboxAccs(0) + ExecutionStateData(data.afterState2, genesisHash, userRollup.bridge().sequencerInboxAccs(0)) ) - ) }) ); return (data.e1Id, e2Id); } - function fillStatesInBetween( - bytes32 start, - bytes32 end, - uint256 totalCount - ) internal returns (bytes32[] memory) { + function fillStatesInBetween(bytes32 start, bytes32 end, uint256 totalCount) internal returns (bytes32[] memory) { bytes32[] memory innerStates = rand.hashes(totalCount - 2); bytes32[] memory states = new bytes32[](totalCount); @@ -968,30 +889,15 @@ contract RollupTest is Test { userRollup.addToDeposit(sequencer, 1); } - function testSuccessCreateSecondAssertion() - public - returns ( - bytes32, - bytes32, - ExecutionState memory, - bytes32 - ) - { - ( - bytes32 prevHash, - ExecutionState memory beforeState, - uint64 prevInboxCount - ) = testSuccessCreateAssertion(); + function testSuccessCreateSecondAssertion() public returns (bytes32, bytes32, ExecutionState memory, bytes32) { + (bytes32 prevHash, ExecutionState memory beforeState, uint64 prevInboxCount) = testSuccessCreateAssertion(); ExecutionState memory afterState; afterState.machineStatus = MachineStatus.FINISHED; afterState.globalState.u64Vals[0] = prevInboxCount; bytes32 inboxAcc = userRollup.bridge().sequencerInboxAccs(1); // 1 because we moved the position within message - bytes32 expectedAssertionHash2 = RollupLib.assertionHash({ - parentAssertionHash: prevHash, - afterState: afterState, - inboxAcc: inboxAcc - }); + bytes32 expectedAssertionHash2 = + RollupLib.assertionHash({parentAssertionHash: prevHash, afterState: afterState, inboxAcc: inboxAcc}); bytes32 prevInboxAcc = userRollup.bridge().sequencerInboxAccs(0); vm.roll(block.number + 75); vm.prank(validator1); @@ -1017,11 +923,8 @@ contract RollupTest is Test { } function testRevertCreateChildReducedStake() public { - ( - bytes32 prevHash, - ExecutionState memory beforeState, - uint64 prevInboxCount - ) = testSuccessConfirmUnchallengedAssertions(); + (bytes32 prevHash, ExecutionState memory beforeState, uint64 prevInboxCount) = + testSuccessConfirmUnchallengedAssertions(); vm.prank(validator1); userRollup.reduceDeposit(1); @@ -1059,7 +962,7 @@ contract RollupTest is Test { } function testSuccessFastConfirmNext() public { - (bytes32 assertionHash, , ) = testSuccessCreateAssertion(); + (bytes32 assertionHash,,) = testSuccessCreateAssertion(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); assertEq(userRollup.latestConfirmed(), genesisHash); vm.prank(anyTrustFastConfirmer); @@ -1068,12 +971,8 @@ contract RollupTest is Test { } function testSuccessFastConfirmSkipOne() public { - ( - bytes32 prevHash, - bytes32 assertionHash, - ExecutionState memory afterState, - bytes32 inboxAcc - ) = testSuccessCreateSecondAssertion(); + (bytes32 prevHash, bytes32 assertionHash, ExecutionState memory afterState, bytes32 inboxAcc) = + testSuccessCreateSecondAssertion(); assertEq(userRollup.latestConfirmed() != prevHash, true); vm.prank(anyTrustFastConfirmer); userRollup.fastConfirmAssertion(assertionHash, prevHash, afterState, inboxAcc); @@ -1081,7 +980,7 @@ contract RollupTest is Test { } function testRevertFastConfirmNotPending() public { - (bytes32 assertionHash, , ) = testSuccessConfirmUnchallengedAssertions(); + (bytes32 assertionHash,,) = testSuccessConfirmUnchallengedAssertions(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.expectRevert("NOT_PENDING"); vm.prank(anyTrustFastConfirmer); @@ -1089,17 +988,16 @@ contract RollupTest is Test { } function testRevertFastConfirmNotConfirmer() public { - (bytes32 assertionHash, , ) = testSuccessCreateAssertion(); + (bytes32 assertionHash,,) = testSuccessCreateAssertion(); bytes32 inboxAccs = userRollup.bridge().sequencerInboxAccs(0); vm.expectRevert("NOT_FAST_CONFIRMER"); userRollup.fastConfirmAssertion(assertionHash, genesisHash, firstState, inboxAccs); } - function _testFastConfirmNewAssertion( - address by, - string memory err, - bool isCreated - ) internal returns (AssertionInputs memory, bytes32) { + function _testFastConfirmNewAssertion(address by, string memory err, bool isCreated) + internal + returns (AssertionInputs memory, bytes32) + { uint64 inboxcount = uint64(_createNewBatch()); ExecutionState memory beforeState; beforeState.machineStatus = MachineStatus.FINISHED; @@ -1145,10 +1043,7 @@ contract RollupTest is Test { vm.expectRevert(bytes(err)); } vm.prank(by); - userRollup.fastConfirmNewAssertion({ - assertion: assertion, - expectedAssertionHash: expectedAssertionHash - }); + userRollup.fastConfirmNewAssertion({assertion: assertion, expectedAssertionHash: expectedAssertionHash}); if (bytes(err).length == 0) { assertEq(userRollup.latestConfirmed(), expectedAssertionHash); } @@ -1168,22 +1063,15 @@ contract RollupTest is Test { } function testRevertFastConfirmNewAssertionConfirmed() public { - ( - AssertionInputs memory assertion, - bytes32 expectedAssertionHash - ) = _testFastConfirmNewAssertion(anyTrustFastConfirmer, "", true); + (AssertionInputs memory assertion, bytes32 expectedAssertionHash) = + _testFastConfirmNewAssertion(anyTrustFastConfirmer, "", true); vm.expectRevert("NOT_PENDING"); vm.prank(anyTrustFastConfirmer); - userRollup.fastConfirmNewAssertion({ - assertion: assertion, - expectedAssertionHash: expectedAssertionHash - }); + userRollup.fastConfirmNewAssertion({assertion: assertion, expectedAssertionHash: expectedAssertionHash}); } - bytes32 constant _IMPLEMENTATION_PRIMARY_SLOT = - 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; - bytes32 constant _IMPLEMENTATION_SECONDARY_SLOT = - 0x2b1dbce74324248c222f0ec2d5ed7bd323cfc425b336f0253c5ccfda7265546d; + bytes32 constant _IMPLEMENTATION_PRIMARY_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; + bytes32 constant _IMPLEMENTATION_SECONDARY_SLOT = 0x2b1dbce74324248c222f0ec2d5ed7bd323cfc425b336f0253c5ccfda7265546d; // should only allow admin to upgrade primary logic function testRevertUpgradeNotAdmin() public { @@ -1213,64 +1101,48 @@ contract RollupTest is Test { } function testSuccessUpgradePrimary() public { - address ori_secondary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) - ); + address ori_secondary_impl = + address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); RollupAdminLogic newAdminLogicImpl = new RollupAdminLogic(); vm.prank(owner); adminRollup.upgradeTo(address(newAdminLogicImpl)); - address new_primary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) - ); - address new_secondary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) - ); + address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); + address new_secondary_impl = + address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); assertEq(address(newAdminLogicImpl), new_primary_impl); assertEq(ori_secondary_impl, new_secondary_impl); } function testSuccessUpgradePrimaryAndCall() public { - address ori_secondary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) - ); + address ori_secondary_impl = + address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); RollupAdminLogic newAdminLogicImpl = new RollupAdminLogic(); vm.prank(owner); - adminRollup.upgradeToAndCall( - address(newAdminLogicImpl), - abi.encodeCall(adminRollup.pause, ()) - ); + adminRollup.upgradeToAndCall(address(newAdminLogicImpl), abi.encodeCall(adminRollup.pause, ())); assertEq(adminRollup.paused(), true); - address new_primary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) - ); - address new_secondary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) - ); + address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); + address new_secondary_impl = + address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); assertEq(address(newAdminLogicImpl), new_primary_impl); assertEq(ori_secondary_impl, new_secondary_impl); } function testSuccessUpgradeSecondary() public { - address ori_primary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) - ); + address ori_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); RollupUserLogic newUserLogicImpl = new RollupUserLogic(); vm.prank(owner); adminRollup.upgradeSecondaryTo(address(newUserLogicImpl)); - address new_primary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT))) - ); - address new_secondary_impl = address( - uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT))) - ); + address new_primary_impl = address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_PRIMARY_SLOT)))); + address new_secondary_impl = + address(uint160(uint256(vm.load(address(userRollup), _IMPLEMENTATION_SECONDARY_SLOT)))); assertEq(ori_primary_impl, new_primary_impl); assertEq(address(newUserLogicImpl), new_secondary_impl); @@ -1323,10 +1195,7 @@ contract RollupTest is Test { function testExecutionStateHash() public { ExecutionState memory es = ExecutionState( - GlobalState( - [rand.hash(), rand.hash()], - [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] - ), + GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), MachineStatus.FINISHED ); bytes32 expectedHash = keccak256(abi.encodePacked(es.machineStatus, es.globalState.hash())); @@ -1336,20 +1205,11 @@ contract RollupTest is Test { function testAssertionHash() public { bytes32 parentHash = rand.hash(); ExecutionState memory es = ExecutionState( - GlobalState( - [rand.hash(), rand.hash()], - [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] - ), + GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), MachineStatus.FINISHED ); bytes32 inboxAcc = rand.hash(); - bytes32 expectedHash = keccak256( - abi.encodePacked(parentHash, RollupLib.executionStateHash(es), inboxAcc) - ); - assertEq( - RollupLib.assertionHash(parentHash, es, inboxAcc), - expectedHash, - "Unexpected hash" - ); + bytes32 expectedHash = keccak256(abi.encodePacked(parentHash, RollupLib.executionStateHash(es), inboxAcc)); + assertEq(RollupLib.assertionHash(parentHash, es, inboxAcc), expectedHash, "Unexpected hash"); } } diff --git a/contracts/test/challengeV2/ArrayUtilsLib.t.sol b/contracts/test/challengeV2/ArrayUtilsLib.t.sol index 11e9b003b..2052f71d7 100644 --- a/contracts/test/challengeV2/ArrayUtilsLib.t.sol +++ b/contracts/test/challengeV2/ArrayUtilsLib.t.sol @@ -14,7 +14,7 @@ contract ArrayUtilsLibTest is Test { function areEqual(bytes32[] memory a, bytes32[] memory b) internal { assertEq(a.length, b.length, "Len unequal"); - for (uint256 i = 0; i < a.length; i++) { + for (uint i = 0; i < a.length; i++) { assertEq(a[i], b[i]); } } @@ -57,7 +57,7 @@ contract ArrayUtilsLibTest is Test { function testSliceAll() public { bytes32[] memory o = random.hashes(5); - + bytes32[] memory s = ArrayUtilsLib.slice(o, 0, o.length); areEqual(o, s); } diff --git a/contracts/test/challengeV2/ChallengeEdgeLib.t.sol b/contracts/test/challengeV2/ChallengeEdgeLib.t.sol index 72c34add6..6cea9dfe2 100644 --- a/contracts/test/challengeV2/ChallengeEdgeLib.t.sol +++ b/contracts/test/challengeV2/ChallengeEdgeLib.t.sol @@ -36,14 +36,7 @@ contract ChallengeEdgeLibAccess { bytes32 endHistoryRoot, uint256 endHeight ) public pure { - return - ChallengeEdgeLib.newEdgeChecks( - originId, - startHistoryRoot, - startHeight, - endHistoryRoot, - endHeight - ); + return ChallengeEdgeLib.newEdgeChecks(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight); } function newLayerZeroEdge( @@ -56,17 +49,9 @@ contract ChallengeEdgeLibAccess { address staker, uint8 level ) public view returns (ChallengeEdge memory) { - return - ChallengeEdgeLib.newLayerZeroEdge( - originId, - startHistoryRoot, - startHeight, - endHistoryRoot, - endHeight, - claimId, - staker, - level - ); + return ChallengeEdgeLib.newLayerZeroEdge( + originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight, claimId, staker, level + ); } function newChildEdge( @@ -77,15 +62,7 @@ contract ChallengeEdgeLibAccess { uint256 endHeight, uint8 level ) public view returns (ChallengeEdge memory) { - return - ChallengeEdgeLib.newChildEdge( - originId, - startHistoryRoot, - startHeight, - endHistoryRoot, - endHeight, - level - ); + return ChallengeEdgeLib.newChildEdge(originId, startHistoryRoot, startHeight, endHistoryRoot, endHeight, level); } function mutualIdComponent( @@ -95,14 +72,7 @@ contract ChallengeEdgeLibAccess { bytes32 startHistoryRoot, uint256 endHeight ) public pure returns (bytes32) { - return - ChallengeEdgeLib.mutualIdComponent( - level, - originId, - startHeight, - startHistoryRoot, - endHeight - ); + return ChallengeEdgeLib.mutualIdComponent(level, originId, startHeight, startHistoryRoot, endHeight); } function mutualId() public view returns (bytes32) { @@ -121,15 +91,7 @@ contract ChallengeEdgeLibAccess { uint256 endHeight, bytes32 endHistoryRoot ) public pure returns (bytes32) { - return - ChallengeEdgeLib.idComponent( - level, - originId, - startHeight, - startHistoryRoot, - endHeight, - endHistoryRoot - ); + return ChallengeEdgeLib.idComponent(level, originId, startHeight, startHistoryRoot, endHeight, endHistoryRoot); } function idMem(ChallengeEdge memory edge) public pure returns (bytes32) { @@ -173,14 +135,7 @@ contract ChallengeEdgeLibTest is Test { Random rand = new Random(); uint8 constant NUM_BIGSTEP_LEVEL = 3; - function randCheckArgs() - internal - returns ( - bytes32, - bytes32, - bytes32 - ) - { + function randCheckArgs() internal returns (bytes32, bytes32, bytes32) { return (rand.hash(), rand.hash(), rand.hash()); } @@ -197,14 +152,14 @@ contract ChallengeEdgeLibTest is Test { } function testEdgeChecksStartRoot() public { - (bytes32 originId, , bytes32 endRoot) = randCheckArgs(); + (bytes32 originId,, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyStartRoot.selector)); access.newEdgeChecks(originId, 0, 10, endRoot, 15); } function testEdgeChecksEndRoot() public { - (bytes32 originId, bytes32 startRoot, ) = randCheckArgs(); + (bytes32 originId, bytes32 startRoot,) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyEndRoot.selector)); access.newEdgeChecks(originId, startRoot, 10, 0, 15); @@ -229,16 +184,8 @@ contract ChallengeEdgeLibTest is Test { bytes32 claimId = rand.hash(); address staker = rand.addr(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); - ChallengeEdge memory e = access.newLayerZeroEdge( - originId, - startRoot, - 10, - endRoot, - 15, - claimId, - staker, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory e = + access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1); assertEq(e.originId, originId, "Origin id"); assertEq(e.startHeight, 10, "Start height"); assertEq(e.startHistoryRoot, startRoot, "Start root"); @@ -254,15 +201,7 @@ contract ChallengeEdgeLibTest is Test { assertTrue(e.level == NUM_BIGSTEP_LEVEL + 1, "EType"); assertEq( access.mutualIdMem(e), - keccak256( - abi.encodePacked( - e.level, - e.originId, - e.startHeight, - e.startHistoryRoot, - e.endHeight - ) - ), + keccak256(abi.encodePacked(e.level, e.originId, e.startHeight, e.startHistoryRoot, e.endHeight)), "Id mem" ); } @@ -272,16 +211,7 @@ contract ChallengeEdgeLibTest is Test { bytes32 claimId = rand.hash(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyStaker.selector)); - access.newLayerZeroEdge( - originId, - startRoot, - 10, - endRoot, - 15, - claimId, - address(0), - NUM_BIGSTEP_LEVEL + 1 - ); + access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, address(0), NUM_BIGSTEP_LEVEL + 1); } function testNewLayerZeroEdgeZeroClaimId() public { @@ -289,29 +219,13 @@ contract ChallengeEdgeLibTest is Test { address staker = rand.addr(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); vm.expectRevert(abi.encodeWithSelector(EmptyClaimId.selector)); - access.newLayerZeroEdge( - originId, - startRoot, - 10, - endRoot, - 15, - 0, - staker, - NUM_BIGSTEP_LEVEL + 1 - ); + access.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, 0, staker, NUM_BIGSTEP_LEVEL + 1); } function testNewChildEdge() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess access = new ChallengeEdgeLibAccess(); - ChallengeEdge memory e = access.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 15, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory e = access.newChildEdge(originId, startRoot, 10, endRoot, 15, NUM_BIGSTEP_LEVEL + 1); assertEq(e.originId, originId, "Origin id"); assertEq(e.startHeight, 10, "Start height"); assertEq(e.startHistoryRoot, startRoot, "Start root"); @@ -338,25 +252,10 @@ contract ChallengeEdgeLibTest is Test { assertFalse(layerZero.exists(), "Layer zero exists"); assertFalse(child.exists(), "Child exists"); - ChallengeEdge memory layerZeroEdge = layerZero.newLayerZeroEdge( - originId, - startRoot, - 10, - endRoot, - 15, - claimId, - staker, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory layerZeroEdge = + layerZero.newLayerZeroEdge(originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1); layerZero.setChallengeEdge(layerZeroEdge); - ChallengeEdge memory childEdge = child.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = child.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); assertTrue(layerZero.exists(), "Layer zero exists"); @@ -378,24 +277,11 @@ contract ChallengeEdgeLibTest is Test { ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); ChallengeEdge memory layerZeroEdge = ChallengeEdgeLib.newLayerZeroEdge( - originId, - startRoot, - 10, - endRoot, - 15, - claimId, - staker, - NUM_BIGSTEP_LEVEL + 1 + originId, startRoot, 10, endRoot, 15, claimId, staker, NUM_BIGSTEP_LEVEL + 1 ); layerZero.setChallengeEdge(layerZeroEdge); - ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = + ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); assertEq(layerZero.length(), 5, "L-zero len"); @@ -414,14 +300,8 @@ contract ChallengeEdgeLibTest is Test { function testSetChildren() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = + ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); bytes32 lowerChildId = rand.hash(); @@ -437,41 +317,22 @@ contract ChallengeEdgeLibTest is Test { function testSetChildrenTwice() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = + ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); bytes32 lowerChildId = rand.hash(); bytes32 upperChildId = rand.hash(); child.setChildren(lowerChildId, upperChildId); - vm.expectRevert( - abi.encodeWithSelector( - ChildrenAlreadySet.selector, - child.id(), - lowerChildId, - upperChildId - ) - ); + vm.expectRevert(abi.encodeWithSelector(ChildrenAlreadySet.selector, child.id(), lowerChildId, upperChildId)); child.setChildren(lowerChildId, upperChildId); } function testSetConfirmed() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = + ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); vm.roll(137); @@ -484,20 +345,12 @@ contract ChallengeEdgeLibTest is Test { function testSetConfirmedTwice() public { (bytes32 originId, bytes32 startRoot, bytes32 endRoot) = randCheckArgs(); ChallengeEdgeLibAccess child = new ChallengeEdgeLibAccess(); - ChallengeEdge memory childEdge = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 10, - endRoot, - 17, - NUM_BIGSTEP_LEVEL + 1 - ); + ChallengeEdge memory childEdge = + ChallengeEdgeLib.newChildEdge(originId, startRoot, 10, endRoot, 17, NUM_BIGSTEP_LEVEL + 1); child.setChallengeEdge(childEdge); child.setConfirmed(); - vm.expectRevert( - abi.encodeWithSelector(EdgeNotPending.selector, child.id(), EdgeStatus.Confirmed) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, child.id(), EdgeStatus.Confirmed)); child.setConfirmed(); } diff --git a/contracts/test/challengeV2/EdgeChallengeManager.t.sol b/contracts/test/challengeV2/EdgeChallengeManager.t.sol index 56b2d02b1..23e666061 100644 --- a/contracts/test/challengeV2/EdgeChallengeManager.t.sol +++ b/contracts/test/challengeV2/EdgeChallengeManager.t.sol @@ -14,21 +14,15 @@ import "../ERC20Mock.sol"; import "./StateTools.sol"; contract MockOneStepProofEntry is IOneStepProofEntry { - function proveOneStep( - ExecutionContext calldata, - uint256, - bytes32, - bytes calldata proof - ) external pure returns (bytes32 afterHash) { - return bytes32(proof); - } - - function getMachineHash(ExecutionState calldata execState) + function proveOneStep(ExecutionContext calldata, uint256, bytes32, bytes calldata proof) external pure - override - returns (bytes32) + returns (bytes32 afterHash) { + return bytes32(proof); + } + + function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return GlobalStateLib.hash(execState.globalState); } @@ -39,8 +33,7 @@ contract EdgeChallengeManagerTest is Test { Random rand = new Random(); bytes32 genesisBlockHash = rand.hash(); - ExecutionState genesisState = - StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); + ExecutionState genesisState = StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); bytes32 genesisStateHash = StateToolsLib.mockMachineHash(genesisState); bytes32 genesisAfterStateHash = RollupLib.executionStateHash(genesisState); ExecutionStateData genesisStateData = ExecutionStateData(genesisState, bytes32(0), bytes32(0)); @@ -83,14 +76,7 @@ contract EdgeChallengeManagerTest is Test { return (full, exp); } - function deploy() - internal - returns ( - MockAssertionChain, - EdgeChallengeManager, - bytes32 - ) - { + function deploy() internal returns (MockAssertionChain, EdgeChallengeManager, bytes32) { MockAssertionChain assertionChain = new MockAssertionChain(); EdgeChallengeManager challengeManagerTemplate = new EdgeChallengeManager(); EdgeChallengeManager challengeManager = EdgeChallengeManager( @@ -106,10 +92,15 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, new MockOneStepProofEntry(), - 2**5, - 2**5, - 2**5, - new ERC20Mock("StakeToken", "ST", address(this), 1000000 ether), + 2 ** 5, + 2 ** 5, + 2 ** 5, + new ERC20Mock( + "StakeToken", + "ST", + address(this), + 1000000 ether + ), miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL @@ -117,13 +108,8 @@ contract EdgeChallengeManagerTest is Test { challengeManager.stakeToken().approve(address(challengeManager), type(uint256).max); - genesisAssertionHash = assertionChain.addAssertionUnsafe( - 0, - genesisHeight, - inboxMsgCountGenesis, - genesisState, - 0 - ); + genesisAssertionHash = + assertionChain.addAssertionUnsafe(0, genesisHeight, inboxMsgCountGenesis, genesisState, 0); return (assertionChain, challengeManager, genesisAssertionHash); } @@ -131,19 +117,30 @@ contract EdgeChallengeManagerTest is Test { MockAssertionChain assertionChain = new MockAssertionChain(); EdgeChallengeManager emt = new EdgeChallengeManager(); EdgeChallengeManager ecm = EdgeChallengeManager( - address(new TransparentUpgradeableProxy(address(emt), address(new ProxyAdmin()), "")) + address( + new TransparentUpgradeableProxy( + address(emt), + address(new ProxyAdmin()), + "" + ) + ) ); MockOneStepProofEntry osp = new MockOneStepProofEntry(); - ERC20Mock erc20 = new ERC20Mock("StakeToken", "ST", address(this), 1000000 ether); + ERC20Mock erc20 = new ERC20Mock( + "StakeToken", + "ST", + address(this), + 1000000 ether + ); vm.expectRevert(abi.encodeWithSelector(EmptyAssertionChain.selector)); ecm.initialize( IAssertionChain(address(0)), challengePeriodBlock, osp, - 2**5, - 2**5, - 2**5, + 2 ** 5, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, @@ -155,9 +152,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, IOneStepProofEntry(address(0)), - 2**5, - 2**5, - 2**5, + 2 ** 5, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, @@ -166,16 +163,7 @@ contract EdgeChallengeManagerTest is Test { vm.expectRevert(abi.encodeWithSelector(EmptyChallengePeriod.selector)); ecm.initialize( - assertionChain, - 0, - osp, - 2**5, - 2**5, - 2**5, - erc20, - miniStakeVal, - excessStakeReceiver, - NUM_BIGSTEP_LEVEL + assertionChain, 0, osp, 2 ** 5, 2 ** 5, 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL ); vm.expectRevert(abi.encodeWithSelector(EmptyStakeReceiver.selector)); @@ -183,51 +171,51 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2**5, - 2**5, - 2**5, + 2 ** 5, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, address(0), NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - (2**5) + 1, - 2**5, - 2**5, + (2 ** 5) + 1, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - 2**5, - (2**5) + 1, - 2**5, + 2 ** 5, + (2 ** 5) + 1, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, NUM_BIGSTEP_LEVEL ); - vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2**5) + 1)); + vm.expectRevert(abi.encodeWithSelector(NotPowerOfTwo.selector, (2 ** 5) + 1)); ecm.initialize( assertionChain, challengePeriodBlock, osp, - 2**5, - 2**5, - (2**5) + 1, + 2 ** 5, + 2 ** 5, + (2 ** 5) + 1, erc20, miniStakeVal, excessStakeReceiver, @@ -239,9 +227,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2**5, - 2**5, - 2**5, + 2 ** 5, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, @@ -253,9 +241,9 @@ contract EdgeChallengeManagerTest is Test { assertionChain, challengePeriodBlock, osp, - 2**5, - 2**5, - 2**5, + 2 ** 5, + 2 ** 5, + 2 ** 5, erc20, miniStakeVal, excessStakeReceiver, @@ -276,85 +264,49 @@ contract EdgeChallengeManagerTest is Test { } function deployAndInit() internal returns (EdgeInitData memory) { - ( - MockAssertionChain assertionChain, - EdgeChallengeManager challengeManager, - bytes32 genesis - ) = deploy(); + (MockAssertionChain assertionChain, EdgeChallengeManager challengeManager, bytes32 genesis) = deploy(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, - GlobalStateLib.getInboxPosition(genesisState.globalState), - h1, - MachineStatus.FINISHED + rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED ); ExecutionState memory a2State = StateToolsLib.randomState( - rand, - GlobalStateLib.getInboxPosition(genesisState.globalState), - h2, - MachineStatus.FINISHED + rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h2, MachineStatus.FINISHED ); // add one since heights are zero indexed in the history states bytes32 a1 = assertionChain.addAssertion( - genesis, - genesisHeight + height1, - inboxMsgCountAssertion, - genesisState, - a1State, - 0 + genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a1State, 0 ); bytes32 a2 = assertionChain.addAssertion( - genesis, - genesisHeight + height1, - inboxMsgCountAssertion, - genesisState, - a2State, - 0 - ); - - return - EdgeInitData({ - assertionChain: assertionChain, - challengeManager: challengeManager, - genesis: genesis, - a1: a1, - a2: a2, - a1State: a1State, - a2State: a2State, - a1Data: ExecutionStateData(a1State, genesis, bytes32(0)), - a2Data: ExecutionStateData(a2State, genesis, bytes32(0)) - }); + genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a2State, 0 + ); + + return EdgeInitData({ + assertionChain: assertionChain, + challengeManager: challengeManager, + genesis: genesis, + a1: a1, + a2: a2, + a1State: a1State, + a2State: a2State, + a1Data: ExecutionStateData(a1State, genesis, bytes32(0)), + a2Data: ExecutionStateData(a2State, genesis, bytes32(0)) + }); } function testRevertBlockNoFork() public { - ( - MockAssertionChain assertionChain, - EdgeChallengeManager challengeManager, - bytes32 genesis - ) = deploy(); + (MockAssertionChain assertionChain, EdgeChallengeManager challengeManager, bytes32 genesis) = deploy(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, - GlobalStateLib.getInboxPosition(genesisState.globalState), - h1, - MachineStatus.FINISHED + rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED ); bytes32 a1 = assertionChain.addAssertion( - genesis, - genesisHeight + height1, - inboxMsgCountAssertion, - genesisState, - a1State, - 0 + genesis, genesisHeight + height1, inboxMsgCountAssertion, genesisState, a1State, 0 ); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(a1State), height1); vm.expectRevert(abi.encodeWithSelector(AssertionNoSibling.selector)); challengeManager.createLayerZeroEdge( @@ -366,15 +318,12 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), genesisStateData, ExecutionStateData(a1State, genesisAssertionHash, bytes32(0)) - ) + ) }) ); } @@ -382,11 +331,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockInvalidHeight() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); ei.challengeManager.createLayerZeroEdge( @@ -398,15 +344,12 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), genesisStateData, ei.a1Data - ) + ) }) ); } @@ -414,11 +357,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockNoProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); vm.expectRevert(abi.encodeWithSelector(EmptyEdgeSpecificProof.selector)); ei.challengeManager.createLayerZeroEdge( @@ -430,7 +370,7 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: "" }) ); @@ -439,11 +379,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertBlockInvalidProof() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -455,12 +392,10 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), - genesisStateData, - ei.a1Data - ) + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), genesisStateData, ei.a1Data + ) }) ); } @@ -468,11 +403,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidHash() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); vm.expectRevert("INVALID_ASSERTION_HASH"); ei.challengeManager.createLayerZeroEdge( @@ -484,12 +416,10 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), + ), proof: abi.encode( - ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), - genesisStateData, - ei.a1Data - ) + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), 0), genesisStateData, ei.a1Data + ) }) ); } @@ -497,11 +427,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidHashPrev() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); vm.expectRevert("INVALID_ASSERTION_HASH"); ei.challengeManager.createLayerZeroEdge( @@ -513,35 +440,22 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), - ei.a2Data, - ei.a1Data - ) + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), ei.a2Data, ei.a1Data + ) }) ); } function testCanCreateEdgeWithStake() public - returns ( - EdgeInitData memory, - bytes32[] memory, - bytes32[] memory, - bytes32 - ) + returns (EdgeInitData memory, bytes32[] memory, bytes32[] memory, bytes32) { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a1State), - height1 - ); + (bytes32[] memory states, bytes32[] memory exp) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a1State), height1); IERC20 stakeToken = ei.challengeManager.stakeToken(); uint256 beforeBalance = stakeToken.balanceOf(address(this)); @@ -554,15 +468,12 @@ contract EdgeChallengeManagerTest is Test { prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states, 0, 1), ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - states.length - 1 ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), states.length - 1), genesisStateData, ei.a1Data - ) + ) }) ); uint256 afterBalance = stakeToken.balanceOf(address(this)); @@ -573,23 +484,14 @@ contract EdgeChallengeManagerTest is Test { ChallengeEdge memory edge = ei.challengeManager.getEdge(edgeId); assertEq( ei.challengeManager.calculateMutualId( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight ), edge.mutualIdMem(), "Mutual id" ); assertEq( ei.challengeManager.calculateEdgeId( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight, - edge.endHistoryRoot + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight, edge.endHistoryRoot ), edge.idMem(), "Mutual id" @@ -598,27 +500,20 @@ contract EdgeChallengeManagerTest is Test { assertEq(ei.challengeManager.hasRival(edgeId), false, "Edge has rival"); assertEq(ei.challengeManager.confirmedRival(edgeId), bytes32(0), "Confirmed rival"); assertEq(ei.challengeManager.hasLengthOneRival(edgeId), false, "Has length one rival"); - assertEq( - ei.challengeManager.firstRival(edge.mutualIdMem()), - EdgeChallengeManagerLib.UNRIVALED, - "Unrivaled" - ); + assertEq(ei.challengeManager.firstRival(edge.mutualIdMem()), EdgeChallengeManagerLib.UNRIVALED, "Unrivaled"); return (ei, states, exp, edgeId); } function testCanConfirmByTime() public { - (EdgeInitData memory ei, , , bytes32 edgeId) = testCanCreateEdgeWithStake(); + (EdgeInitData memory ei,,, bytes32 edgeId) = testCanCreateEdgeWithStake(); vm.roll(challengePeriodBlock + 2); bytes32[] memory ancestorEdges = new bytes32[](0); ei.challengeManager.confirmEdgeByTime(edgeId, ancestorEdges, ei.a1Data); - assertTrue( - ei.challengeManager.getEdge(edgeId).status == EdgeStatus.Confirmed, - "Edge confirmed" - ); + assertTrue(ei.challengeManager.getEdge(edgeId).status == EdgeStatus.Confirmed, "Edge confirmed"); } function testCanConfirmByTimeNotBlock() public { @@ -629,15 +524,8 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -657,24 +545,13 @@ contract EdgeChallengeManagerTest is Test { bytes32[] memory ancestorEdges = new bytes32[](0); vm.expectRevert(abi.encodeWithSelector(EdgeTypeNotBlock.selector, 1)); - ei.challengeManager.confirmEdgeByTime( - bsbd.edges1[5].lowerChildId, - ancestorEdges, - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(bsbd.edges1[5].lowerChildId, ancestorEdges, ei.a1Data); } function testCanConfirmByTimeLayerZero() public { EdgeInitData memory ei = deployAndInit(); - (, , BisectionChildren[6] memory blockEdges1, ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) + (,, BisectionChildren[6] memory blockEdges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); vm.roll(challengePeriodBlock + 2); @@ -683,37 +560,20 @@ contract EdgeChallengeManagerTest is Test { ChallengeEdge memory ce = ei.challengeManager.getEdge(blockEdges1[0].lowerChildId); vm.expectRevert( - abi.encodeWithSelector( - EdgeNotLayerZero.selector, - blockEdges1[0].lowerChildId, - ce.staker, - ce.claimId - ) - ); - ei.challengeManager.confirmEdgeByTime( - blockEdges1[0].lowerChildId, - ancestorEdges, - ei.a1Data + abi.encodeWithSelector(EdgeNotLayerZero.selector, blockEdges1[0].lowerChildId, ce.staker, ce.claimId) ); + ei.challengeManager.confirmEdgeByTime(blockEdges1[0].lowerChildId, ancestorEdges, ei.a1Data); } function testCanConfirmByChildren() public returns (EdgeInitData memory, bytes32) { - ( - EdgeInitData memory ei, - bytes32[] memory states1, - , - bytes32 edge1Id - ) = testCanCreateEdgeWithStake(); + (EdgeInitData memory ei, bytes32[] memory states1,, bytes32 edge1Id) = testCanCreateEdgeWithStake(); vm.roll(block.number + 1); assertEq(ei.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); { - (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a2State), - height1 - ); + (bytes32[] memory states2, bytes32[] memory exp2) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a2State), height1); bytes32 edge2Id = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 0, @@ -722,19 +582,13 @@ contract EdgeChallengeManagerTest is Test { claimId: ei.a2, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states2, 1, states2.length) - ) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states2), - states2.length - 1 + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1), genesisStateData, ei.a2Data - ) + ) }) ); @@ -743,13 +597,7 @@ contract EdgeChallengeManagerTest is Test { assertEq(ei.challengeManager.timeUnrivaled(edge2Id), 0, "Edge2 timer"); } - BisectionChildren memory children = bisect( - ei.challengeManager, - edge1Id, - states1, - 16, - states1.length - 1 - ); + BisectionChildren memory children = bisect(ei.challengeManager, edge1Id, states1, 16, states1.length - 1); vm.roll(challengePeriodBlock + 5); @@ -759,10 +607,7 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByTime(children.upperChildId, ancestors, ei.a1Data); ei.challengeManager.confirmEdgeByChildren(edge1Id); - assertTrue( - ei.challengeManager.getEdge(edge1Id).status == EdgeStatus.Confirmed, - "Edge confirmed" - ); + assertTrue(ei.challengeManager.getEdge(edge1Id).status == EdgeStatus.Confirmed, "Edge confirmed"); return (ei, edge1Id); } @@ -770,11 +615,8 @@ contract EdgeChallengeManagerTest is Test { function testRevertConfirmAnotherRival() public { (EdgeInitData memory ei, bytes32 edge1Id) = testCanConfirmByChildren(); - (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(ei.a2State), - height1 - ); + (bytes32[] memory states2, bytes32[] memory exp2) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(ei.a2State), height1); bytes32 edge2Id = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 0, @@ -783,36 +625,18 @@ contract EdgeChallengeManagerTest is Test { claimId: ei.a2, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states2, 1, states2.length) - ) - ), - proof: abi.encode( - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states2), - states2.length - 1 + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) ), + proof: abi.encode( + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1), genesisStateData, ei.a2Data - ) + ) }) ); - BisectionChildren memory children = bisect( - ei.challengeManager, - edge2Id, - states2, - 16, - states2.length - 1 - ); - BisectionChildren memory children2 = bisect( - ei.challengeManager, - children.lowerChildId, - states2, - 8, - 16 - ); + BisectionChildren memory children = bisect(ei.challengeManager, edge2Id, states2, 16, states2.length - 1); + BisectionChildren memory children2 = bisect(ei.challengeManager, children.lowerChildId, states2, 8, 16); vm.roll(block.number + challengePeriodBlock + 5); bytes32[] memory ancestors = new bytes32[](2); ancestors[0] = children.lowerChildId; @@ -826,10 +650,7 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByTime(children.upperChildId, ancestors, ei.a2Data); vm.expectRevert(); // should not be able to confirm when a rival is already confirmed ei.challengeManager.confirmEdgeByChildren(edge2Id); - assertFalse( - ei.challengeManager.getEdge(edge1Id).status == - ei.challengeManager.getEdge(edge2Id).status - ); + assertFalse(ei.challengeManager.getEdge(edge1Id).status == ei.challengeManager.getEdge(edge2Id).status); assertTrue(edge1Id != edge2Id, "Same edge"); assertEq( ei.challengeManager.getEdge(edge1Id).mutualIdMem(), @@ -883,107 +704,43 @@ contract EdgeChallengeManagerTest is Test { // height 16 winningEdges[4] = bisect( - args.challengeManager, - winningEdges[5].lowerChildId, - args.winningLeaves, - 16, - args.winningLeaves.length - 1 + args.challengeManager, winningEdges[5].lowerChildId, args.winningLeaves, 16, args.winningLeaves.length - 1 ); losingEdges[4] = bisect( - args.challengeManager, - losingEdges[5].lowerChildId, - args.losingLeaves, - 16, - args.losingLeaves.length - 1 + args.challengeManager, losingEdges[5].lowerChildId, args.losingLeaves, 16, args.losingLeaves.length - 1 ); // height 8 - winningEdges[3] = bisect( - args.challengeManager, - winningEdges[4].lowerChildId, - args.winningLeaves, - 8, - 16 - ); - losingEdges[3] = bisect( - args.challengeManager, - losingEdges[4].lowerChildId, - args.losingLeaves, - 8, - 16 - ); + winningEdges[3] = bisect(args.challengeManager, winningEdges[4].lowerChildId, args.winningLeaves, 8, 16); + losingEdges[3] = bisect(args.challengeManager, losingEdges[4].lowerChildId, args.losingLeaves, 8, 16); // height 4 - winningEdges[2] = bisect( - args.challengeManager, - winningEdges[3].lowerChildId, - args.winningLeaves, - 4, - 8 - ); - losingEdges[2] = bisect( - args.challengeManager, - losingEdges[3].lowerChildId, - args.losingLeaves, - 4, - 8 - ); - - winningEdges[1] = bisect( - args.challengeManager, - winningEdges[2].lowerChildId, - args.winningLeaves, - 2, - 4 - ); - losingEdges[1] = bisect( - args.challengeManager, - losingEdges[2].lowerChildId, - args.losingLeaves, - 2, - 4 - ); + winningEdges[2] = bisect(args.challengeManager, winningEdges[3].lowerChildId, args.winningLeaves, 4, 8); + losingEdges[2] = bisect(args.challengeManager, losingEdges[3].lowerChildId, args.losingLeaves, 4, 8); + + winningEdges[1] = bisect(args.challengeManager, winningEdges[2].lowerChildId, args.winningLeaves, 2, 4); + losingEdges[1] = bisect(args.challengeManager, losingEdges[2].lowerChildId, args.losingLeaves, 2, 4); // height 2 - winningEdges[0] = bisect( - args.challengeManager, - winningEdges[1].lowerChildId, - args.winningLeaves, - 1, - 2 - ); + winningEdges[0] = bisect(args.challengeManager, winningEdges[1].lowerChildId, args.winningLeaves, 1, 2); if (!args.skipLast) { - losingEdges[0] = bisect( - args.challengeManager, - losingEdges[1].lowerChildId, - args.losingLeaves, - 1, - 2 - ); + losingEdges[0] = bisect(args.challengeManager, losingEdges[1].lowerChildId, args.losingLeaves, 1, 2); } return (winningEdges, losingEdges); } - function appendRandomStatesBetween( - bytes32[] memory currentStates, - bytes32 endState, - uint256 numStates - ) internal returns (bytes32[] memory, bytes32[] memory) { - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates( - currentStates, - numStates - 1 - ); + function appendRandomStatesBetween(bytes32[] memory currentStates, bytes32 endState, uint256 numStates) + internal + returns (bytes32[] memory, bytes32[] memory) + { + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates(currentStates, numStates - 1); bytes32[] memory fullStates = ArrayUtilsLib.append(states, endState); bytes32[] memory fullExp = MerkleTreeLib.appendLeaf(exp, endState); return (fullStates, fullExp); } - function toDynamic(BisectionChildren[6] memory l) - internal - pure - returns (BisectionChildren[] memory) - { + function toDynamic(BisectionChildren[6] memory l) internal pure returns (BisectionChildren[] memory) { BisectionChildren[] memory d = new BisectionChildren[](6); for (uint256 i = 0; i < d.length; i++) { d[i] = l[i]; @@ -1023,53 +780,25 @@ contract EdgeChallengeManagerTest is Test { pure returns (bytes memory) { - bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(bigStepStates), - bigStepStates.length - 1 - ); - return - abi.encode( - states1[0], - states1[1], - claimStartInclusionProof, - claimEndInclusionProof, - edgeInclusionProof - ); + bytes32[] memory claimStartInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); + return abi.encode(states1[0], states1[1], claimStartInclusionProof, claimEndInclusionProof, edgeInclusionProof); } function testRevertEmptyPrefixProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + vm.expectRevert(abi.encodeWithSelector(EmptyPrefixProof.selector)); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1086,28 +815,13 @@ contract EdgeChallengeManagerTest is Test { function testRevertInvalidPrefixProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + vm.expectRevert("Post expansion root not equal post"); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1117,11 +831,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states1, 1, states1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1130,7 +841,7 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeNotOneStepFork() public { EdgeInitData memory ei = deployAndInit(); - (bytes32[] memory states1, , BisectionChildren[6] memory edges1, ) = createBlockEdgesAndBisectToFork( + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( CreateBlockEdgesBisectArgs( ei.challengeManager, ei.a1, @@ -1141,15 +852,10 @@ contract EdgeChallengeManagerTest is Test { ) ); - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 - ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); - vm.expectRevert( - abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, edges1[0].lowerChildId) - ); + vm.expectRevert(abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, edges1[0].lowerChildId)); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 1, @@ -1158,11 +864,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1171,28 +874,13 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeNoProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + vm.expectRevert(abi.encodeWithSelector(EmptyEdgeSpecificProof.selector)); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1202,11 +890,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: "" }) ); @@ -1215,36 +900,17 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidStartClaimProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(bigStepStates), - bigStepStates.length - 1 - ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -1255,18 +921,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: abi.encode( - states1[0], - states1[1], - claimEndInclusionProof, - claimEndInclusionProof, - edgeInclusionProof - ) + states1[0], states1[1], claimEndInclusionProof, claimEndInclusionProof, edgeInclusionProof + ) }) ); } @@ -1274,36 +933,17 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidEndClaimProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); - bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), - 0 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(bigStepStates), - bigStepStates.length - 1 - ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + + bytes32[] memory claimStartInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(bigStepStates), bigStepStates.length - 1); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -1314,18 +954,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: abi.encode( - states1[0], - states1[1], - claimStartInclusionProof, - claimStartInclusionProof, - edgeInclusionProof - ) + states1[0], states1[1], claimStartInclusionProof, claimStartInclusionProof, edgeInclusionProof + ) }) ); } @@ -1333,36 +966,17 @@ contract EdgeChallengeManagerTest is Test { function testRevertSubChallengeInvalidEdgeProof() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); - bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), - 1 - ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + + bytes32[] memory claimStartInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 1)), 0); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, 2)), 1); vm.expectRevert("Invalid inclusion proof"); ei.challengeManager.createLayerZeroEdge( @@ -1373,18 +987,11 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: abi.encode( - states1[0], - states1[1], - claimStartInclusionProof, - claimEndInclusionProof, - claimStartInclusionProof - ) + states1[0], states1[1], claimStartInclusionProof, claimEndInclusionProof, claimStartInclusionProof + ) }) ); } @@ -1392,28 +999,13 @@ contract EdgeChallengeManagerTest is Test { function testRevertBigStepInvalidHeight() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1423,11 +1015,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1442,25 +1031,14 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 - ); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1470,11 +1048,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1484,11 +1059,7 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge2BigStepId; { bytes32[] memory bigStepExp2; - (bigStepStates2, bigStepExp2) = appendRandomStatesBetween( - genesisStates(), - states2[1], - height1 - ); + (bigStepStates2, bigStepExp2) = appendRandomStatesBetween(genesisStates(), states2[1], height1); edge2BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1498,24 +1069,16 @@ contract EdgeChallengeManagerTest is Test { claimId: edges2[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length)) + ), proof: generateEdgeProof(states2, bigStepStates2) }) ); } - (BisectionChildren[6] memory bigstepedges1, ) = bisectToForkOnly( + (BisectionChildren[6] memory bigstepedges1,) = bisectToForkOnly( BisectToForkOnlyArgs( - ei.challengeManager, - edge1BigStepId, - edge2BigStepId, - bigStepStates1, - bigStepStates2, - false + ei.challengeManager, edge1BigStepId, edge2BigStepId, bigStepStates1, bigStepStates2, false ) ); @@ -1523,11 +1086,7 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge1SmallStepId; { bytes32[] memory smallStepExp1; - (smallStepStates1, smallStepExp1) = appendRandomStatesBetween( - genesisStates(), - bigStepStates1[1], - height1 - ); + (smallStepStates1, smallStepExp1) = appendRandomStatesBetween(genesisStates(), bigStepStates1[1], height1); vm.expectRevert(abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, 1, 1)); edge1SmallStepId = ei.challengeManager.createLayerZeroEdge( @@ -1538,11 +1097,8 @@ contract EdgeChallengeManagerTest is Test { claimId: bigstepedges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(smallStepStates1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length)) + ), proof: generateEdgeProof(bigStepStates1, smallStepStates1) }) ); @@ -1552,31 +1108,15 @@ contract EdgeChallengeManagerTest is Test { function testRevertSmallStepInvalidClaimType() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 - ); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); vm.expectRevert(abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, 2, 0)); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( @@ -1587,11 +1127,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1607,25 +1144,14 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); bytes32[] memory bigStepStates1; bytes32 edge1BigStepId; { bytes32[] memory bigStepExp1; - (bigStepStates1, bigStepExp1) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 - ); + (bigStepStates1, bigStepExp1) = appendRandomStatesBetween(genesisStates(), states1[1], height1); edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1635,11 +1161,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates1, 1, bigStepStates1.length)) + ), proof: generateEdgeProof(states1, bigStepStates1) }) ); @@ -1649,11 +1172,7 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge2BigStepId; { bytes32[] memory bigStepExp2; - (bigStepStates2, bigStepExp2) = appendRandomStatesBetween( - genesisStates(), - states2[1], - height1 - ); + (bigStepStates2, bigStepExp2) = appendRandomStatesBetween(genesisStates(), states2[1], height1); edge2BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ @@ -1663,24 +1182,16 @@ contract EdgeChallengeManagerTest is Test { claimId: edges2[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates2, 1, bigStepStates2.length)) + ), proof: generateEdgeProof(states2, bigStepStates2) }) ); } - (BisectionChildren[6] memory bigstepedges1, ) = bisectToForkOnly( + (BisectionChildren[6] memory bigstepedges1,) = bisectToForkOnly( BisectToForkOnlyArgs( - ei.challengeManager, - edge1BigStepId, - edge2BigStepId, - bigStepStates1, - bigStepStates2, - false + ei.challengeManager, edge1BigStepId, edge2BigStepId, bigStepStates1, bigStepStates2, false ) ); @@ -1688,11 +1199,7 @@ contract EdgeChallengeManagerTest is Test { bytes32 edge1SmallStepId; { bytes32[] memory smallStepExp1; - (smallStepStates1, smallStepExp1) = appendRandomStatesBetween( - genesisStates(), - bigStepStates1[1], - height1 - ); + (smallStepStates1, smallStepExp1) = appendRandomStatesBetween(genesisStates(), bigStepStates1[1], height1); vm.expectRevert(abi.encodeWithSelector(InvalidEndHeight.selector, 1, 32)); edge1SmallStepId = ei.challengeManager.createLayerZeroEdge( @@ -1703,11 +1210,8 @@ contract EdgeChallengeManagerTest is Test { claimId: bigstepedges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(smallStepStates1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(smallStepStates1, 1, smallStepStates1.length)) + ), proof: generateEdgeProof(bigStepStates1, smallStepStates1) }) ); @@ -1717,28 +1221,13 @@ contract EdgeChallengeManagerTest is Test { function testCanConfirmByClaim() public { EdgeInitData memory ei = deployAndInit(); - ( - bytes32[] memory states1, - , - BisectionChildren[6] memory edges1, - - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); - - (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = appendRandomStatesBetween( - genesisStates(), - states1[1], - height1 + (bytes32[] memory states1,, BisectionChildren[6] memory edges1,) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); + (bytes32[] memory bigStepStates, bytes32[] memory bigStepExp) = + appendRandomStatesBetween(genesisStates(), states1[1], height1); + bytes32 edge1BigStepId = ei.challengeManager.createLayerZeroEdge( CreateEdgeArgs({ level: 1, @@ -1747,11 +1236,8 @@ contract EdgeChallengeManagerTest is Test { claimId: edges1[0].lowerChildId, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(bigStepStates, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(bigStepStates, 1, bigStepStates.length)) + ), proof: generateEdgeProof(states1, bigStepStates) }) ); @@ -1766,38 +1252,27 @@ contract EdgeChallengeManagerTest is Test { ei.challengeManager.confirmEdgeByClaim(edges1[0].lowerChildId, edge1BigStepId); ei.challengeManager.confirmEdgeByTime( - edges1[0].upperChildId, - getAncestorsAbove(toDynamic(edges1), 0), - ei.a1Data + edges1[0].upperChildId, getAncestorsAbove(toDynamic(edges1), 0), ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[1].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[1].upperChildId, - getAncestorsAbove(toDynamic(edges1), 1), - ei.a1Data + edges1[1].upperChildId, getAncestorsAbove(toDynamic(edges1), 1), ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[2].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[2].upperChildId, - getAncestorsAbove(toDynamic(edges1), 2), - ei.a1Data + edges1[2].upperChildId, getAncestorsAbove(toDynamic(edges1), 2), ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[3].lowerChildId); ei.challengeManager.confirmEdgeByTime( - edges1[3].upperChildId, - getAncestorsAbove(toDynamic(edges1), 3), - ei.a1Data + edges1[3].upperChildId, getAncestorsAbove(toDynamic(edges1), 3), ei.a1Data ); ei.challengeManager.confirmEdgeByChildren(edges1[4].lowerChildId); - assertTrue( - ei.challengeManager.getEdge(edges1[4].lowerChildId).status == EdgeStatus.Confirmed, - "Edge confirmed" - ); + assertTrue(ei.challengeManager.getEdge(edges1[4].lowerChildId).status == EdgeStatus.Confirmed, "Edge confirmed"); } struct CreateBlockEdgesBisectArgs { @@ -1834,75 +1309,41 @@ contract EdgeChallengeManagerTest is Test { ExecutionStateData(endState, genesisAssertionHash, bytes32(0)) ); - return - challengeManager.createLayerZeroEdge( - CreateEdgeArgs({ - level: 0, - endHistoryRoot: MerkleTreeLib.root(exp), - endHeight: height1, - claimId: claimId, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states, 1, states.length) - ) + return challengeManager.createLayerZeroEdge( + CreateEdgeArgs({ + level: 0, + endHistoryRoot: MerkleTreeLib.root(exp), + endHeight: height1, + claimId: claimId, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states, 0, 1), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) ), - proof: typeSpecificProof1 - }) - ); + proof: typeSpecificProof1 + }) + ); } function createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs memory args) internal - returns ( - bytes32[] memory, - bytes32[] memory, - BisectionChildren[6] memory, - BisectionChildren[6] memory - ) + returns (bytes32[] memory, bytes32[] memory, BisectionChildren[6] memory, BisectionChildren[6] memory) { - (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(args.endState1), - height1 - ); - bytes32 edge1Id = createLayerZeroEdge( - args.challengeManager, - args.claim1Id, - args.endState1, - states1, - exp1 - ); + (bytes32[] memory states1, bytes32[] memory exp1) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState1), height1); + bytes32 edge1Id = createLayerZeroEdge(args.challengeManager, args.claim1Id, args.endState1, states1, exp1); vm.roll(block.number + 1); assertEq(args.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(args.endState2), - height1 - ); - bytes32 edge2Id = createLayerZeroEdge( - args.challengeManager, - args.claim2Id, - args.endState2, - states2, - exp2 - ); + (bytes32[] memory states2, bytes32[] memory exp2) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState2), height1); + bytes32 edge2Id = createLayerZeroEdge(args.challengeManager, args.claim2Id, args.endState2, states2, exp2); vm.roll(block.number + 2); (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs( - args.challengeManager, - edge1Id, - edge2Id, - states1, - states2, - args.skipLast - ) + BisectToForkOnlyArgs(args.challengeManager, edge1Id, edge2Id, states1, states2, args.skipLast) ); return (states1, states2, edges1, edges2); @@ -1912,27 +1353,19 @@ contract EdgeChallengeManagerTest is Test { internal returns (BisectionData memory) { - (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( - genesisStates(), - args.endState1, - height1 - ); + (bytes32[] memory states1, bytes32[] memory exp1) = + appendRandomStatesBetween(genesisStates(), args.endState1, height1); bytes32 edge1Id; { bytes memory typeSpecificProof1; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(args.forkStates1), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states1), - states1.length - 1 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), 0 ); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates1), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), states1.length - 1); typeSpecificProof1 = abi.encode( genesisStateHash, args.endState1, @@ -1949,11 +1382,8 @@ contract EdgeChallengeManagerTest is Test { claimId: args.claim1Id, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states1, 1, states1.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) + ), proof: typeSpecificProof1 }) ); @@ -1963,27 +1393,19 @@ contract EdgeChallengeManagerTest is Test { assertEq(args.challengeManager.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( - genesisStates(), - args.endState2, - height1 - ); + (bytes32[] memory states2, bytes32[] memory exp2) = + appendRandomStatesBetween(genesisStates(), args.endState2, height1); bytes32 edge2Id; { bytes memory typeSpecificProof2; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(args.forkStates2), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states2), - states2.length - 1 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), 0 ); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates2), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1); typeSpecificProof2 = abi.encode( genesisStateHash, args.endState2, @@ -2000,11 +1422,8 @@ contract EdgeChallengeManagerTest is Test { claimId: args.claim2Id, prefixProof: abi.encode( ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states2, 1, states2.length) - ) - ), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) + ), proof: typeSpecificProof2 }) ); @@ -2013,14 +1432,7 @@ contract EdgeChallengeManagerTest is Test { vm.roll(block.number + 2); (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs( - args.challengeManager, - edge1Id, - edge2Id, - states1, - states2, - args.skipLast - ) + BisectToForkOnlyArgs(args.challengeManager, edge1Id, edge2Id, states1, states2, args.skipLast) ); return BisectionData(states1, states2, edges1, edges2); @@ -2034,15 +1446,8 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -2074,135 +1479,62 @@ contract EdgeChallengeManagerTest is Test { vm.roll(challengePeriodBlock + 11); - BisectionChildren[] memory allWinners = concat( - concat(toDynamic(ssbd.edges1), toDynamic(bsbd.edges1)), - toDynamic(blockEdges1) - ); + BisectionChildren[] memory allWinners = + concat(concat(toDynamic(ssbd.edges1), toDynamic(bsbd.edges1)), toDynamic(blockEdges1)); - ei.challengeManager.confirmEdgeByTime( - allWinners[0].lowerChildId, - getAncestorsAbove(allWinners, 0), - ei.a1Data - ); - ei.challengeManager.confirmEdgeByTime( - allWinners[0].upperChildId, - getAncestorsAbove(allWinners, 0), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[0].lowerChildId, getAncestorsAbove(allWinners, 0), ei.a1Data); + ei.challengeManager.confirmEdgeByTime(allWinners[0].upperChildId, getAncestorsAbove(allWinners, 0), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[1].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[1].upperChildId, - getAncestorsAbove(allWinners, 1), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[1].upperChildId, getAncestorsAbove(allWinners, 1), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[2].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[2].upperChildId, - getAncestorsAbove(allWinners, 2), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[2].upperChildId, getAncestorsAbove(allWinners, 2), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[3].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[3].upperChildId, - getAncestorsAbove(allWinners, 3), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[3].upperChildId, getAncestorsAbove(allWinners, 3), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[4].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[4].upperChildId, - getAncestorsAbove(allWinners, 4), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[4].upperChildId, getAncestorsAbove(allWinners, 4), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[5].lowerChildId); - ei.challengeManager.confirmEdgeByClaim( - allWinners[6].lowerChildId, - allWinners[5].lowerChildId - ); - ei.challengeManager.confirmEdgeByTime( - allWinners[6].upperChildId, - getAncestorsAbove(allWinners, 6), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByClaim(allWinners[6].lowerChildId, allWinners[5].lowerChildId); + ei.challengeManager.confirmEdgeByTime(allWinners[6].upperChildId, getAncestorsAbove(allWinners, 6), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[7].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[7].upperChildId, - getAncestorsAbove(allWinners, 7), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[7].upperChildId, getAncestorsAbove(allWinners, 7), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[8].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[8].upperChildId, - getAncestorsAbove(allWinners, 8), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[8].upperChildId, getAncestorsAbove(allWinners, 8), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[9].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[9].upperChildId, - getAncestorsAbove(allWinners, 9), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[9].upperChildId, getAncestorsAbove(allWinners, 9), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[10].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[10].upperChildId, - getAncestorsAbove(allWinners, 10), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[10].upperChildId, getAncestorsAbove(allWinners, 10), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[11].lowerChildId); - ei.challengeManager.confirmEdgeByClaim( - allWinners[12].lowerChildId, - allWinners[11].lowerChildId - ); - ei.challengeManager.confirmEdgeByTime( - allWinners[12].upperChildId, - getAncestorsAbove(allWinners, 12), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByClaim(allWinners[12].lowerChildId, allWinners[11].lowerChildId); + ei.challengeManager.confirmEdgeByTime(allWinners[12].upperChildId, getAncestorsAbove(allWinners, 12), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[13].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[13].upperChildId, - getAncestorsAbove(allWinners, 13), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[13].upperChildId, getAncestorsAbove(allWinners, 13), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[14].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[14].upperChildId, - getAncestorsAbove(allWinners, 14), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[14].upperChildId, getAncestorsAbove(allWinners, 14), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[15].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[15].upperChildId, - getAncestorsAbove(allWinners, 15), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[15].upperChildId, getAncestorsAbove(allWinners, 15), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[16].lowerChildId); - ei.challengeManager.confirmEdgeByTime( - allWinners[16].upperChildId, - getAncestorsAbove(allWinners, 16), - ei.a1Data - ); + ei.challengeManager.confirmEdgeByTime(allWinners[16].upperChildId, getAncestorsAbove(allWinners, 16), ei.a1Data); ei.challengeManager.confirmEdgeByChildren(allWinners[17].lowerChildId); assertTrue( - ei.challengeManager.getEdge(allWinners[14].lowerChildId).status == EdgeStatus.Confirmed, - "Edge confirmed" + ei.challengeManager.getEdge(allWinners[14].lowerChildId).status == EdgeStatus.Confirmed, "Edge confirmed" ); } @@ -2222,27 +1554,12 @@ contract EdgeChallengeManagerTest is Test { BisectionData smallStepBisection; } - function testCanConfirmByOneStep() - public - returns (EdgeInitData memory, BisectionChildren[] memory) - { + function testCanConfirmByOneStep() public returns (EdgeInitData memory, BisectionChildren[] memory) { EdgeInitData memory ei = deployAndInit(); CanConfirmByOneStepData memory local; - ( - local.blockStates1, - local.blockStates2, - local.blockEdges1, - local.blockEdges2 - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) + (local.blockStates1, local.blockStates2, local.blockEdges1, local.blockEdges2) = createBlockEdgesAndBisectToFork( + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) ); local.bigStepBisections[0] = createMachineEdgesAndBisectToFork( @@ -2294,10 +1611,7 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[] memory allWinners = toDynamic(local.smallStepBisection.edges1); for (uint256 i = 0; i < NUM_BIGSTEP_LEVEL; ++i) { - allWinners = concat( - allWinners, - toDynamic(local.bigStepBisections[NUM_BIGSTEP_LEVEL - i - 1].edges1) - ); + allWinners = concat(allWinners, toDynamic(local.bigStepBisections[NUM_BIGSTEP_LEVEL - i - 1].edges1)); } allWinners = concat(allWinners, toDynamic(local.blockEdges1)); @@ -2326,15 +1640,10 @@ contract EdgeChallengeManagerTest is Test { if (i % 6 != 0) { ei.challengeManager.confirmEdgeByChildren(allWinners[i].lowerChildId); } else { - ei.challengeManager.confirmEdgeByClaim( - allWinners[i].lowerChildId, - allWinners[i - 1].lowerChildId - ); + ei.challengeManager.confirmEdgeByClaim(allWinners[i].lowerChildId, allWinners[i - 1].lowerChildId); } ei.challengeManager.confirmEdgeByTime( - allWinners[i].upperChildId, - getAncestorsAbove(allWinners, i), - ei.a1Data + allWinners[i].upperChildId, getAncestorsAbove(allWinners, i), ei.a1Data ); } else { ei.challengeManager.confirmEdgeByChildren(allWinners[i].lowerChildId); @@ -2342,8 +1651,7 @@ contract EdgeChallengeManagerTest is Test { } assertTrue( - ei.challengeManager.getEdge(allWinners[allWinners.length - 1].lowerChildId).status == - EdgeStatus.Confirmed, + ei.challengeManager.getEdge(allWinners[allWinners.length - 1].lowerChildId).status == EdgeStatus.Confirmed, "Edge confirmed" ); @@ -2351,7 +1659,7 @@ contract EdgeChallengeManagerTest is Test { } function testExcessStakeReceived() external { - (EdgeInitData memory ei, ) = testCanConfirmByOneStep(); + (EdgeInitData memory ei,) = testCanConfirmByOneStep(); IERC20 stakeToken = ei.challengeManager.stakeToken(); assertEq( stakeToken.balanceOf(excessStakeReceiver), @@ -2375,10 +1683,7 @@ contract EdgeChallengeManagerTest is Test { (EdgeInitData memory ei, BisectionChildren[] memory allWinners) = testCanConfirmByOneStep(); ei.challengeManager.refundStake(allWinners[allWinners.length - 1].lowerChildId); vm.expectRevert( - abi.encodeWithSelector( - EdgeAlreadyRefunded.selector, - allWinners[allWinners.length - 1].lowerChildId - ) + abi.encodeWithSelector(EdgeAlreadyRefunded.selector, allWinners[allWinners.length - 1].lowerChildId) ); ei.challengeManager.refundStake(allWinners[allWinners.length - 1].lowerChildId); } @@ -2386,12 +1691,7 @@ contract EdgeChallengeManagerTest is Test { function testRevertRefundStakeNotLayerZero() external { (EdgeInitData memory ei, BisectionChildren[] memory allWinners) = testCanConfirmByOneStep(); vm.expectRevert( - abi.encodeWithSelector( - EdgeNotLayerZero.selector, - allWinners[allWinners.length - 2].lowerChildId, - 0, - 0 - ) + abi.encodeWithSelector(EdgeNotLayerZero.selector, allWinners[allWinners.length - 2].lowerChildId, 0, 0) ); ei.challengeManager.refundStake(allWinners[allWinners.length - 2].lowerChildId); } @@ -2419,11 +1719,9 @@ contract EdgeChallengeManagerTest is Test { } function testRevertRefundStakeNotConfirmed() external { - (EdgeInitData memory ei, , , bytes32 edgeId) = testCanCreateEdgeWithStake(); + (EdgeInitData memory ei,,, bytes32 edgeId) = testCanCreateEdgeWithStake(); - vm.expectRevert( - abi.encodeWithSelector(EdgeNotConfirmed.selector, edgeId, EdgeStatus.Pending) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, edgeId, EdgeStatus.Pending)); ei.challengeManager.refundStake(edgeId); } @@ -2436,15 +1734,8 @@ contract EdgeChallengeManagerTest is Test { BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs( - ei.challengeManager, - ei.a1, - ei.a2, - ei.a1State, - ei.a2State, - false - ) - ); + CreateBlockEdgesBisectArgs(ei.challengeManager, ei.a1, ei.a2, ei.a1State, ei.a2State, false) + ); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( diff --git a/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol b/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol index d86f5990f..087d95598 100644 --- a/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol +++ b/contracts/test/challengeV2/EdgeChallengeManagerLib.t.sol @@ -12,21 +12,15 @@ import "./Utils.sol"; contract MockOneStepProofEntry is IOneStepProofEntry { using GlobalStateLib for GlobalState; - function proveOneStep( - ExecutionContext calldata, - uint256, - bytes32, - bytes calldata proof - ) external pure returns (bytes32 afterHash) { - return bytes32(proof); - } - - function getMachineHash(ExecutionState calldata execState) + function proveOneStep(ExecutionContext calldata, uint256, bytes32, bytes calldata proof) external pure - override - returns (bytes32) + returns (bytes32 afterHash) { + return bytes32(proof); + } + + function getMachineHash(ExecutionState calldata execState) external pure override returns (bytes32) { require(execState.machineStatus == MachineStatus.FINISHED, "BAD_MACHINE_STATUS"); return GlobalStateLib.hash(execState.globalState); } @@ -65,14 +59,7 @@ contract EdgeChallengeManagerLibAccess { uint256 expectedEndHeight, uint8 numBigStepLevel ) public returns (EdgeAddedData memory) { - return - store.createLayerZeroEdge( - args, - ard, - oneStepProofEntry, - expectedEndHeight, - numBigStepLevel - ); + return store.createLayerZeroEdge(args, ard, oneStepProofEntry, expectedEndHeight, numBigStepLevel); } function getPrevAssertionHash(bytes32 edgeId) public view returns (bytes32) { @@ -99,17 +86,9 @@ contract EdgeChallengeManagerLibAccess { return EdgeChallengeManagerLib.mandatoryBisectionHeight(start, end); } - function bisectEdge( - bytes32 edgeId, - bytes32 bisectionHistoryRoot, - bytes memory prefixProof - ) + function bisectEdge(bytes32 edgeId, bytes32 bisectionHistoryRoot, bytes memory prefixProof) public - returns ( - bytes32, - EdgeAddedData memory, - EdgeAddedData memory - ) + returns (bytes32, EdgeAddedData memory, EdgeAddedData memory) { return store.bisectEdge(edgeId, bisectionHistoryRoot, prefixProof); } @@ -154,11 +133,7 @@ contract EdgeChallengeManagerLibAccess { return store.confirmedRivals[mutualId]; } - function confirmEdgeByClaim( - bytes32 edgeId, - bytes32 claimingEdgeId, - uint8 numBigStepLevel - ) public { + function confirmEdgeByClaim(bytes32 edgeId, bytes32 claimingEdgeId, uint8 numBigStepLevel) public { return store.confirmEdgeByClaim(edgeId, claimingEdgeId, numBigStepLevel); } @@ -169,14 +144,9 @@ contract EdgeChallengeManagerLibAccess { uint64 confirmationThresholdBlock, uint8 numBigStepLevel ) public returns (uint64) { - return - store.confirmEdgeByTime( - edgeId, - ancestorEdgeIds, - claimedAssertionUnrivaledBlocks, - confirmationThresholdBlock, - numBigStepLevel - ); + return store.confirmEdgeByTime( + edgeId, ancestorEdgeIds, claimedAssertionUnrivaledBlocks, confirmationThresholdBlock, numBigStepLevel + ); } function confirmEdgeByOneStepProof( @@ -188,16 +158,15 @@ contract EdgeChallengeManagerLibAccess { bytes32[] calldata afterHistoryInclusionProof, uint8 numBigStepLevel ) public { - return - store.confirmEdgeByOneStepProof( - edgeId, - oneStepProofEntry, - oneStepData, - execCtx, - beforeHistoryInclusionProof, - afterHistoryInclusionProof, - numBigStepLevel - ); + return store.confirmEdgeByOneStepProof( + edgeId, + oneStepProofEntry, + oneStepData, + execCtx, + beforeHistoryInclusionProof, + afterHistoryInclusionProof, + numBigStepLevel + ); } } @@ -217,22 +186,8 @@ contract EdgeChallengeManagerLibTest is Test { function twoNonRivals() internal returns (ChallengeEdge memory, ChallengeEdge memory) { bytes32 originId = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - rand.hash(), - 3, - rand.hash(), - 9, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - rand.hash(), - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); return (edge1, edge2); } @@ -241,38 +196,16 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 3, - rand.hash(), - 9, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); return (edge1, edge2); } - function checkEdgeAddedData( - ChallengeEdge memory edge, - bool hasRival, - EdgeAddedData memory d - ) internal { + function checkEdgeAddedData(ChallengeEdge memory edge, bool hasRival, EdgeAddedData memory d) internal { bytes32 id = edge.idMem(); bytes32 mutualId = ChallengeEdgeLib.mutualIdComponent( - edge.level, - edge.originId, - edge.startHeight, - edge.startHistoryRoot, - edge.endHeight + edge.level, edge.originId, edge.startHeight, edge.startHistoryRoot, edge.endHeight ); assertEq(id, d.edgeId, "invalid edge id"); assertEq(mutualId, d.mutualId, "invalid mutual id"); @@ -284,22 +217,19 @@ contract EdgeChallengeManagerLibTest is Test { } function testAdd() public { - (ChallengeEdge memory edge, ) = twoNonRivals(); + (ChallengeEdge memory edge,) = twoNonRivals(); EdgeAddedData memory d = store.add(edge); ChallengeEdge memory se = store.get(edge.idMem()); assertTrue(store.exists(edge.idMem()), "Edge exists"); - assertTrue( - store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, - "NO_RIVAL first rival" - ); + assertTrue(store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "NO_RIVAL first rival"); checkEdgeAddedData(se, false, d); } function testGet() public { - (ChallengeEdge memory edge, ) = twoNonRivals(); + (ChallengeEdge memory edge,) = twoNonRivals(); store.add(edge); @@ -308,7 +238,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testGetNotExist() public { - (ChallengeEdge memory edge, ) = twoNonRivals(); + (ChallengeEdge memory edge,) = twoNonRivals(); bytes32 edgeId = edge.idMem(); @@ -335,12 +265,7 @@ contract EdgeChallengeManagerLibTest is Test { function testAddMoreRivals() public { (ChallengeEdge memory edge1, ChallengeEdge memory edge2) = twoRivals(); ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( - edge1.originId, - edge1.startHistoryRoot, - edge1.startHeight, - rand.hash(), - edge1.endHeight, - 0 + edge1.originId, edge1.startHistoryRoot, edge1.startHeight, rand.hash(), edge1.endHeight, 0 ); store.add(edge1); @@ -365,25 +290,12 @@ contract EdgeChallengeManagerLibTest is Test { ChallengeEdge memory se = store.get(edge1.idMem()); ChallengeEdge memory se2 = store.get(edge2.idMem()); assertTrue(store.exists(se2.idMem()), "Edge exists"); - assertTrue( - store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, - "First rival1" - ); - assertTrue( - store.firstRivals(se2.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, - "First rival2" - ); + assertTrue(store.firstRivals(se.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "First rival1"); + assertTrue(store.firstRivals(se2.mutualIdMem()) == EdgeChallengeManagerLib.UNRIVALED, "First rival2"); } function testCannotAddSameEdgeTwice() public { - ChallengeEdge memory edge = ChallengeEdgeLib.newChildEdge( - rand.hash(), - rand.hash(), - 0, - rand.hash(), - 10, - 0 - ); + ChallengeEdge memory edge = ChallengeEdgeLib.newChildEdge(rand.hash(), rand.hash(), 0, rand.hash(), 10, 0); store.add(edge); @@ -416,12 +328,7 @@ contract EdgeChallengeManagerLibTest is Test { function testHasRivalMore() public { (ChallengeEdge memory edge1, ChallengeEdge memory edge2) = twoRivals(); ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( - edge1.originId, - edge1.startHistoryRoot, - edge1.startHeight, - rand.hash(), - edge1.endHeight, - 0 + edge1.originId, edge1.startHistoryRoot, edge1.startHeight, rand.hash(), edge1.endHeight, 0 ); store.add(edge1); @@ -455,22 +362,8 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotRival() public { bytes32 originId = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - rand.hash(), - 9, - rand.hash(), - 10, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - rand.hash(), - 9, - rand.hash(), - 10, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 9, rand.hash(), 10, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 9, rand.hash(), 10, 0); store.add(edge1); store.add(edge2); @@ -482,22 +375,8 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotHeight() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 8, - rand.hash(), - 10, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 8, - rand.hash(), - 10, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 8, rand.hash(), 10, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 8, rand.hash(), 10, 0); store.add(edge1); store.add(edge2); @@ -509,22 +388,8 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRival() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 9, - rand.hash(), - 10, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 9, - rand.hash(), - 10, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); store.add(edge1); store.add(edge2); @@ -536,22 +401,8 @@ contract EdgeChallengeManagerLibTest is Test { function testSingleStepRivalNotExist() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 9, - rand.hash(), - 10, - 0 - ); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 9, - rand.hash(), - 10, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 9, rand.hash(), 10, 0); store.add(edge1); @@ -561,7 +412,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaled() public { - (ChallengeEdge memory edge1, ) = twoRivals(); + (ChallengeEdge memory edge1,) = twoRivals(); store.add(edge1); vm.roll(block.number + 3); @@ -583,7 +434,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaledFirstRivalNotExist() public { - (ChallengeEdge memory edge1, ) = twoRivals(); + (ChallengeEdge memory edge1,) = twoRivals(); store.add(edge1); vm.roll(block.number + 3); @@ -594,7 +445,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testTimeUnrivaledNotExist() public { - (ChallengeEdge memory edge1, ) = twoRivals(); + (ChallengeEdge memory edge1,) = twoRivals(); vm.roll(block.number + 3); @@ -606,50 +457,22 @@ contract EdgeChallengeManagerLibTest is Test { function testTimeUnrivaledAfterRival() public { bytes32 originId = rand.hash(); bytes32 startRoot = rand.hash(); - ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge1 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); store.add(edge1); vm.roll(block.number + 4); - ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge2 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); store.add(edge2); vm.roll(block.number + 5); - ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge( - originId, - startRoot, - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge3 = ChallengeEdgeLib.newChildEdge(originId, startRoot, 3, rand.hash(), 9, 0); store.add(edge3); vm.roll(block.number + 6); - ChallengeEdge memory edge4 = ChallengeEdgeLib.newChildEdge( - originId, - rand.hash(), - 3, - rand.hash(), - 9, - 0 - ); + ChallengeEdge memory edge4 = ChallengeEdgeLib.newChildEdge(originId, rand.hash(), 3, rand.hash(), 9, 0); store.add(edge4); vm.roll(block.number + 7); @@ -742,15 +565,11 @@ contract EdgeChallengeManagerLibTest is Test { return (full, exp); } - function appendRandomStatesBetween( - bytes32[] memory currentStates, - bytes32 endState, - uint256 numStates - ) internal returns (bytes32[] memory, bytes32[] memory) { - (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates( - currentStates, - numStates - 1 - ); + function appendRandomStatesBetween(bytes32[] memory currentStates, bytes32 endState, uint256 numStates) + internal + returns (bytes32[] memory, bytes32[] memory) + { + (bytes32[] memory states, bytes32[] memory exp) = appendRandomStates(currentStates, numStates - 1); bytes32[] memory fullStates = ArrayUtilsLib.append(states, endState); bytes32[] memory fullExp = MerkleTreeLib.appendLeaf(exp, endState); return (fullStates, fullExp); @@ -762,58 +581,37 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end; } - function rivalStates( - uint256 start, - uint256 agreePoint, - uint256 end - ) internal returns (bytes32[] memory, bytes32[] memory) { + function rivalStates(uint256 start, uint256 agreePoint, uint256 end) + internal + returns (bytes32[] memory, bytes32[] memory) + { bytes32[] memory preStates = rand.hashes(start + 1); - (bytes32[] memory agreeStates, ) = appendRandomStates(preStates, agreePoint - start); - (bytes32[] memory states1, ) = appendRandomStates(agreeStates, end - agreePoint); + (bytes32[] memory agreeStates,) = appendRandomStates(preStates, agreePoint - start); + (bytes32[] memory states1,) = appendRandomStates(agreeStates, end - agreePoint); - (bytes32[] memory states2, ) = appendRandomStates(agreeStates, end - agreePoint); + (bytes32[] memory states2,) = appendRandomStates(agreeStates, end - agreePoint); return (states1, states2); } - function edgeFromStates( - bytes32 originId, - uint256 start, - uint256 end, - bytes32[] memory states - ) internal view returns (ChallengeEdge memory) { - bytes32 startRoot = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states, 0, start + 1) - ); + function edgeFromStates(bytes32 originId, uint256 start, uint256 end, bytes32[] memory states) + internal + view + returns (ChallengeEdge memory) + { + bytes32 startRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, start + 1)); bytes32 endRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, end + 1)); return ChallengeEdgeLib.newChildEdge(originId, startRoot, start, endRoot, end, 0); } - function proofGen(uint256 start, bytes32[] memory states) - internal - pure - returns (bytes32[] memory) - { - return - ProofUtils.generatePrefixProof( - start, - ArrayUtilsLib.slice(states, start, states.length) - ); + function proofGen(uint256 start, bytes32[] memory states) internal pure returns (bytes32[] memory) { + return ProofUtils.generatePrefixProof(start, ArrayUtilsLib.slice(states, start, states.length)); } - function twoRivalsFromLeaves( - uint256 start, - uint256 agreePoint, - uint256 end - ) + function twoRivalsFromLeaves(uint256 start, uint256 agreePoint, uint256 end) internal - returns ( - ChallengeEdge memory, - ChallengeEdge memory, - bytes32[] memory, - bytes32[] memory - ) + returns (ChallengeEdge memory, ChallengeEdge memory, bytes32[] memory, bytes32[] memory) { (bytes32[] memory states1, bytes32[] memory states2) = rivalStates(start, agreePoint, end); @@ -834,20 +632,10 @@ contract EdgeChallengeManagerLibTest is Test { EdgeAddedData memory upperChildAdded ) internal { ChallengeEdge memory lowerChild = ChallengeEdgeLib.newChildEdge( - edge.originId, - edge.startHistoryRoot, - edge.startHeight, - bisectionRoot, - bisectionHeight, - edge.level + edge.originId, edge.startHistoryRoot, edge.startHeight, bisectionRoot, bisectionHeight, edge.level ); ChallengeEdge memory upperChild = ChallengeEdgeLib.newChildEdge( - edge.originId, - bisectionRoot, - bisectionHeight, - edge.endHistoryRoot, - edge.endHeight, - edge.level + edge.originId, bisectionRoot, bisectionHeight, edge.endHistoryRoot, edge.endHeight, edge.level ); if (lowerChildAdded.edgeId != 0) { @@ -867,21 +655,17 @@ contract EdgeChallengeManagerLibTest is Test { bool lowerHasRival, bool upperHasRival ) internal { - ( - bytes32 lowerChildId, - EdgeAddedData memory lowerChildAdded, - EdgeAddedData memory upperChildAdded - ) = store.bisectEdge( - edge.idMem(), - bisectionRoot, - abi.encode( - ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), - ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states, bisectionPoint + 1, states.length) - ) + (bytes32 lowerChildId, EdgeAddedData memory lowerChildAdded, EdgeAddedData memory upperChildAdded) = store + .bisectEdge( + edge.idMem(), + bisectionRoot, + abi.encode( + ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), + ProofUtils.generatePrefixProof( + bisectionPoint + 1, ArrayUtilsLib.slice(states, bisectionPoint + 1, states.length) ) - ); + ) + ); bisectEdgeEmitted( edge, bisectionRoot, @@ -900,19 +684,13 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - bytes32[] memory states2 - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bisectAndCheck(edge1, bisectionRoot1, bisectionPoint, states1, false, false); assertEq( @@ -934,12 +712,7 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge1.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge1.originId, - bisectionRoot1, - bisectionPoint, - edge1.endHistoryRoot, - edge1.endHeight, - edge1.level + edge1.originId, bisectionRoot1, bisectionPoint, edge1.endHistoryRoot, edge1.endHeight, edge1.level ) ).idMem(), "Lower child id" @@ -948,9 +721,7 @@ contract EdgeChallengeManagerLibTest is Test { assertFalse(store.hasRival(store.get(edge1.idMem()).lowerChildId), "Lower child rival"); assertFalse(store.hasRival(store.get(edge1.idMem()).upperChildId), "Upper child rival"); - bytes32 bisectionRoot2 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot2 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1)); bisectAndCheck(edge2, bisectionRoot2, bisectionPoint, states2, true, false); assertEq( @@ -972,12 +743,7 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge2.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge2.originId, - bisectionRoot2, - bisectionPoint, - edge2.endHistoryRoot, - edge2.endHeight, - edge2.level + edge2.originId, bisectionRoot2, bisectionPoint, edge2.endHistoryRoot, edge2.endHeight, edge2.level ) ).idMem(), "Lower child id" @@ -992,19 +758,13 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - bytes32[] memory states2 - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bisectAndCheck(edge1, bisectionRoot1, bisectionPoint, states1, false, false); assertEq( @@ -1026,12 +786,7 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge1.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge1.originId, - bisectionRoot1, - bisectionPoint, - edge1.endHistoryRoot, - edge1.endHeight, - edge1.level + edge1.originId, bisectionRoot1, bisectionPoint, edge1.endHistoryRoot, edge1.endHeight, edge1.level ) ).idMem(), "Lower child id" @@ -1040,9 +795,7 @@ contract EdgeChallengeManagerLibTest is Test { assertFalse(store.hasRival(store.get(edge1.idMem()).lowerChildId), "Lower child rival"); assertFalse(store.hasRival(store.get(edge1.idMem()).upperChildId), "Upper child rival"); - bytes32 bisectionRoot2 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot2 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states2, 0, bisectionPoint + 1)); bisectAndCheck(edge2, bisectionRoot2, bisectionPoint, states2, false, true); assertEq( @@ -1064,12 +817,7 @@ contract EdgeChallengeManagerLibTest is Test { store.get(edge2.idMem()).upperChildId, ( ChallengeEdgeLib.newChildEdge( - edge2.originId, - bisectionRoot2, - bisectionPoint, - edge2.endHistoryRoot, - edge2.endHeight, - edge2.level + edge2.originId, bisectionRoot2, bisectionPoint, edge2.endHistoryRoot, edge2.endHeight, edge2.level ) ).idMem(), "Lower child id" @@ -1099,23 +847,16 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - (ChallengeEdge memory edge1, , bytes32[] memory states1, ) = twoRivalsFromLeaves( - start, - agree, - end - ); + (ChallengeEdge memory edge1,, bytes32[] memory states1,) = twoRivalsFromLeaves(start, agree, end); store.add(edge1); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); vm.expectRevert(abi.encodeWithSelector(EdgeUnrivaled.selector, edgeId)); @@ -1128,32 +869,23 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); store.bisectEdge(edgeId, bisectionRoot1, proof); - vm.expectRevert( - abi.encodeWithSelector(EdgeAlreadyExists.selector, store.get(edgeId).upperChildId) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeAlreadyExists.selector, store.get(edgeId).upperChildId)); store.bisectEdge(edgeId, bisectionRoot1, proof); } @@ -1163,25 +895,18 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bytes32 edgeId = edge1.idMem(); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint), ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); vm.expectRevert("Pre expansion root mismatch"); @@ -1194,32 +919,23 @@ contract EdgeChallengeManagerLibTest is Test { uint256 end = 11; uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = + twoRivalsFromLeaves(start, agree, end); edge1.status = EdgeStatus.Confirmed; store.add(edge1); store.add(edge2); - bytes32 bisectionRoot1 = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot1 = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1)); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states1, 0, bisectionPoint + 1), ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) + bisectionPoint + 1, ArrayUtilsLib.slice(states1, bisectionPoint + 1, states1.length) ) ); bytes32 edgeId = edge1.idMem(); - vm.expectRevert( - abi.encodeWithSelector(EdgeNotPending.selector, edgeId, EdgeStatus.Confirmed) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, edgeId, EdgeStatus.Confirmed)); store.bisectEdge(edgeId, bisectionRoot1, proof); } @@ -1244,72 +960,40 @@ contract EdgeChallengeManagerLibTest is Test { store.bisectEdge(edgeId, edge1.endHistoryRoot, ""); } - function bisectArgs( - bytes32[] memory states, - uint256 start, - uint256 end - ) + function bisectArgs(bytes32[] memory states, uint256 start, uint256 end) internal view - returns ( - uint256, - bytes32, - bytes memory - ) + returns (uint256, bytes32, bytes memory) { uint256 bisectionPoint = store.mandatoryBisectionHeight(start, end); - bytes32 bisectionRoot = MerkleTreeLib.root( - ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1) - ); + bytes32 bisectionRoot = MerkleTreeLib.root(ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1)); bytes memory proof = abi.encode( ProofUtils.expansionFromLeaves(states, 0, bisectionPoint + 1), - ProofUtils.generatePrefixProof( - bisectionPoint + 1, - ArrayUtilsLib.slice(states, bisectionPoint + 1, end + 1) - ) + ProofUtils.generatePrefixProof(bisectionPoint + 1, ArrayUtilsLib.slice(states, bisectionPoint + 1, end + 1)) ); return (bisectionPoint, bisectionRoot, proof); } - function addParentAndChildren( - uint256 start, - uint256 agree, - uint256 end - ) + function addParentAndChildren(uint256 start, uint256 agree, uint256 end) internal - returns ( - bytes32, - bytes32, - bytes32 - ) + returns (bytes32, bytes32, bytes32) { - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - - ) = twoRivalsFromLeaves(start, agree, end); + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1,) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(states1, start, end); - (bytes32 lowerChildId, , EdgeAddedData memory upperChildAdded) = store.bisectEdge( - edge1.idMem(), - bisectionRoot, - bisectionProof - ); + (bytes32 lowerChildId,, EdgeAddedData memory upperChildAdded) = + store.bisectEdge(edge1.idMem(), bisectionRoot, bisectionProof); return (edge1.idMem(), lowerChildId, upperChildAdded.edgeId); } function testConfirmEdgeByChildren() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1332,26 +1016,18 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(pc.upperChildId2); store.confirmEdgeByChildren(pc.edge1Id); - vm.expectRevert( - abi.encodeWithSelector(RivalEdgeConfirmed.selector, pc.edge2Id, pc.edge1Id) - ); + vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, pc.edge2Id, pc.edge1Id)); store.confirmEdgeByChildren(pc.edge2Id); } function testConfirmEdgeByChildrenAlreadyConfirmed() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); store.confirmEdgeByChildren(parentEdgeId); - vm.expectRevert( - abi.encodeWithSelector(RivalEdgeConfirmed.selector, parentEdgeId, parentEdgeId) - ); + vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, parentEdgeId, parentEdgeId)); store.confirmEdgeByChildren(parentEdgeId); } @@ -1363,11 +1039,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenLowerChildNotExist() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1378,11 +1050,7 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenUpperChildNotExist() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(lowerChildId); store.setConfirmed(upperChildId); @@ -1393,43 +1061,27 @@ contract EdgeChallengeManagerLibTest is Test { } function testConfirmEdgeByChildrenLowerChildPending() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(upperChildId); - vm.expectRevert( - abi.encodeWithSelector(EdgeNotConfirmed.selector, lowerChildId, EdgeStatus.Pending) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, lowerChildId, EdgeStatus.Pending)); store.confirmEdgeByChildren(parentEdgeId); } function testConfirmEdgeByChildrenUpperChildPending() public { - (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren( - 3, - 5, - 11 - ); + (bytes32 parentEdgeId, bytes32 lowerChildId, bytes32 upperChildId) = addParentAndChildren(3, 5, 11); store.setConfirmed(lowerChildId); - vm.expectRevert( - abi.encodeWithSelector(EdgeNotConfirmed.selector, upperChildId, EdgeStatus.Pending) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotConfirmed.selector, upperChildId, EdgeStatus.Pending)); store.confirmEdgeByChildren(parentEdgeId); } function testNextlevel() public { assertTrue(store.nextEdgeLevel(0, NUM_BIGSTEP_LEVEL) == 1); - assertTrue( - store.nextEdgeLevel(NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL) == NUM_BIGSTEP_LEVEL + 1 - ); - vm.expectRevert( - abi.encodeWithSelector(LevelTooHigh.selector, NUM_BIGSTEP_LEVEL + 2, NUM_BIGSTEP_LEVEL) - ); + assertTrue(store.nextEdgeLevel(NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL) == NUM_BIGSTEP_LEVEL + 1); + vm.expectRevert(abi.encodeWithSelector(LevelTooHigh.selector, NUM_BIGSTEP_LEVEL + 2, NUM_BIGSTEP_LEVEL)); store.nextEdgeLevel(NUM_BIGSTEP_LEVEL + 1, NUM_BIGSTEP_LEVEL); } @@ -1455,9 +1107,7 @@ contract EdgeChallengeManagerLibTest is Test { assertTrue(store.get(bargs.upperChildId1).status == EdgeStatus.Confirmed, "Edge confirmed"); assertEq( - store.confirmedRivals(store.get(bargs.upperChildId1).mutualIdMem()), - bargs.upperChildId1, - "Confirmed rival" + store.confirmedRivals(store.get(bargs.upperChildId1).mutualIdMem()), bargs.upperChildId1, "Confirmed rival" ); } @@ -1483,13 +1133,7 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(bargs.upperChildId2); store.setConfirmedRival(bargs.upperChildId2); - vm.expectRevert( - abi.encodeWithSelector( - RivalEdgeConfirmed.selector, - bargs.upperChildId1, - bargs.upperChildId2 - ) - ); + vm.expectRevert(abi.encodeWithSelector(RivalEdgeConfirmed.selector, bargs.upperChildId1, bargs.upperChildId2)); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1497,14 +1141,7 @@ contract EdgeChallengeManagerLibTest is Test { BArgs memory bargs = addParentsAndChildren(2, 3, 4); ChallengeEdge memory ce = ChallengeEdgeLib.newLayerZeroEdge( - rand.hash(), - rand.hash(), - 3, - rand.hash(), - 4, - bargs.upperChildId1, - rand.addr(), - NUM_BIGSTEP_LEVEL + rand.hash(), rand.hash(), 3, rand.hash(), 4, bargs.upperChildId1, rand.addr(), NUM_BIGSTEP_LEVEL ); store.add(ce); @@ -1512,9 +1149,7 @@ contract EdgeChallengeManagerLibTest is Test { store.setConfirmed(eid); vm.expectRevert( abi.encodeWithSelector( - OriginIdMutualIdMismatch.selector, - store.get(bargs.upperChildId1).mutualIdMem(), - store.get(eid).originId + OriginIdMutualIdMismatch.selector, store.get(bargs.upperChildId1).mutualIdMem(), store.get(eid).originId ) ); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); @@ -1553,26 +1188,13 @@ contract EdgeChallengeManagerLibTest is Test { BArgs memory bargs = addParentsAndChildren(2, 3, 4); ChallengeEdge memory ce = ChallengeEdgeLib.newLayerZeroEdge( - store.get(bargs.upperChildId1).mutualIdMem(), - rand.hash(), - 3, - rand.hash(), - 4, - rand.hash(), - rand.addr(), - 1 + store.get(bargs.upperChildId1).mutualIdMem(), rand.hash(), 3, rand.hash(), 4, rand.hash(), rand.addr(), 1 ); store.add(ce); bytes32 eid = ce.idMem(); store.setConfirmed(eid); - vm.expectRevert( - abi.encodeWithSelector( - EdgeClaimMismatch.selector, - bargs.upperChildId1, - store.get(eid).claimId - ) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeClaimMismatch.selector, bargs.upperChildId1, store.get(eid).claimId)); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1614,13 +1236,7 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 eid = ce.idMem(); store.setConfirmed(eid); store.setConfirmed(bargs.upperChildId1); - vm.expectRevert( - abi.encodeWithSelector( - EdgeNotPending.selector, - bargs.upperChildId1, - EdgeStatus.Confirmed - ) - ); + vm.expectRevert(abi.encodeWithSelector(EdgeNotPending.selector, bargs.upperChildId1, EdgeStatus.Confirmed)); store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } @@ -1663,18 +1279,13 @@ contract EdgeChallengeManagerLibTest is Test { store.confirmEdgeByClaim(bargs.upperChildId1, eid, NUM_BIGSTEP_LEVEL); } - function bisect( - ChallengeEdge memory edge, - bytes32[] memory states, - uint256 start, - uint256 end - ) internal returns (bytes32, bytes32) { + function bisect(ChallengeEdge memory edge, bytes32[] memory states, uint256 start, uint256 end) + internal + returns (bytes32, bytes32) + { (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(states, start, end); - (bytes32 lowerChildId, , EdgeAddedData memory upperChildAdded) = store.bisectEdge( - edge.idMem(), - bisectionRoot, - bisectionProof - ); + (bytes32 lowerChildId,, EdgeAddedData memory upperChildAdded) = + store.bisectEdge(edge.idMem(), bisectionRoot, bisectionProof); return (lowerChildId, upperChildAdded.edgeId); } @@ -1689,17 +1300,9 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] states2; } - function addParentsAndChildren( - uint256 start, - uint256 agree, - uint256 end - ) internal returns (BArgs memory) { - ( - ChallengeEdge memory edge1, - ChallengeEdge memory edge2, - bytes32[] memory states1, - bytes32[] memory states2 - ) = twoRivalsFromLeaves(start, agree, end); + function addParentsAndChildren(uint256 start, uint256 agree, uint256 end) internal returns (BArgs memory) { + (ChallengeEdge memory edge1, ChallengeEdge memory edge2, bytes32[] memory states1, bytes32[] memory states2) = + twoRivalsFromLeaves(start, agree, end); store.add(edge1); store.add(edge2); @@ -1707,17 +1310,9 @@ contract EdgeChallengeManagerLibTest is Test { (bytes32 lowerChildId1, bytes32 upperChildId1) = bisect(edge1, states1, start, end); (bytes32 lowerChildId2, bytes32 upperChildId2) = bisect(edge2, states2, start, end); - return - BArgs( - edge1.idMem(), - edge2.idMem(), - lowerChildId1, - upperChildId1, - lowerChildId2, - upperChildId2, - states1, - states2 - ); + return BArgs( + edge1.idMem(), edge2.idMem(), lowerChildId1, upperChildId1, lowerChildId2, upperChildId2, states1, states2 + ); } function claimWithMixedAncestors( @@ -1732,11 +1327,7 @@ contract EdgeChallengeManagerLibTest is Test { bytes memory revertArg; { (, bytes32 bisectionRoot, bytes memory bisectionProof) = bisectArgs(pc.states1, 4, 8); - (bytes32 lowerChildId148, , ) = store.bisectEdge( - pc.upperChildId1, - bisectionRoot, - bisectionProof - ); + (bytes32 lowerChildId148,,) = store.bisectEdge(pc.upperChildId1, bisectionRoot, bisectionProof); ancestorIds[1] = lowerChildId148; } vm.roll(block.number + timeAfterParent1); @@ -1745,25 +1336,14 @@ contract EdgeChallengeManagerLibTest is Test { { bytes32 lowerChildId248; { - (, bytes32 bisectionRoot2, bytes memory bisectionProof2) = bisectArgs( - pc.states2, - 4, - 8 - ); - (bytes32 lowerChildId248X, , ) = store.bisectEdge( - pc.upperChildId2, - bisectionRoot2, - bisectionProof2 - ); + (, bytes32 bisectionRoot2, bytes memory bisectionProof2) = bisectArgs(pc.states2, 4, 8); + (bytes32 lowerChildId248X,,) = store.bisectEdge(pc.upperChildId2, bisectionRoot2, bisectionProof2); lowerChildId248 = lowerChildId248X; } (, bytes32 bisectionRoot3, bytes memory bisectionProof3) = bisectArgs(pc.states1, 4, 6); - (, , EdgeAddedData memory upperChildId146Data) = store.bisectEdge( - ancestorIds[1], - bisectionRoot3, - bisectionProof3 - ); + (,, EdgeAddedData memory upperChildId146Data) = + store.bisectEdge(ancestorIds[1], bisectionRoot3, bisectionProof3); upperChildId146 = upperChildId146Data.edgeId; vm.roll(block.number + timeAfterParent2); @@ -1797,14 +1377,8 @@ contract EdgeChallengeManagerLibTest is Test { ancestorIds[2] = pc.upperChildId1; if (timeAfterParent1 == 137) { - ChallengeEdge memory childE1 = ChallengeEdgeLib.newChildEdge( - rand.hash(), - rand.hash(), - 10, - rand.hash(), - 100, - 0 - ); + ChallengeEdge memory childE1 = + ChallengeEdgeLib.newChildEdge(rand.hash(), rand.hash(), 10, rand.hash(), 100, 0); store.add(childE1); @@ -1851,33 +1425,18 @@ contract EdgeChallengeManagerLibTest is Test { store.add(bigStepZero2); store.setConfirmed(bigStepZero2.idMem()); store.setConfirmedRival(bigStepZero2.idMem()); - revertArg = abi.encodeWithSelector( - RivalEdgeConfirmed.selector, - bsId, - bigStepZero2.idMem() - ); + revertArg = abi.encodeWithSelector(RivalEdgeConfirmed.selector, bsId, bigStepZero2.idMem()); } - if ( - timeAfterParent1 + timeAfterParent2 + timeAfterZeroLayer + claimedAssertionBlocks == 4 - ) { - revertArg = abi.encodeWithSelector( - InsufficientConfirmationBlocks.selector, - 4, - challengePeriodBlock - ); + if (timeAfterParent1 + timeAfterParent2 + timeAfterZeroLayer + claimedAssertionBlocks == 4) { + revertArg = abi.encodeWithSelector(InsufficientConfirmationBlocks.selector, 4, challengePeriodBlock); } if (revertArg.length != 0) { vm.expectRevert(revertArg); } - uint256 totalTime = store.confirmEdgeByTime( - bsId, - ancestorIds, - claimedAssertionBlocks, - challengePeriodBlock, - NUM_BIGSTEP_LEVEL - ); + uint256 totalTime = + store.confirmEdgeByTime(bsId, ancestorIds, claimedAssertionBlocks, challengePeriodBlock, NUM_BIGSTEP_LEVEL); if (revertArg.length == 0) { assertTrue(store.get(bsId).status == EdgeStatus.Confirmed, "Edge confirmed"); @@ -1946,11 +1505,7 @@ contract EdgeChallengeManagerLibTest is Test { function confirmByOneStep(uint256 flag) internal { uint256 startHeight = 5; - (bytes32[] memory states1, bytes32[] memory states2) = rivalStates( - startHeight, - startHeight, - startHeight + 1 - ); + (bytes32[] memory states1, bytes32[] memory states2) = rivalStates(startHeight, startHeight, startHeight + 1); ConfirmByOneStepData memory data; data.e1 = ChallengeEdgeLib.newChildEdge( @@ -1993,27 +1548,18 @@ contract EdgeChallengeManagerLibTest is Test { if (flag != 4) { store.add(data.e2); } - OneStepData memory d = OneStepData({ - beforeHash: states1[startHeight], - proof: abi.encodePacked(states1[startHeight + 1]) - }); - ExecutionContext memory e = ExecutionContext({ - maxInboxMessagesRead: 0, - bridge: IBridge(address(0)), - initialWasmModuleRoot: bytes32(0) - }); + OneStepData memory d = + OneStepData({beforeHash: states1[startHeight], proof: abi.encodePacked(states1[startHeight + 1])}); + ExecutionContext memory e = + ExecutionContext({maxInboxMessagesRead: 0, bridge: IBridge(address(0)), initialWasmModuleRoot: bytes32(0)}); bytes32[] memory beforeProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, startHeight + 1)), - startHeight + ProofUtils.rehashed(ArrayUtilsLib.slice(states1, 0, startHeight + 1)), startHeight ); if (flag == 6) { beforeProof[0] = rand.hash(); data.revertArg = "Invalid inclusion proof"; } - bytes32[] memory afterProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states1), - startHeight + 1 - ); + bytes32[] memory afterProof = ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), startHeight + 1); if (flag == 7) { afterProof[0] = rand.hash(); data.revertArg = "Invalid inclusion proof"; @@ -2025,25 +1571,13 @@ contract EdgeChallengeManagerLibTest is Test { if (flag == 9) { store.setConfirmed(data.e2.idMem()); store.setConfirmedRival(data.e2.idMem()); - data.revertArg = abi.encodeWithSelector( - RivalEdgeConfirmed.selector, - data.e1.idMem(), - data.e2.idMem() - ); + data.revertArg = abi.encodeWithSelector(RivalEdgeConfirmed.selector, data.e1.idMem(), data.e2.idMem()); } if (data.revertArg.length != 0) { vm.expectRevert(data.revertArg); } - store.confirmEdgeByOneStepProof( - eid, - entry, - d, - e, - beforeProof, - afterProof, - NUM_BIGSTEP_LEVEL - ); + store.confirmEdgeByOneStepProof(eid, entry, d, e, beforeProof, afterProof, NUM_BIGSTEP_LEVEL); if (bytes(data.revertArg).length != 0) { // for flag one the edge does not exist @@ -2053,11 +1587,7 @@ contract EdgeChallengeManagerLibTest is Test { } } else { assertTrue(store.get(eid).status == EdgeStatus.Confirmed, "Edge confirmed"); - assertEq( - store.getConfirmedRival(ChallengeEdgeLib.mutualIdMem(data.e1)), - eid, - "Confirmed rival" - ); + assertEq(store.getConfirmedRival(ChallengeEdgeLib.mutualIdMem(data.e1)), eid, "Confirmed rival"); } } @@ -2107,7 +1637,7 @@ contract EdgeChallengeManagerLibTest is Test { assertEq(store.isPowerOfTwo(6), false); assertEq(store.isPowerOfTwo(7), false); assertEq(store.isPowerOfTwo(8), true); - assertEq(store.isPowerOfTwo(2**17), true); + assertEq(store.isPowerOfTwo(2 ** 17), true); assertEq(store.isPowerOfTwo(1 << 255), true); } @@ -2120,12 +1650,10 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] prefixProof; } - function newRootsAndProofs( - uint256 startHeight, - uint256 endHeight, - bytes32 startState, - bytes32 endState - ) internal returns (ExpsAndProofs memory) { + function newRootsAndProofs(uint256 startHeight, uint256 endHeight, bytes32 startState, bytes32 endState) + internal + returns (ExpsAndProofs memory) + { bytes32[] memory states; { if (startState == 0) { @@ -2140,38 +1668,21 @@ contract EdgeChallengeManagerLibTest is Test { startStates[0] = startState; bytes32[] memory endStates = new bytes32[](1); endStates[0] = endState; - states = ArrayUtilsLib.concat( - ArrayUtilsLib.concat(startStates, innerStates), - endStates - ); + states = ArrayUtilsLib.concat(ArrayUtilsLib.concat(startStates, innerStates), endStates); } bytes32[] memory startExp = ProofUtils.expansionFromLeaves(states, 0, startHeight + 1); bytes32[] memory expansion = ProofUtils.expansionFromLeaves(states, 0, endHeight + 1); // inclusion in the start root bytes32[] memory startInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(states, 0, startHeight + 1)), - startHeight - ); - bytes32[] memory endInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states), - endHeight + ProofUtils.rehashed(ArrayUtilsLib.slice(states, 0, startHeight + 1)), startHeight ); + bytes32[] memory endInclusionProof = ProofUtils.generateInclusionProof(ProofUtils.rehashed(states), endHeight); - bytes32[] memory prefixProof = ProofUtils.generatePrefixProof( - startHeight + 1, - ArrayUtilsLib.slice(states, startHeight + 1, endHeight + 1) - ); + bytes32[] memory prefixProof = + ProofUtils.generatePrefixProof(startHeight + 1, ArrayUtilsLib.slice(states, startHeight + 1, endHeight + 1)); - return - ExpsAndProofs( - states, - startExp, - expansion, - startInclusionProof, - endInclusionProof, - prefixProof - ); + return ExpsAndProofs(states, startExp, expansion, startInclusionProof, endInclusionProof, prefixProof); } struct ExecStateVars { @@ -2181,10 +1692,7 @@ contract EdgeChallengeManagerLibTest is Test { function randomExecutionState(IOneStepProofEntry os) private returns (ExecStateVars memory) { ExecutionState memory execState = ExecutionState( - GlobalState( - [rand.hash(), rand.hash()], - [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))] - ), + GlobalState([rand.hash(), rand.hash()], [uint64(uint256(rand.hash())), uint64(uint256(rand.hash()))]), MachineStatus.FINISHED ); @@ -2195,20 +1703,15 @@ contract EdgeChallengeManagerLibTest is Test { function createZeroBlockEdge(uint256 mode) internal { bytes memory revertArg; MockOneStepProofEntry entry = new MockOneStepProofEntry(); - uint256 expectedEndHeight = 2**2; + uint256 expectedEndHeight = 2 ** 2; if (mode == 139) { - expectedEndHeight = 2**5 - 1; + expectedEndHeight = 2 ** 5 - 1; revertArg = abi.encodeWithSelector(NotPowerOfTwo.selector, expectedEndHeight); } ExecStateVars memory startExec = randomExecutionState(entry); ExecStateVars memory endExec = randomExecutionState(entry); - ExpsAndProofs memory roots = newRootsAndProofs( - 0, - expectedEndHeight, - startExec.machineHash, - endExec.machineHash - ); + ExpsAndProofs memory roots = newRootsAndProofs(0, expectedEndHeight, startExec.machineHash, endExec.machineHash); bytes32 claimId = rand.hash(); bytes32 endRoot; if (mode == 137) { @@ -2229,11 +1732,7 @@ contract EdgeChallengeManagerLibTest is Test { }); if (mode == 141) { ard.assertionHash = rand.hash(); - revertArg = abi.encodeWithSelector( - AssertionHashMismatch.selector, - ard.assertionHash, - claimId - ); + revertArg = abi.encodeWithSelector(AssertionHashMismatch.selector, ard.assertionHash, claimId); } if (mode == 142) { ard.isPending = false; @@ -2277,8 +1776,8 @@ contract EdgeChallengeManagerLibTest is Test { proof: proof }); if (mode == 138) { - args.endHeight = 2**4; - revertArg = abi.encodeWithSelector(InvalidEndHeight.selector, 2**4, expectedEndHeight); + args.endHeight = 2 ** 4; + revertArg = abi.encodeWithSelector(InvalidEndHeight.selector, 2 ** 4, expectedEndHeight); } if (mode == 148) { args.prefixProof = ""; @@ -2288,21 +1787,13 @@ contract EdgeChallengeManagerLibTest is Test { if (revertArg.length != 0) { vm.expectRevert(revertArg); } - EdgeAddedData memory addedEdge = store.createLayerZeroEdge( - args, - ard, - entry, - expectedEndHeight, - NUM_BIGSTEP_LEVEL - ); + EdgeAddedData memory addedEdge = + store.createLayerZeroEdge(args, ard, entry, expectedEndHeight, NUM_BIGSTEP_LEVEL); if (revertArg.length == 0) { assertEq( store.get(addedEdge.edgeId).startHistoryRoot, MerkleTreeLib.root( - MerkleTreeLib.appendLeaf( - new bytes32[](0), - mockOsp.getMachineHash(startExec.execState) - ) + MerkleTreeLib.appendLeaf(new bytes32[](0), mockOsp.getMachineHash(startExec.execState)) ), "Start history root" ); @@ -2361,12 +1852,10 @@ contract EdgeChallengeManagerLibTest is Test { createZeroBlockEdge(148); } - function createClaimEdge( - EdgeChallengeManagerLibAccess c, - uint256 start, - uint256 end, - bool includeRival - ) public returns (bytes32, ExpsAndProofs memory) { + function createClaimEdge(EdgeChallengeManagerLibAccess c, uint256 start, uint256 end, bool includeRival) + public + returns (bytes32, ExpsAndProofs memory) + { // create a claim edge ExpsAndProofs memory claimRoots = newRootsAndProofs(start, end, 0, 0); ChallengeEdge memory ce = ChallengeEdgeLib.newChildEdge( @@ -2382,12 +1871,7 @@ contract EdgeChallengeManagerLibTest is Test { if (includeRival) { c.add( ChallengeEdgeLib.newChildEdge( - ce.originId, - ce.startHistoryRoot, - ce.startHeight, - rand.hash(), - ce.endHeight, - ce.level + ce.originId, ce.startHistoryRoot, ce.startHeight, rand.hash(), ce.endHeight, ce.level ) ); } @@ -2414,24 +1898,14 @@ contract EdgeChallengeManagerLibTest is Test { vars.claimStartHeight = 4; vars.claimEndHeight = mode == 161 ? 6 : 5; - vars.expectedEndHeight = 2**5; - (vars.claimId, vars.claimRoots) = createClaimEdge( - store, - vars.claimStartHeight, - vars.claimEndHeight, - mode == 160 ? false : true - ); + vars.expectedEndHeight = 2 ** 5; + (vars.claimId, vars.claimRoots) = + createClaimEdge(store, vars.claimStartHeight, vars.claimEndHeight, mode == 160 ? false : true); if (mode == 160) { - vars.revertArg = abi.encodeWithSelector( - ClaimEdgeNotLengthOneRival.selector, - vars.claimId - ); + vars.revertArg = abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, vars.claimId); } if (mode == 161) { - vars.revertArg = abi.encodeWithSelector( - ClaimEdgeNotLengthOneRival.selector, - vars.claimId - ); + vars.revertArg = abi.encodeWithSelector(ClaimEdgeNotLengthOneRival.selector, vars.claimId); } vars.roots = newRootsAndProofs( @@ -2443,19 +1917,13 @@ contract EdgeChallengeManagerLibTest is Test { if (mode == 164) { bytes32[] memory b = new bytes32[](1); b[0] = rand.hash(); - vars.claimRoots.startInclusionProof = ArrayUtilsLib.concat( - vars.claimRoots.startInclusionProof, - b - ); + vars.claimRoots.startInclusionProof = ArrayUtilsLib.concat(vars.claimRoots.startInclusionProof, b); vars.revertArg = "Invalid inclusion proof"; } if (mode == 165) { bytes32[] memory b = new bytes32[](1); b[0] = rand.hash(); - vars.claimRoots.endInclusionProof = ArrayUtilsLib.concat( - vars.claimRoots.endInclusionProof, - b - ); + vars.claimRoots.endInclusionProof = ArrayUtilsLib.concat(vars.claimRoots.endInclusionProof, b); vars.revertArg = "Invalid inclusion proof"; } vars.proof = abi.encode( @@ -2463,10 +1931,7 @@ contract EdgeChallengeManagerLibTest is Test { vars.roots.states[vars.expectedEndHeight], vars.claimRoots.startInclusionProof, vars.claimRoots.endInclusionProof, - ProofUtils.generateInclusionProof( - ProofUtils.rehashed(vars.roots.states), - vars.expectedEndHeight - ) + ProofUtils.generateInclusionProof(ProofUtils.rehashed(vars.roots.states), vars.expectedEndHeight) ); if (mode == 166) { vars.proof = ""; @@ -2481,11 +1946,8 @@ contract EdgeChallengeManagerLibTest is Test { vars.emptyArd; if (mode == 163) { - vars.revertArg = abi.encodeWithSelector( - ClaimEdgeInvalidLevel.selector, - NUM_BIGSTEP_LEVEL, - NUM_BIGSTEP_LEVEL - ); + vars.revertArg = + abi.encodeWithSelector(ClaimEdgeInvalidLevel.selector, NUM_BIGSTEP_LEVEL, NUM_BIGSTEP_LEVEL); } if (vars.revertArg.length != 0) { vm.expectRevert(vars.revertArg); @@ -2547,8 +2009,7 @@ contract EdgeChallengeManagerLibTest is Test { } bytes32 genesisBlockHash = rand.hash(); - ExecutionState genesisState = - StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); + ExecutionState genesisState = StateToolsLib.randomState(rand, 4, genesisBlockHash, MachineStatus.FINISHED); bytes32 genesisStateHash = StateToolsLib.mockMachineHash(genesisState); ExecutionStateData genesisStateData = ExecutionStateData(genesisState, bytes32(0), bytes32(0)); bytes32 genesisAssertionHash = rand.hash(); @@ -2579,23 +2040,20 @@ contract EdgeChallengeManagerLibTest is Test { ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states, 1, states.length)) ); - return - store - .createLayerZeroEdge( - CreateEdgeArgs({ - level: 0, - endHistoryRoot: MerkleTreeLib.root(exp), - endHeight: height1, - claimId: claimId, - prefixProof: prefixProof, - proof: typeSpecificProof1 - }), - ard, - mockOsp, - expectedEndHeight, - numBigStepLevel - ) - .edgeId; + return store.createLayerZeroEdge( + CreateEdgeArgs({ + level: 0, + endHistoryRoot: MerkleTreeLib.root(exp), + endHeight: height1, + claimId: claimId, + prefixProof: prefixProof, + proof: typeSpecificProof1 + }), + ard, + mockOsp, + expectedEndHeight, + numBigStepLevel + ).edgeId; } struct BisectionChildren { @@ -2611,16 +2069,14 @@ contract EdgeChallengeManagerLibTest is Test { bool skipLast; } - function bisect( - bytes32 edgeId, - bytes32[] memory states, - uint256 bisectionSize, - uint256 endSize - ) internal returns (BisectionChildren memory) { + function bisect(bytes32 edgeId, bytes32[] memory states, uint256 bisectionSize, uint256 endSize) + internal + returns (BisectionChildren memory) + { bytes32[] memory middleExp = ProofUtils.expansionFromLeaves(states, 0, bisectionSize + 1); bytes32[] memory upperStates = ArrayUtilsLib.slice(states, bisectionSize + 1, endSize + 1); - (bytes32 lowerChildId, , EdgeAddedData memory upperChild) = store.bisectEdge( + (bytes32 lowerChildId,, EdgeAddedData memory upperChild) = store.bisectEdge( edgeId, MerkleTreeLib.root(middleExp), abi.encode(middleExp, ProofUtils.generatePrefixProof(bisectionSize + 1, upperStates)) @@ -2640,18 +2096,8 @@ contract EdgeChallengeManagerLibTest is Test { losingEdges[5] = BisectionChildren(args.losingId, 0); // height 16 - winningEdges[4] = bisect( - winningEdges[5].lowerChildId, - args.winningLeaves, - 16, - args.winningLeaves.length - 1 - ); - losingEdges[4] = bisect( - losingEdges[5].lowerChildId, - args.losingLeaves, - 16, - args.losingLeaves.length - 1 - ); + winningEdges[4] = bisect(winningEdges[5].lowerChildId, args.winningLeaves, 16, args.winningLeaves.length - 1); + losingEdges[4] = bisect(losingEdges[5].lowerChildId, args.losingLeaves, 16, args.losingLeaves.length - 1); // height 8 winningEdges[3] = bisect(winningEdges[4].lowerChildId, args.winningLeaves, 8, 16); @@ -2675,36 +2121,21 @@ contract EdgeChallengeManagerLibTest is Test { function createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs memory args) internal - returns ( - bytes32[] memory, - bytes32[] memory, - BisectionChildren[6] memory, - BisectionChildren[6] memory - ) + returns (bytes32[] memory, bytes32[] memory, BisectionChildren[6] memory, BisectionChildren[6] memory) { bytes32[] memory states1; bytes32 edge1Id; { bytes32[] memory exp1; - (states1, exp1) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(args.endState1), - height1 - ); + (states1, exp1) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState1), height1); edge1Id = createLayerZeroEdge( args.claim1Id, args.endState1, states1, exp1, - AssertionReferenceData( - args.claim1Id, - genesisAssertionHash, - true, - true, - genesisState, - args.endState1 - ), + AssertionReferenceData(args.claim1Id, genesisAssertionHash, true, true, genesisState, args.endState1), 32, 1 ); @@ -2718,28 +2149,11 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 edge2Id; { bytes32[] memory exp2; - (states2, exp2) = appendRandomStatesBetween( - genesisStates(), - StateToolsLib.mockMachineHash(args.endState2), - height1 - ); - AssertionReferenceData memory ard2 = AssertionReferenceData( - args.claim2Id, - genesisAssertionHash, - true, - true, - genesisState, - args.endState2 - ); - edge2Id = createLayerZeroEdge( - args.claim2Id, - args.endState2, - states2, - exp2, - ard2, - 32, - 1 - ); + (states2, exp2) = + appendRandomStatesBetween(genesisStates(), StateToolsLib.mockMachineHash(args.endState2), height1); + AssertionReferenceData memory ard2 = + AssertionReferenceData(args.claim2Id, genesisAssertionHash, true, true, genesisState, args.endState2); + edge2Id = createLayerZeroEdge(args.claim2Id, args.endState2, states2, exp2, ard2, 32, 1); vm.roll(block.number + 2); @@ -2747,9 +2161,8 @@ contract EdgeChallengeManagerLibTest is Test { assertEq(store.timeUnrivaled(edge2Id), 0, "Edge2 timer 2"); } - (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast) - ); + (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = + bisectToForkOnly(BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast)); return (states1, states2, edges1, edges2); } @@ -2778,27 +2191,19 @@ contract EdgeChallengeManagerLibTest is Test { internal returns (BisectionData memory) { - (bytes32[] memory states1, bytes32[] memory exp1) = appendRandomStatesBetween( - genesisStates(), - args.endState1, - height1 - ); + (bytes32[] memory states1, bytes32[] memory exp1) = + appendRandomStatesBetween(genesisStates(), args.endState1, height1); bytes32 edge1Id; { bytes memory typeSpecificProof1; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(args.forkStates1), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states1), - states1.length - 1 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates1, 0, 1)), 0 ); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates1), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states1), states1.length - 1); typeSpecificProof1 = abi.encode( genesisStateHash, args.endState1, @@ -2807,55 +2212,42 @@ contract EdgeChallengeManagerLibTest is Test { edgeInclusionProof ); } - edge1Id = store - .createLayerZeroEdge( - CreateEdgeArgs({ - level: args.eType, - endHistoryRoot: MerkleTreeLib.root(exp1), - endHeight: height1, - claimId: args.claim1Id, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states1, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states1, 1, states1.length) - ) + edge1Id = store.createLayerZeroEdge( + CreateEdgeArgs({ + level: args.eType, + endHistoryRoot: MerkleTreeLib.root(exp1), + endHeight: height1, + claimId: args.claim1Id, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states1, 0, 1), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states1, 1, states1.length)) ), - proof: typeSpecificProof1 - }), - emptyArd, - mockOsp, - 32, - 1 - ) - .edgeId; + proof: typeSpecificProof1 + }), + emptyArd, + mockOsp, + 32, + 1 + ).edgeId; } vm.roll(block.number + 1); assertEq(store.timeUnrivaled(edge1Id), 1, "Edge1 timer"); - (bytes32[] memory states2, bytes32[] memory exp2) = appendRandomStatesBetween( - genesisStates(), - args.endState2, - height1 - ); + (bytes32[] memory states2, bytes32[] memory exp2) = + appendRandomStatesBetween(genesisStates(), args.endState2, height1); bytes32 edge2Id; { bytes memory typeSpecificProof2; { bytes32[] memory claimStartInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), - 0 - ); - bytes32[] memory claimEndInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(args.forkStates2), - 1 - ); - bytes32[] memory edgeInclusionProof = ProofUtils.generateInclusionProof( - ProofUtils.rehashed(states2), - states2.length - 1 + ProofUtils.rehashed(ArrayUtilsLib.slice(args.forkStates2, 0, 1)), 0 ); + bytes32[] memory claimEndInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(args.forkStates2), 1); + bytes32[] memory edgeInclusionProof = + ProofUtils.generateInclusionProof(ProofUtils.rehashed(states2), states2.length - 1); typeSpecificProof2 = abi.encode( genesisStateHash, args.endState2, @@ -2864,35 +2256,29 @@ contract EdgeChallengeManagerLibTest is Test { edgeInclusionProof ); } - edge2Id = store - .createLayerZeroEdge( - CreateEdgeArgs({ - level: args.eType, - endHistoryRoot: MerkleTreeLib.root(exp2), - endHeight: height1, - claimId: args.claim2Id, - prefixProof: abi.encode( - ProofUtils.expansionFromLeaves(states2, 0, 1), - ProofUtils.generatePrefixProof( - 1, - ArrayUtilsLib.slice(states2, 1, states2.length) - ) + edge2Id = store.createLayerZeroEdge( + CreateEdgeArgs({ + level: args.eType, + endHistoryRoot: MerkleTreeLib.root(exp2), + endHeight: height1, + claimId: args.claim2Id, + prefixProof: abi.encode( + ProofUtils.expansionFromLeaves(states2, 0, 1), + ProofUtils.generatePrefixProof(1, ArrayUtilsLib.slice(states2, 1, states2.length)) ), - proof: typeSpecificProof2 - }), - emptyArd, - mockOsp, - 32, - 1 - ) - .edgeId; + proof: typeSpecificProof2 + }), + emptyArd, + mockOsp, + 32, + 1 + ).edgeId; } vm.roll(block.number + 2); - (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = bisectToForkOnly( - BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast) - ); + (BisectionChildren[6] memory edges1, BisectionChildren[6] memory edges2) = + bisectToForkOnly(BisectToForkOnlyArgs(edge1Id, edge2Id, states1, states2, args.skipLast)); return BisectionData(states1, states2, edges1, edges2); } @@ -2905,16 +2291,10 @@ contract EdgeChallengeManagerLibTest is Test { bytes32 h1 = rand.hash(); bytes32 h2 = rand.hash(); ExecutionState memory a1State = StateToolsLib.randomState( - rand, - GlobalStateLib.getInboxPosition(genesisState.globalState), - h1, - MachineStatus.FINISHED + rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h1, MachineStatus.FINISHED ); ExecutionState memory a2State = StateToolsLib.randomState( - rand, - GlobalStateLib.getInboxPosition(genesisState.globalState), - h2, - MachineStatus.FINISHED + rand, GlobalStateLib.getInboxPosition(genesisState.globalState), h2, MachineStatus.FINISHED ); ( @@ -2922,9 +2302,7 @@ contract EdgeChallengeManagerLibTest is Test { bytes32[] memory blockStates2, BisectionChildren[6] memory blockEdges1, BisectionChildren[6] memory blockEdges2 - ) = createBlockEdgesAndBisectToFork( - CreateBlockEdgesBisectArgs(a1, a2, a1State, a2State, false) - ); + ) = createBlockEdgesAndBisectToFork(CreateBlockEdgesBisectArgs(a1, a2, a1State, a2State, false)); BisectionData memory bsbd = createMachineEdgesAndBisectToFork( CreateMachineEdgesBisectArgs( @@ -2953,14 +2331,10 @@ contract EdgeChallengeManagerLibTest is Test { ); assertEq( - store.getPrevAssertionHash(blockEdges1[5].lowerChildId), - genesisAssertionHash, - "Block level winning edge" + store.getPrevAssertionHash(blockEdges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(blockEdges2[5].lowerChildId), - genesisAssertionHash, - "Block level losing edge" + store.getPrevAssertionHash(blockEdges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { @@ -2987,14 +2361,10 @@ contract EdgeChallengeManagerLibTest is Test { } assertEq( - store.getPrevAssertionHash(bsbd.edges1[5].lowerChildId), - genesisAssertionHash, - "Block level winning edge" + store.getPrevAssertionHash(bsbd.edges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(bsbd.edges2[5].lowerChildId), - genesisAssertionHash, - "Block level losing edge" + store.getPrevAssertionHash(bsbd.edges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { @@ -3021,14 +2391,10 @@ contract EdgeChallengeManagerLibTest is Test { } assertEq( - store.getPrevAssertionHash(ssbd.edges1[5].lowerChildId), - genesisAssertionHash, - "Block level winning edge" + store.getPrevAssertionHash(ssbd.edges1[5].lowerChildId), genesisAssertionHash, "Block level winning edge" ); assertEq( - store.getPrevAssertionHash(ssbd.edges2[5].lowerChildId), - genesisAssertionHash, - "Block level losing edge" + store.getPrevAssertionHash(ssbd.edges2[5].lowerChildId), genesisAssertionHash, "Block level losing edge" ); for (uint256 x = 0; x < 5; x++) { diff --git a/contracts/test/challengeV2/MerkleTreeLib.t.sol b/contracts/test/challengeV2/MerkleTreeLib.t.sol index db3cd70f2..81ea0f793 100644 --- a/contracts/test/challengeV2/MerkleTreeLib.t.sol +++ b/contracts/test/challengeV2/MerkleTreeLib.t.sol @@ -48,11 +48,7 @@ contract MerkleTreeLibTest is Test { function expansionsFromLeaves(bytes32[] memory leaves, uint256 lowSize) public pure - returns ( - bytes32[] memory, - bytes32[] memory, - bytes32[] memory - ) + returns (bytes32[] memory, bytes32[] memory, bytes32[] memory) { bytes32[] memory lowExpansion = new bytes32[](0); bytes32[] memory highExpansion = new bytes32[](0); @@ -73,21 +69,13 @@ contract MerkleTreeLibTest is Test { function proveVerify(uint256 startSize, uint256 endSize) internal { bytes32[] memory leaves = random.hashes(endSize); - ( - bytes32[] memory lowExp, - bytes32[] memory highExp, - bytes32[] memory diff - ) = expansionsFromLeaves(leaves, startSize); + (bytes32[] memory lowExp, bytes32[] memory highExp, bytes32[] memory diff) = + expansionsFromLeaves(leaves, startSize); bytes32[] memory proof = ProofUtils.generatePrefixProof(startSize, diff); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(lowExp), - startSize, - MerkleTreeLib.root(highExp), - endSize, - lowExp, - proof + MerkleTreeLib.root(lowExp), startSize, MerkleTreeLib.root(highExp), endSize, lowExp, proof ); } @@ -152,10 +140,7 @@ contract MerkleTreeLibTest is Test { function testRoot5() public { bytes32[] memory expansion = getExpansion(5); - bytes32 expectedRoot = hashTogether( - expansion[2], - hashTogether(hashTogether(expansion[0], 0), 0) - ); + bytes32 expectedRoot = hashTogether(expansion[2], hashTogether(hashTogether(expansion[0], 0), 0)); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -167,10 +152,7 @@ contract MerkleTreeLibTest is Test { function testRoot7() public { bytes32[] memory expansion = getExpansion(7); - bytes32 expectedRoot = hashTogether( - expansion[2], - hashTogether(expansion[1], hashTogether(expansion[0], 0)) - ); + bytes32 expectedRoot = hashTogether(expansion[2], hashTogether(expansion[1], hashTogether(expansion[0], 0))); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -182,19 +164,14 @@ contract MerkleTreeLibTest is Test { function testRoot9() public { bytes32[] memory expansion = getExpansion(9); - bytes32 expectedRoot = hashTogether( - expansion[3], - hashTogether(hashTogether(hashTogether(expansion[0], 0), 0), 0) - ); + bytes32 expectedRoot = + hashTogether(expansion[3], hashTogether(hashTogether(hashTogether(expansion[0], 0), 0), 0)); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } function testRoot11() public { bytes32[] memory expansion = getExpansion(10); - bytes32 expectedRoot = hashTogether( - expansion[3], - hashTogether(hashTogether(expansion[1], 0), 0) - ); + bytes32 expectedRoot = hashTogether(expansion[3], hashTogether(hashTogether(expansion[1], 0), 0)); assertEq(MerkleTreeLib.root(expansion), expectedRoot, "Invalid root"); } @@ -243,7 +220,7 @@ contract MerkleTreeLibTest is Test { uint256 preSize = MerkleTreeLib.treeSize(expansion); uint256 postSize = MerkleTreeLib.treeSize(post); - assertEq(postSize, preSize + (2**i), "Sizes"); + assertEq(postSize, preSize + (2 ** i), "Sizes"); } } @@ -282,11 +259,7 @@ contract MerkleTreeLibTest is Test { if (i == level || i == level + 1) { assertEq(post[i], 0, "Post level equal"); } else if (i == level + 2) { - assertEq( - post[i], - hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), - "Post level plus 1 equal" - ); + assertEq(post[i], hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), "Post level plus 1 equal"); } else { assertEq(pre[i], post[i], "Pre post equal"); } @@ -305,11 +278,7 @@ contract MerkleTreeLibTest is Test { if (i == level || i == level + 1) { assertEq(post[i], 0, "Post level equal"); } else if (i == level + 2) { - assertEq( - post[i], - hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), - "Post level plus 1 equal" - ); + assertEq(post[i], hashTogether(pre[i - 1], hashTogether(pre[i - 2], rand)), "Post level plus 1 equal"); } else { assertEq(pre[i], post[i], "Pre post equal"); } @@ -530,14 +499,7 @@ contract MerkleTreeLibTest is Test { proof[0] = rehashedLeaves[0]; proof[1] = hashTogether(rehashedLeaves[1], rehashedLeaves[2]); proof[2] = rehashedLeaves[3]; - MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), - 5, - MerkleTreeLib.root(post), - 9, - pre, - proof - ); + MerkleTreeLib.verifyPrefixProof(MerkleTreeLib.root(pre), 5, MerkleTreeLib.root(post), 9, pre, proof); } function testVerifyPrefixProofPreZero() public { @@ -554,12 +516,7 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Pre-size cannot be 0"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), - 0, - MerkleTreeLib.root(post), - preSize + newLeavesCount, - pre, - proof + MerkleTreeLib.root(pre), 0, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof ); } @@ -578,12 +535,7 @@ contract MerkleTreeLibTest is Test { bytes32 randomHash = random.hash(); vm.expectRevert("Pre expansion root mismatch"); MerkleTreeLib.verifyPrefixProof( - randomHash, - preSize, - MerkleTreeLib.root(post), - preSize + newLeavesCount, - pre, - proof + randomHash, preSize, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof ); } @@ -601,14 +553,7 @@ contract MerkleTreeLibTest is Test { bytes32[] memory proof = ProofUtils.generatePrefixProof(preSize, newLeaves); vm.expectRevert("Pre size not less than post size"); - MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), - preSize, - MerkleTreeLib.root(post), - preSize, - pre, - proof - ); + MerkleTreeLib.verifyPrefixProof(MerkleTreeLib.root(pre), preSize, MerkleTreeLib.root(post), preSize, pre, proof); } function testVerifyPrefixProofInvalidProofSize() public { @@ -627,12 +572,7 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Incomplete proof usage"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), - preSize, - MerkleTreeLib.root(post), - preSize + newLeavesCount, - pre, - proof + MerkleTreeLib.root(pre), preSize, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof ); } @@ -651,12 +591,7 @@ contract MerkleTreeLibTest is Test { vm.expectRevert("Pre size does not match expansion"); MerkleTreeLib.verifyPrefixProof( - MerkleTreeLib.root(pre), - preSize - 1, - MerkleTreeLib.root(post), - preSize + newLeavesCount, - pre, - proof + MerkleTreeLib.root(pre), preSize - 1, MerkleTreeLib.root(post), preSize + newLeavesCount, pre, proof ); } @@ -672,10 +607,7 @@ contract MerkleTreeLibTest is Test { proof[0] = re[5]; proof[1] = hashTogether(re[6], re[7]); proof[2] = hashTogether(hashTogether(re[0], re[1]), hashTogether(re[2], re[3])); - proof[3] = hashTogether( - hashTogether(hashTogether(re[8], re[9]), hashTogether(re[10], 0)), - 0 - ); + proof[3] = hashTogether(hashTogether(hashTogether(re[8], re[9]), hashTogether(re[10], 0)), 0); MerkleTreeLib.verifyInclusionProof(MerkleTreeLib.root(me), leaves[index], index, proof); } diff --git a/contracts/test/challengeV2/StateTools.sol b/contracts/test/challengeV2/StateTools.sol index f0c00e19f..faacbf586 100644 --- a/contracts/test/challengeV2/StateTools.sol +++ b/contracts/test/challengeV2/StateTools.sol @@ -13,12 +13,10 @@ import "./Utils.sol"; library StateToolsLib { using GlobalStateLib for GlobalState; - function randomState( - Random rand, - uint256 inboxMsgCountProcessed, - bytes32 blockHash, - MachineStatus ms - ) internal returns (ExecutionState memory) { + function randomState(Random rand, uint256 inboxMsgCountProcessed, bytes32 blockHash, MachineStatus ms) + internal + returns (ExecutionState memory) + { bytes32[2] memory bytes32Vals = [blockHash, rand.hash()]; uint64[2] memory u64Vals = [uint64(inboxMsgCountProcessed), uint64(uint256(rand.hash()))]; diff --git a/contracts/test/challengeV2/UintUtilsLib.t.sol b/contracts/test/challengeV2/UintUtilsLib.t.sol index d01b0cfb5..172c982e7 100644 --- a/contracts/test/challengeV2/UintUtilsLib.t.sol +++ b/contracts/test/challengeV2/UintUtilsLib.t.sol @@ -28,10 +28,7 @@ contract UintUtilsLibTest is Test { assertEq(UintUtilsLib.leastSignificantBit(10), 1); // 1010 assertEq(UintUtilsLib.leastSignificantBit(696320), 13); // 10101010000000000000 assertEq(UintUtilsLib.leastSignificantBit(696321), 0); // 10101010000000000001 - assertEq( - UintUtilsLib.leastSignificantBit(236945758459398306981350710526416285671374848), - 14 - ); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 + assertEq(UintUtilsLib.leastSignificantBit(236945758459398306981350710526416285671374848), 14); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 assertEq(UintUtilsLib.leastSignificantBit(type(uint256).max), 0); } @@ -61,10 +58,7 @@ contract UintUtilsLibTest is Test { assertEq(UintUtilsLib.mostSignificantBit(10), 3); // 1010 assertEq(UintUtilsLib.mostSignificantBit(696320), 19); // 10101010000000000000 assertEq(UintUtilsLib.mostSignificantBit(696321), 19); // 10101010000000000001 - assertEq( - UintUtilsLib.mostSignificantBit(236945758459398306981350710526416285671374848), - 147 - ); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 + assertEq(UintUtilsLib.mostSignificantBit(236945758459398306981350710526416285671374848), 147); // 1010101000000000000100000000010101010100000000000010101000000000000000001010100000000000010101001000101010000000000000000010100001000100000000000000 assertEq(UintUtilsLib.mostSignificantBit(type(uint256).max), 255); } diff --git a/contracts/test/challengeV2/Utils.sol b/contracts/test/challengeV2/Utils.sol index c1606c47c..0a88cc311 100644 --- a/contracts/test/challengeV2/Utils.sol +++ b/contracts/test/challengeV2/Utils.sol @@ -46,11 +46,11 @@ library ProofUtils { /// @param leaves The leaves to form into an expansion /// @param leafStartIndex The subset of the leaves to start the expansion from - inclusive /// @param leafEndIndex The subset of the leaves to end the expansion from - exclusive - function expansionFromLeaves( - bytes32[] memory leaves, - uint256 leafStartIndex, - uint256 leafEndIndex - ) internal pure returns (bytes32[] memory) { + function expansionFromLeaves(bytes32[] memory leaves, uint256 leafStartIndex, uint256 leafEndIndex) + internal + pure + returns (bytes32[] memory) + { require(leafStartIndex < leafEndIndex, "Leaf start not less than leaf end"); require(leafEndIndex <= leaves.length, "Leaf end not less than leaf length"); @@ -101,11 +101,7 @@ library ProofUtils { return proof; } - function generateInclusionProof(bytes32[] memory leaves, uint256 index) - internal - pure - returns (bytes32[] memory) - { + function generateInclusionProof(bytes32[] memory leaves, uint256 index) internal pure returns (bytes32[] memory) { require(leaves.length >= 1, "No leaves"); require(index < leaves.length, "Index too high"); bytes32[][] memory fullT = fullTree(leaves); @@ -120,9 +116,7 @@ library ProofUtils { uint256 counterpartIndex = levelIndex ^ 1; bytes32[] memory layer = fullT[level]; - bytes32 counterpart = counterpartIndex > layer.length - 1 - ? bytes32(0) - : layer[counterpartIndex]; + bytes32 counterpart = counterpartIndex > layer.length - 1 ? bytes32(0) : layer[counterpartIndex]; proof[level] = counterpart; } @@ -144,9 +138,7 @@ library ProofUtils { bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2); for (uint256 i = 0; i < nextLayer.length; i++) { if (2 * i + 1 < prevLayer.length) { - nextLayer[i] = keccak256( - abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1]) - ); + nextLayer[i] = keccak256(abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1])); } else { nextLayer[i] = keccak256(abi.encodePacked(prevLayer[2 * i], bytes32(0))); } diff --git a/contracts/test/contract/common/challengeLib.ts b/contracts/test/contract/common/challengeLib.ts index b3b66b165..6a3602d22 100644 --- a/contracts/test/contract/common/challengeLib.ts +++ b/contracts/test/contract/common/challengeLib.ts @@ -7,7 +7,10 @@ export enum MachineStatus { ERRORED = 2, } -export function machineHash(machineStatus: BigNumber, globalStateHash: string) { +export function machineHash( + machineStatus: BigNumber, + globalStateHash: string +) { const machineStatusNum = machineStatus.toNumber() if (machineStatusNum === MachineStatus.FINISHED) { return solidityKeccak256( diff --git a/contracts/test/stakingPool/AssertionStakingPool.t.sol b/contracts/test/stakingPool/AssertionStakingPool.t.sol index e41ca2f00..7605ef004 100644 --- a/contracts/test/stakingPool/AssertionStakingPool.t.sol +++ b/contracts/test/stakingPool/AssertionStakingPool.t.sol @@ -49,12 +49,11 @@ contract AssertinPoolTest is Test { GlobalState emptyGlobalState; ExecutionState emptyExecutionState = ExecutionState(emptyGlobalState, MachineStatus.FINISHED); - bytes32 genesisHash = - RollupLib.assertionHash({ - parentAssertionHash: bytes32(0), - afterState: emptyExecutionState, - inboxAcc: bytes32(0) - }); + bytes32 genesisHash = RollupLib.assertionHash({ + parentAssertionHash: bytes32(0), + afterState: emptyExecutionState, + inboxAcc: bytes32(0) + }); ExecutionState firstState; AssertionStakingPool pool; @@ -79,11 +78,7 @@ contract AssertinPoolTest is Test { uint64 inboxcount; event RollupCreated( - address indexed rollupAddress, - address inboxAddress, - address adminProxy, - address sequencerInbox, - address bridge + address indexed rollupAddress, address inboxAddress, address adminProxy, address sequencerInbox, address bridge ); function setUp() public { @@ -111,10 +106,8 @@ contract AssertinPoolTest is Test { rollupUserLogicImpl, address(0) ); - ExecutionState memory emptyState = ExecutionState( - GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), - MachineStatus.FINISHED - ); + ExecutionState memory emptyState = + ExecutionState(GlobalState([bytes32(0), bytes32(0)], [uint64(0), uint64(0)]), MachineStatus.FINISHED); token = new TestWETH9("Test", "TEST"); IWETH9(address(token)).deposit{value: 21 ether}(); @@ -136,9 +129,9 @@ contract AssertinPoolTest is Test { genesisExecutionState: emptyState, genesisInboxCount: 0, miniStakeValue: MINI_STAKE_VALUE, - layerZeroBlockEdgeHeight: 2**5, - layerZeroBigStepEdgeHeight: 2**5, - layerZeroSmallStepEdgeHeight: 2**5, + layerZeroBlockEdgeHeight: 2 ** 5, + layerZeroBigStepEdgeHeight: 2 ** 5, + layerZeroSmallStepEdgeHeight: 2 ** 5, numBigStepLevel: 2, anyTrustFastConfirmer: address(300001), challengeGracePeriodBlocks: CHALLENGE_GRACE_PERIOD_BLOCKS @@ -146,13 +139,7 @@ contract AssertinPoolTest is Test { vm.expectEmit(false, false, false, false); emit RollupCreated(address(0), address(0), address(0), address(0), address(0)); - rollupAddr = rollupCreator.createRollup( - config, - address(0), - new address[](0), - false, - MAX_DATA_SIZE - ); + rollupAddr = rollupCreator.createRollup(config, address(0), new address[](0), false, MAX_DATA_SIZE); userRollup = RollupUserLogic(address(rollupAddr)); adminRollup = RollupAdminLogic(address(rollupAddr)); @@ -201,9 +188,8 @@ contract AssertinPoolTest is Test { afterState: afterState }); aspcreator = new AssertionStakingPoolCreator(); - pool = AssertionStakingPool( - aspcreator.createPoolForAssertion(address(rollupAddr), assertionInputs, assertionHash) - ); + pool = + AssertionStakingPool(aspcreator.createPoolForAssertion(address(rollupAddr), assertionInputs, assertionHash)); token.transfer(staker1, staker1Bal); token.transfer(staker2, staker2Bal); @@ -274,11 +260,7 @@ contract AssertinPoolTest is Test { vm.prank(staker2); pool.depositIntoPool(staker2Bal); - assertEq( - token.balanceOf(address(pool)), - staker1Bal + staker2Bal, - "tokens depositted into pool" - ); + assertEq(token.balanceOf(address(pool)), staker1Bal + staker2Bal, "tokens depositted into pool"); assertEq(token.balanceOf(address(staker1)), uint256(0), "tokens depositted into pool"); assertEq(token.balanceOf(address(staker2)), uint256(0), "tokens depositted into pool"); diff --git a/contracts/test/util/TestUtil.sol b/contracts/test/util/TestUtil.sol deleted file mode 100644 index 27b326586..000000000 --- a/contracts/test/util/TestUtil.sol +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 -pragma solidity ^0.8.4; - -import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; -import "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; - -library TestUtil { - function deployProxy(address logic) public returns (address) { - ProxyAdmin pa = new ProxyAdmin(); - return address(new TransparentUpgradeableProxy(address(logic), address(pa), "")); - } -} From f029d5f37556d74f487957cf274f7fd8e4b595f8 Mon Sep 17 00:00:00 2001 From: Mahsa Moosavi Date: Fri, 22 Dec 2023 13:53:46 -0500 Subject: [PATCH 3/4] smol edit --- contracts/test/ValidatorWalletTest.t.sol | 1 - 1 file changed, 1 deletion(-) diff --git a/contracts/test/ValidatorWalletTest.t.sol b/contracts/test/ValidatorWalletTest.t.sol index f0d4e37a3..44fc9872b 100644 --- a/contracts/test/ValidatorWalletTest.t.sol +++ b/contracts/test/ValidatorWalletTest.t.sol @@ -7,7 +7,6 @@ pragma solidity ^0.8.17; import "forge-std/Test.sol"; import "../src/rollup/ValidatorWallet.sol"; import "../src/rollup/ValidatorWalletCreator.sol"; -import "./util/TestUtil.sol"; import "./RollupMock.sol"; contract ValidatorWalletTest is Test { From f4522ead6ef45cb2ae68fbc7a9f027d9da0d90f2 Mon Sep 17 00:00:00 2001 From: Mahsa Moosavi Date: Fri, 22 Dec 2023 13:56:14 -0500 Subject: [PATCH 4/4] forge fmt --- contracts/test/ValidatorWalletTest.t.sol | 30 +++++++----------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/contracts/test/ValidatorWalletTest.t.sol b/contracts/test/ValidatorWalletTest.t.sol index 44fc9872b..77366b494 100644 --- a/contracts/test/ValidatorWalletTest.t.sol +++ b/contracts/test/ValidatorWalletTest.t.sol @@ -73,9 +73,7 @@ contract ValidatorWalletTest is Test { // Check if a non-set destination is not allowed require( - !wallet.allowedExecutorDestinations( - address(0x1114567812345678123456781234567812341111) - ), + !wallet.allowedExecutorDestinations(address(0x1114567812345678123456781234567812341111)), "Address 0x1114567812345678123456781234567812341111 should not be allowed" ); } @@ -95,14 +93,7 @@ contract ValidatorWalletTest is Test { vm.prank(owner); wallet.setExecutor(newExecutors, isExecutor); // Expect the transaction to revert with a specific error message when called by the executor - vm.expectRevert( - abi.encodeWithSelector( - OnlyOwnerDestination.selector, - owner, - executor, - address(rollupMock1) - ) - ); + vm.expectRevert(abi.encodeWithSelector(OnlyOwnerDestination.selector, owner, executor, address(rollupMock1))); vm.prank(executor); wallet.executeTransaction(data, address(rollupMock1), 0); @@ -157,21 +148,16 @@ contract ValidatorWalletTest is Test { wallet.setAllowedExecutorDestinations(destination_addrs, isSet); // Expect the transaction to revert with a specific error message when called by the executor - vm.expectRevert( - abi.encodeWithSelector( - OnlyOwnerDestination.selector, - owner, - executor, - address(rollupMock2) - ) - ); + vm.expectRevert(abi.encodeWithSelector(OnlyOwnerDestination.selector, owner, executor, address(rollupMock2))); vm.prank(executor); wallet.executeTransactions(data, destination_addrs, amount); } - /**** - **** Event declarations - ***/ + /** + * + * Event declarations + * + */ event WithdrawTriggered(); event ExecutorUpdated(address indexed executor, bool isExecutor);