From 4e0ad8a28abeba222d472cc293dd6b6748820029 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=A1s=20Pernas=20Maradei?= Date: Tue, 16 Jan 2024 15:32:13 +0100 Subject: [PATCH] apply prettier config --- .prettierrc.yml | 2 +- contracts/Dispatcher.sol | 81 ++++++------ contracts/DummyConsensusStateManager.sol | 13 +- contracts/Earth.sol | 47 +++---- contracts/GeneralMiddleware.sol | 72 +++++++---- contracts/Groth16Verifier.sol | 152 +++++++++++++++-------- contracts/Ibc.sol | 2 +- contracts/IbcDispatcher.sol | 12 +- contracts/IbcMiddleware.sol | 30 +++-- contracts/IbcReceiver.sol | 26 ++-- contracts/Mars.sol | 42 ++++--- contracts/OpConsensusStateManager.sol | 39 +++--- contracts/UniversalChannelHandler.sol | 86 +++++++------ test/Dispatcher.base.t.sol | 113 ++++++++++------- test/Dispatcher.client.t.sol | 32 ++--- test/Dispatcher.t.sol | 123 +++++++++--------- test/OpConsensusStateManager.t.sol | 10 +- test/VirtualChain.sol | 67 +++++----- test/universal.channel.t.sol | 80 +++++++----- 19 files changed, 593 insertions(+), 436 deletions(-) diff --git a/.prettierrc.yml b/.prettierrc.yml index e8593b94..5d3608a4 100644 --- a/.prettierrc.yml +++ b/.prettierrc.yml @@ -1,4 +1,4 @@ trailingComma: none semi: false singleQuote: true -printWidth: 120 \ No newline at end of file +printWidth: 120 diff --git a/contracts/Dispatcher.sol b/contracts/Dispatcher.sol index 437942dd..86e299a2 100644 --- a/contracts/Dispatcher.sol +++ b/contracts/Dispatcher.sol @@ -2,12 +2,12 @@ pragma solidity ^0.8.9; -import "@openzeppelin/contracts/utils/Strings.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "./IbcDispatcher.sol"; -import {IbcChannelReceiver, IbcPacketReceiver} from "./IbcReceiver.sol"; -import "./IbcVerifier.sol"; -import "./ConsensusStateManager.sol"; +import '@openzeppelin/contracts/utils/Strings.sol'; +import '@openzeppelin/contracts/access/Ownable.sol'; +import './IbcDispatcher.sol'; +import {IbcChannelReceiver, IbcPacketReceiver} from './IbcReceiver.sol'; +import './IbcVerifier.sol'; +import './ConsensusStateManager.sol'; // InitClientMsg is used to create a new Polymer client on an EVM chain // TODO: replace bytes with explictly typed fields for gas cost saving @@ -145,9 +145,7 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // updateClientWithConsensusState updates the client with the // latest consensus state. The zkproof related to this consensus // state is used to verify the consensus state. - function updateClientWithConsensusState(ConsensusState calldata consensusState, ZkProof calldata zkProof) - external - { + function updateClientWithConsensusState(ConsensusState calldata consensusState, ZkProof calldata zkProof) external { if (!isClientCreated) { revert clientNotCreated(); } @@ -163,10 +161,10 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // with the optimistic consensus state. The optimistic consensus // is accepted and will be open for verify in the fraud proof // window. - function updateClientWithOptimisticConsensusState(uint256 height, uint256 appHash) - external - returns (uint256 fraudProofEndTime, bool ended) - { + function updateClientWithOptimisticConsensusState( + uint256 height, + uint256 appHash + ) external returns (uint256 fraudProofEndTime, bool ended) { if (!isClientCreated) { revert clientNotCreated(); } @@ -175,11 +173,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { } // getOptimisticConsensusState - function getOptimisticConsensusState(uint256 height) - external - view - returns (uint256 appHash, uint256 fraudProofEndTime, bool ended) - { + function getOptimisticConsensusState( + uint256 height + ) external view returns (uint256 appHash, uint256 fraudProofEndTime, bool ended) { if (!isClientCreated) { revert clientNotCreated(); } @@ -253,9 +249,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // TODO: fill below proof path consensusStateManager.verifyMembership( proof, - "channel/path/to/be/added/here", - bytes("expected channel bytes constructed from params. Channel.State = {Try_Pending}"), - "Fail to prove channel state" + 'channel/path/to/be/added/here', + bytes('expected channel bytes constructed from params. Channel.State = {Try_Pending}'), + 'Fail to prove channel state' ); } @@ -298,9 +294,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { ) external { consensusStateManager.verifyMembership( proof, - bytes("channel/path/to/be/added/here"), - bytes("expected channel bytes constructed from params. Channel.State = {Ack_Pending, Confirm_Pending}"), - "Fail to prove channel state" + bytes('channel/path/to/be/added/here'), + bytes('expected channel bytes constructed from params. Channel.State = {Ack_Pending, Confirm_Pending}'), + 'Fail to prove channel state' ); portAddress.onConnectIbcChannel(channelId, counterpartyChannelId, counterpartyVersion); @@ -362,9 +358,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // verify VIBC/IBC hub chain has processed ChanCloseConfirm event consensusStateManager.verifyMembership( proof, - bytes("channel/path/to/be/added/here"), - bytes("expected channel bytes constructed from params. Channel.State = {Closed(_Pending?)}"), - "Fail to prove channel state" + bytes('channel/path/to/be/added/here'), + bytes('expected channel bytes constructed from params. Channel.State = {Closed(_Pending?)}'), + 'Fail to prove channel state' ); // ensure port owns channel @@ -442,7 +438,10 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // prove ack packet is on Polymer chain consensusStateManager.verifyMembership( - proof, bytes("ack/packet/path"), bytes("expected ack receipt hash on Polymer chain"), "Fail to prove ack" + proof, + bytes('ack/packet/path'), + bytes('expected ack receipt hash on Polymer chain'), + 'Fail to prove ack' ); // verify packet has been committed and not yet ack'ed or timed out bool hasCommitment = sendPacketCommitment[address(receiver)][packet.src.channelId][packet.sequence]; @@ -485,7 +484,7 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { } // prove absence of packet receipt on Polymer chain - consensusStateManager.verifyNonMembership(proof, "packet/receipt/path", "Fail to prove timeout"); + consensusStateManager.verifyNonMembership(proof, 'packet/receipt/path', 'Fail to prove timeout'); // verify packet has been committed and not yet ack'ed or timed out bool hasCommitment = sendPacketCommitment[address(receiver)][packet.src.channelId][packet.sequence]; @@ -519,9 +518,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { } consensusStateManager.verifyMembership( proof, - "packet/commitment/path", - "expected virtual packet commitment hash on Polymer chain", - "Fail to prove packet commitment" + 'packet/commitment/path', + 'expected virtual packet commitment hash on Polymer chain', + 'Fail to prove packet commitment' ); // verify packet has not been received yet @@ -549,7 +548,11 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { if (isPacketTimeout(packet)) { address writerPortAddress = address(receiver); emit WriteTimeoutPacket( - writerPortAddress, packet.dest.channelId, packet.sequence, packet.timeoutHeight, packet.timeoutTimestamp + writerPortAddress, + packet.dest.channelId, + packet.sequence, + packet.timeoutHeight, + packet.timeoutTimestamp ); return; } @@ -580,11 +583,9 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { // isPacketTimeout returns true if the given packet has timed out acoording to host chain's block height and timestamp function isPacketTimeout(IbcPacket calldata packet) internal view returns (bool) { - return ( - (packet.timeoutTimestamp != 0 && block.timestamp >= packet.timeoutTimestamp) + return ((packet.timeoutTimestamp != 0 && block.timestamp >= packet.timeoutTimestamp) || // TODO: check timeoutHeight.revision_number? - || (packet.timeoutHeight.revision_height != 0 && block.number >= packet.timeoutHeight.revision_height) - ); + (packet.timeoutHeight.revision_height != 0 && block.number >= packet.timeoutHeight.revision_height)); } // TODO: remove below writeTimeoutPacket() function @@ -613,7 +614,11 @@ contract Dispatcher is IbcDispatcher, IbcEventsEmitter, Ownable { } emit WriteTimeoutPacket( - receiver, packet.dest.channelId, packet.sequence, packet.timeoutHeight, packet.timeoutTimestamp + receiver, + packet.dest.channelId, + packet.sequence, + packet.timeoutHeight, + packet.timeoutTimestamp ); } } diff --git a/contracts/DummyConsensusStateManager.sol b/contracts/DummyConsensusStateManager.sol index 001a8e51..e1dbea5a 100644 --- a/contracts/DummyConsensusStateManager.sol +++ b/contracts/DummyConsensusStateManager.sol @@ -1,7 +1,8 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; -import "./ConsensusStateManager.sol"; +import './ConsensusStateManager.sol'; + /** * @title DummyConsensusStateManager * @dev This contract is a dummy implementation of a consensus state manager. @@ -24,10 +25,12 @@ contract DummyConsensusStateManager is ConsensusStateManager { return 0; } - function verifyMembership(Proof calldata proof, bytes memory key, bytes memory expectedValue, string memory message) - external - view - { + function verifyMembership( + Proof calldata proof, + bytes memory key, + bytes memory expectedValue, + string memory message + ) external view { require(proof.proof.length > 0, message); } diff --git a/contracts/Earth.sol b/contracts/Earth.sol index a900bfd6..a34ea4dd 100644 --- a/contracts/Earth.sol +++ b/contracts/Earth.sol @@ -2,10 +2,10 @@ pragma solidity ^0.8.9; -import "./Ibc.sol"; -import "./IbcReceiver.sol"; -import "./IbcDispatcher.sol"; -import "./IbcMiddleware.sol"; +import './Ibc.sol'; +import './IbcReceiver.sol'; +import './IbcDispatcher.sol'; +import './IbcMiddleware.sol'; contract Earth is IbcMwUser, IbcUniversalPacketReceiver { struct UcPacketWithChannel { @@ -30,36 +30,39 @@ contract Earth is IbcMwUser, IbcUniversalPacketReceiver { function greet(address destPortAddr, bytes32 channelId, bytes calldata message, uint64 timeoutTimestamp) external { IbcUniversalPacketSender(mw).sendUniversalPacket( - channelId, Ibc.toBytes32(destPortAddr), message, timeoutTimestamp + channelId, + Ibc.toBytes32(destPortAddr), + message, + timeoutTimestamp ); } // For testing only; real dApps should implment their own ack logic - function generateAckPacket(bytes32 channelId, address srcPortAddr, bytes calldata appData) - external - view - returns (AckPacket memory ackPacket) - { - return AckPacket(true, abi.encodePacked(this, srcPortAddr, "ack-", appData)); + function generateAckPacket( + bytes32 channelId, + address srcPortAddr, + bytes calldata appData + ) external view returns (AckPacket memory ackPacket) { + return AckPacket(true, abi.encodePacked(this, srcPortAddr, 'ack-', appData)); } - function onRecvUniversalPacket(bytes32 channelId, UniversalPacket calldata packet) - external - onlyIbcMw - returns (AckPacket memory ackPacket) - { + function onRecvUniversalPacket( + bytes32 channelId, + UniversalPacket calldata packet + ) external onlyIbcMw returns (AckPacket memory ackPacket) { recvedPackets.push(UcPacketWithChannel(channelId, packet)); return this.generateAckPacket(channelId, Ibc.toAddress(packet.srcPortAddr), packet.appData); } - function onUniversalAcknowledgement(bytes32 channelId, UniversalPacket memory packet, AckPacket calldata ack) - external - onlyIbcMw - { + function onUniversalAcknowledgement( + bytes32 channelId, + UniversalPacket memory packet, + AckPacket calldata ack + ) external onlyIbcMw { // verify packet's destPortAddr is the ack's first encoded address. See generateAckPacket()) - require(ack.data.length >= 20, "ack data too short"); + require(ack.data.length >= 20, 'ack data too short'); address ackSender = address(bytes20(ack.data[0:20])); - require(Ibc.toAddress(packet.destPortAddr) == ackSender, "ack address mismatch"); + require(Ibc.toAddress(packet.destPortAddr) == ackSender, 'ack address mismatch'); ackPackets.push(UcAckWithChannel(channelId, packet, ack)); } diff --git a/contracts/GeneralMiddleware.sol b/contracts/GeneralMiddleware.sol index ead1daa6..bf6e6bd8 100644 --- a/contracts/GeneralMiddleware.sol +++ b/contracts/GeneralMiddleware.sol @@ -2,10 +2,10 @@ pragma solidity ^0.8.9; -import "./Ibc.sol"; -import "./IbcReceiver.sol"; -import "./IbcDispatcher.sol"; -import "./IbcMiddleware.sol"; +import './Ibc.sol'; +import './IbcReceiver.sol'; +import './IbcDispatcher.sol'; +import './IbcMiddleware.sol'; contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { /** @@ -63,14 +63,21 @@ contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { // implementer can emit custom data fields suitable for their use cases. // Here we use MW_ID as the custom MW data field. emit RecvMWPacket( - channelId, ucPacket.srcPortAddr, ucPacket.destPortAddr, MW_ID, ucPacket.appData, abi.encodePacked(MW_ID) + channelId, + ucPacket.srcPortAddr, + ucPacket.destPortAddr, + MW_ID, + ucPacket.appData, + abi.encodePacked(MW_ID) ); if (mwIndex == mwAddrs.length - 1) { // last MW in the stack, deliver packet to dApp - return IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.destPortAddr)).onRecvUniversalPacket( - channelId, ucPacket - ); + return + IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.destPortAddr)).onRecvUniversalPacket( + channelId, + ucPacket + ); } else { // send packet to next MW return IbcMwPacketReceiver(mwAddrs[mwIndex + 1]).onRecvMWPacket(channelId, ucPacket, mwIndex + 1, mwAddrs); @@ -104,7 +111,9 @@ contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { if (mwIndex == mwAddrs.length - 1) { // last MW in the stack, deliver ack to dApp IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.srcPortAddr)).onUniversalAcknowledgement( - channelId, ucPacket, ack + channelId, + ucPacket, + ack ); } else { // send ack to next MW @@ -122,13 +131,19 @@ contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { // implementer can emit custom data fields suitable for their use cases. // Here we use MW_ID as the custom MW data field. emit RecvMWTimeout( - channelId, ucPacket.srcPortAddr, ucPacket.destPortAddr, MW_ID, ucPacket.appData, abi.encodePacked(MW_ID) + channelId, + ucPacket.srcPortAddr, + ucPacket.destPortAddr, + MW_ID, + ucPacket.appData, + abi.encodePacked(MW_ID) ); if (mwIndex == mwAddrs.length - 1) { // last MW in the stack, deliver timeout to dApp IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.srcPortAddr)).onTimeoutUniversalPacket( - channelId, ucPacket + channelId, + ucPacket ); } else { // send timeout to next MW @@ -136,18 +151,16 @@ contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { } } - function onRecvUniversalPacket(bytes32 channelId, UniversalPacket calldata ucPacket) - external - override - onlyIbcMw - returns (AckPacket memory ackPacket) - {} + function onRecvUniversalPacket( + bytes32 channelId, + UniversalPacket calldata ucPacket + ) external override onlyIbcMw returns (AckPacket memory ackPacket) {} - function onUniversalAcknowledgement(bytes32 channelId, UniversalPacket memory packet, AckPacket calldata ack) - external - override - onlyIbcMw - {} + function onUniversalAcknowledgement( + bytes32 channelId, + UniversalPacket memory packet, + AckPacket calldata ack + ) external override onlyIbcMw {} function onTimeoutUniversalPacket(bytes32 channelId, UniversalPacket calldata packet) external override onlyIbcMw {} @@ -165,12 +178,23 @@ contract GeneralMiddleware is IbcMwUser, IbcMiddleware, IbcMwEventsEmitter { // implementer can emit custom data fields suitable for their use cases. // Here we use MW_ID as the custom MW data field. emit SendMWPacket( - channelId, srcPortAddr, destPortAddr, MW_ID, appData, timeoutTimestamp, abi.encodePacked(MW_ID) + channelId, + srcPortAddr, + destPortAddr, + MW_ID, + appData, + timeoutTimestamp, + abi.encodePacked(MW_ID) ); // send packet to next MW IbcMwPacketSender(mw).sendMWPacket( - channelId, srcPortAddr, destPortAddr, srcMwIds | MW_ID, appData, timeoutTimestamp + channelId, + srcPortAddr, + destPortAddr, + srcMwIds | MW_ID, + appData, + timeoutTimestamp ); } } diff --git a/contracts/Groth16Verifier.sol b/contracts/Groth16Verifier.sol index 9b3a32b0..bfb25438 100644 --- a/contracts/Groth16Verifier.sol +++ b/contracts/Groth16Verifier.sol @@ -1,6 +1,5 @@ - // SPDX-License-Identifier: AML -// +// // Copyright 2017 Christian Reitwiessner // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to @@ -23,7 +22,6 @@ pragma solidity ^0.8.0; library Pairing { - uint256 constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; struct G1Point { @@ -38,10 +36,9 @@ library Pairing { } /* - * @return The negation of p, i.e. p.plus(p.negate()) should be zero. + * @return The negation of p, i.e. p.plus(p.negate()) should be zero. */ function negate(G1Point memory p) internal pure returns (G1Point memory) { - // The prime q in the base field F_q for G1 if (p.X == 0 && p.Y == 0) { return G1Point(0, 0); @@ -53,11 +50,7 @@ library Pairing { /* * @return The sum of two points of G1 */ - function plus( - G1Point memory p1, - G1Point memory p2 - ) internal view returns (G1Point memory r) { - + function plus(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint256[4] memory input; input[0] = p1.X; input[1] = p1.Y; @@ -68,11 +61,14 @@ library Pairing { // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60) - // Use "invalid" to make gas estimation work - switch success case 0 { invalid() } + // Use "invalid" to make gas estimation work + switch success + case 0 { + invalid() + } } - require(success,"pairing-add-failed"); + require(success, 'pairing-add-failed'); } /* @@ -81,7 +77,6 @@ library Pairing { * points p. */ function scalar_mul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { - uint256[3] memory input; input[0] = p.X; input[1] = p.Y; @@ -90,10 +85,13 @@ library Pairing { // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60) - // Use "invalid" to make gas estimation work - switch success case 0 { invalid() } + // Use "invalid" to make gas estimation work + switch success + case 0 { + invalid() + } } - require (success,"pairing-mul-failed"); + require(success, 'pairing-mul-failed'); } /* @return The result of computing the pairing check @@ -111,7 +109,6 @@ library Pairing { G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { - G1Point[4] memory p1 = [a1, b1, c1, d1]; G2Point[4] memory p2 = [a2, b2, c2, d2]; uint256 inputSize = 24; @@ -133,18 +130,20 @@ library Pairing { // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) - // Use "invalid" to make gas estimation work - switch success case 0 { invalid() } + // Use "invalid" to make gas estimation work + switch success + case 0 { + invalid() + } } - require(success,"pairing-opcode-failed"); + require(success, 'pairing-opcode-failed'); return out[0] != 0; } } library Groth16Verifier { - using Pairing for *; uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; @@ -165,18 +164,72 @@ library Groth16Verifier { } function verifyingKey() internal pure returns (VerifyingKey memory vk) { - vk.alfa1 = Pairing.G1Point(uint256(9041581582060717595492610069145468205116174493526442818794958076202160238426), uint256(17430267454404372329967775110759870069262922016407141640769546476837087513608)); - vk.beta2 = Pairing.G2Point([uint256(17160639003816211700100815211055426011616919670804350443916604678495784286914), uint256(10172656219193566051258707305997132372545403954428461647141109154301404603308)], [uint256(10474964450160206107164539643452524685631532984424461857738227830926405889996), uint256(13769070105124617312880570141301681697648518948546773986049492471544849876118)]); - vk.gamma2 = Pairing.G2Point([uint256(15366432914386395598802993015272425907640795569697478589068715083160994364142), uint256(17939051302951047099723700007196294243145030630521621515134860110656485933769)], [uint256(17290971625882297327504948650906942728284767850765414819411288684211503934379), uint256(5457932457199341215907858839083449566915295576969609589090637087542639807838)]); - vk.delta2 = Pairing.G2Point([uint256(17726047766288055942017090152908882025199059914973711733416779836637877219414), uint256(14306630215667359884170035685393755807551441029923560351918124455359597757150)], [uint256(15584532392675955284448538053657198098192143301967651926548439628373083647138), uint256(6321397308224630485033690148041200770722810546328902566491166771275000619935)]); - vk.IC[0] = Pairing.G1Point(uint256(20711978127705108280222223541175040161939524837596035934448771647659449707504), uint256(17761827335138367637798232568264217682297013376048369845367669671078024451359)); - vk.IC[1] = Pairing.G1Point(uint256(15632324860893017542868775364673206500633252405511417266745159501563060177522), uint256(13163916530309351000367449265651706404182574863325941937173177907824927042852)); - vk.IC[2] = Pairing.G1Point(uint256(13907948337148122986032599140006417458562893894726326238450991354726574022974), uint256(3882738447073022479669934152258218153445597917598393117862280721012589683481)); - vk.IC[3] = Pairing.G1Point(uint256(11580283230941746573963003333070228477975994586729173478188709812027538295928), uint256(18054229126115750841013996020960807730423222872399771412367569101031414675856)); - vk.IC[4] = Pairing.G1Point(uint256(5875655426275592533678882584868003074482922144498656979279036031874717159910), uint256(19363439765866781148598220465230175052087969786104478017256189841026663833769)); - vk.IC[5] = Pairing.G1Point(uint256(9587835809155593123290821502548076669284595476422052890769498333569460599531), uint256(20906516916426725543781336344480131768858034407043204057313439207873363572967)); - vk.IC[6] = Pairing.G1Point(uint256(18082817428585530221336966468439321203247255330422358393951451812263583493893), uint256(3237089416983138077914541208439580619140598218839303752471224047216159042969)); - vk.IC[7] = Pairing.G1Point(uint256(2819061179750721002530772858766432929024461442142161649967391226887818137237), uint256(10427682181626131138586709406858696690306839913358258579426995745728813235384)); + vk.alfa1 = Pairing.G1Point( + uint256(9041581582060717595492610069145468205116174493526442818794958076202160238426), + uint256(17430267454404372329967775110759870069262922016407141640769546476837087513608) + ); + vk.beta2 = Pairing.G2Point( + [ + uint256(17160639003816211700100815211055426011616919670804350443916604678495784286914), + uint256(10172656219193566051258707305997132372545403954428461647141109154301404603308) + ], + [ + uint256(10474964450160206107164539643452524685631532984424461857738227830926405889996), + uint256(13769070105124617312880570141301681697648518948546773986049492471544849876118) + ] + ); + vk.gamma2 = Pairing.G2Point( + [ + uint256(15366432914386395598802993015272425907640795569697478589068715083160994364142), + uint256(17939051302951047099723700007196294243145030630521621515134860110656485933769) + ], + [ + uint256(17290971625882297327504948650906942728284767850765414819411288684211503934379), + uint256(5457932457199341215907858839083449566915295576969609589090637087542639807838) + ] + ); + vk.delta2 = Pairing.G2Point( + [ + uint256(17726047766288055942017090152908882025199059914973711733416779836637877219414), + uint256(14306630215667359884170035685393755807551441029923560351918124455359597757150) + ], + [ + uint256(15584532392675955284448538053657198098192143301967651926548439628373083647138), + uint256(6321397308224630485033690148041200770722810546328902566491166771275000619935) + ] + ); + vk.IC[0] = Pairing.G1Point( + uint256(20711978127705108280222223541175040161939524837596035934448771647659449707504), + uint256(17761827335138367637798232568264217682297013376048369845367669671078024451359) + ); + vk.IC[1] = Pairing.G1Point( + uint256(15632324860893017542868775364673206500633252405511417266745159501563060177522), + uint256(13163916530309351000367449265651706404182574863325941937173177907824927042852) + ); + vk.IC[2] = Pairing.G1Point( + uint256(13907948337148122986032599140006417458562893894726326238450991354726574022974), + uint256(3882738447073022479669934152258218153445597917598393117862280721012589683481) + ); + vk.IC[3] = Pairing.G1Point( + uint256(11580283230941746573963003333070228477975994586729173478188709812027538295928), + uint256(18054229126115750841013996020960807730423222872399771412367569101031414675856) + ); + vk.IC[4] = Pairing.G1Point( + uint256(5875655426275592533678882584868003074482922144498656979279036031874717159910), + uint256(19363439765866781148598220465230175052087969786104478017256189841026663833769) + ); + vk.IC[5] = Pairing.G1Point( + uint256(9587835809155593123290821502548076669284595476422052890769498333569460599531), + uint256(20906516916426725543781336344480131768858034407043204057313439207873363572967) + ); + vk.IC[6] = Pairing.G1Point( + uint256(18082817428585530221336966468439321203247255330422358393951451812263583493893), + uint256(3237089416983138077914541208439580619140598218839303752471224047216159042969) + ); + vk.IC[7] = Pairing.G1Point( + uint256(2819061179750721002530772858766432929024461442142161649967391226887818137237), + uint256(10427682181626131138586709406858696690306839913358258579426995745728813235384) + ); } /* @@ -189,7 +242,6 @@ library Groth16Verifier { uint256[2] memory c, uint256[7] memory input ) internal view returns (bool r) { - Proof memory proof; proof.A = Pairing.G1Point(a[0], a[1]); proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]); @@ -201,35 +253,27 @@ library Groth16Verifier { Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); // Make sure that proof.A, B, and C are each less than the prime q - require(proof.A.X < PRIME_Q, "verifier-aX-gte-prime-q"); - require(proof.A.Y < PRIME_Q, "verifier-aY-gte-prime-q"); + require(proof.A.X < PRIME_Q, 'verifier-aX-gte-prime-q'); + require(proof.A.Y < PRIME_Q, 'verifier-aY-gte-prime-q'); - require(proof.B.X[0] < PRIME_Q, "verifier-bX0-gte-prime-q"); - require(proof.B.Y[0] < PRIME_Q, "verifier-bY0-gte-prime-q"); + require(proof.B.X[0] < PRIME_Q, 'verifier-bX0-gte-prime-q'); + require(proof.B.Y[0] < PRIME_Q, 'verifier-bY0-gte-prime-q'); - require(proof.B.X[1] < PRIME_Q, "verifier-bX1-gte-prime-q"); - require(proof.B.Y[1] < PRIME_Q, "verifier-bY1-gte-prime-q"); + require(proof.B.X[1] < PRIME_Q, 'verifier-bX1-gte-prime-q'); + require(proof.B.Y[1] < PRIME_Q, 'verifier-bY1-gte-prime-q'); - require(proof.C.X < PRIME_Q, "verifier-cX-gte-prime-q"); - require(proof.C.Y < PRIME_Q, "verifier-cY-gte-prime-q"); + require(proof.C.X < PRIME_Q, 'verifier-cX-gte-prime-q'); + require(proof.C.Y < PRIME_Q, 'verifier-cY-gte-prime-q'); // Make sure that every input is less than the snark scalar field for (uint256 i = 0; i < input.length; i++) { - require(input[i] < SNARK_SCALAR_FIELD, "verifier-gte-snark-scalar-field"); + require(input[i] < SNARK_SCALAR_FIELD, 'verifier-gte-snark-scalar-field'); vk_x = Pairing.plus(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i])); } vk_x = Pairing.plus(vk_x, vk.IC[0]); - return Pairing.pairing( - Pairing.negate(proof.A), - proof.B, - vk.alfa1, - vk.beta2, - vk_x, - vk.gamma2, - proof.C, - vk.delta2 - ); + return + Pairing.pairing(Pairing.negate(proof.A), proof.B, vk.alfa1, vk.beta2, vk_x, vk.gamma2, proof.C, vk.delta2); } } diff --git a/contracts/Ibc.sol b/contracts/Ibc.sol index c55ad1c6..788809c0 100644 --- a/contracts/Ibc.sol +++ b/contracts/Ibc.sol @@ -2,7 +2,7 @@ pragma solidity ^0.8.9; -import "@openzeppelin/contracts/utils/Strings.sol"; +import '@openzeppelin/contracts/utils/Strings.sol'; /** * Ibc.sol diff --git a/contracts/IbcDispatcher.sol b/contracts/IbcDispatcher.sol index ad3a8557..9416af47 100644 --- a/contracts/IbcDispatcher.sol +++ b/contracts/IbcDispatcher.sol @@ -2,8 +2,8 @@ pragma solidity ^0.8.9; -import "./Ibc.sol"; -import "./IbcReceiver.sol"; +import './Ibc.sol'; +import './IbcReceiver.sol'; /** * @title IbcPacketSender @@ -18,7 +18,8 @@ interface IbcPacketSender { * @title IbcDispatcher * @author Polymer Labs * @notice IBC dispatcher interface is the Polymer Core Smart Contract that implements the core IBC protocol. - * @dev IBC-compatible contracts depend on this interface to actively participate in the IBC protocol. Other features are implemented as callback methods in the IbcReceiver interface. + * @dev IBC-compatible contracts depend on this interface to actively participate in the IBC protocol. + Other features are implemented as callback methods in the IbcReceiver interface. */ interface IbcDispatcher is IbcPacketSender { function portPrefix() external view returns (string memory); @@ -79,7 +80,10 @@ interface IbcEventsEmitter { event RecvPacket(address indexed destPortAddress, bytes32 indexed destChannelId, uint64 sequence); event WriteAckPacket( - address indexed writerPortAddress, bytes32 indexed writerChannelId, uint64 sequence, AckPacket ackPacket + address indexed writerPortAddress, + bytes32 indexed writerChannelId, + uint64 sequence, + AckPacket ackPacket ); event WriteTimeoutPacket( diff --git a/contracts/IbcMiddleware.sol b/contracts/IbcMiddleware.sol index 4734faeb..b6d4b5a9 100644 --- a/contracts/IbcMiddleware.sol +++ b/contracts/IbcMiddleware.sol @@ -2,9 +2,9 @@ pragma solidity ^0.8.9; -import "./Ibc.sol"; -import "./IbcDispatcher.sol"; -import "./IbcReceiver.sol"; +import './Ibc.sol'; +import './IbcDispatcher.sol'; +import './IbcReceiver.sol'; /** * @title IbcUniversalPacketSender @@ -71,12 +71,16 @@ interface IbcMwPacketReceiver { // dApps and IBC middleware contracts need to implement this interface to receive universal channel packets as packets' final destination. interface IbcUniversalPacketReceiver { - function onRecvUniversalPacket(bytes32 channelId, UniversalPacket calldata ucPacket) - external - returns (AckPacket memory ackPacket); + function onRecvUniversalPacket( + bytes32 channelId, + UniversalPacket calldata ucPacket + ) external returns (AckPacket memory ackPacket); - function onUniversalAcknowledgement(bytes32 channelId, UniversalPacket memory packet, AckPacket calldata ack) - external; + function onUniversalAcknowledgement( + bytes32 channelId, + UniversalPacket memory packet, + AckPacket calldata ack + ) external; function onTimeoutUniversalPacket(bytes32 channelId, UniversalPacket calldata packet) external; } @@ -101,7 +105,9 @@ interface IbcMiddlwareProvider is IbcUniversalPacketSender, IbcMwPacketSender { * - IbcMiddleware must sit on top of a UniversalChannel MW or another IbcMiddleware. * - IbcMiddleware cannnot own an IBC channel. Instead, UniversalChannel MW owns channels. */ -interface IbcMiddleware is IbcMiddlwareProvider, IbcMwPacketReceiver, IbcUniversalPacketReceiver {} +interface IbcMiddleware is IbcMiddlwareProvider, IbcMwPacketReceiver, IbcUniversalPacketReceiver { + +} /** * @title IbcUniversalChannelMW @@ -109,7 +115,9 @@ interface IbcMiddleware is IbcMiddlwareProvider, IbcMwPacketReceiver, IbcUnivers * IbcUniversalChannelMW is a special type of IbcMiddleware that owns IBC channels, which are multiplexed for other IbcMiddleware. * IbcUniversalChannelMW cannot sit on top of other MW, and must talk to IbcDispatcher directly. */ -interface IbcUniversalChannelMW is IbcMiddlwareProvider, IbcPacketReceiver, IbcChannelReceiver {} +interface IbcUniversalChannelMW is IbcMiddlwareProvider, IbcPacketReceiver, IbcChannelReceiver { + +} /** * @title IbcMwEventsEmitter @@ -212,7 +220,7 @@ contract IbcMwUser is Ownable { * Should add this modifier to all IBC-related callback functions. */ modifier onlyIbcMw() { - require(authorizedMws[msg.sender], "unauthorized IBC middleware"); + require(authorizedMws[msg.sender], 'unauthorized IBC middleware'); _; } } diff --git a/contracts/IbcReceiver.sol b/contracts/IbcReceiver.sol index 142ca45b..fe3f1c49 100644 --- a/contracts/IbcReceiver.sol +++ b/contracts/IbcReceiver.sol @@ -2,9 +2,9 @@ pragma solidity ^0.8.9; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "./IbcDispatcher.sol"; -import "./Ibc.sol"; +import '@openzeppelin/contracts/access/Ownable.sol'; +import './IbcDispatcher.sol'; +import './Ibc.sol'; /** * @title IbcChannelReceiver @@ -21,11 +21,17 @@ interface IbcChannelReceiver { string calldata counterpartyVersion ) external returns (string memory selectedVersion); - function onConnectIbcChannel(bytes32 channelId, bytes32 counterpartyChannelId, string calldata counterpartyVersion) - external; + function onConnectIbcChannel( + bytes32 channelId, + bytes32 counterpartyChannelId, + string calldata counterpartyVersion + ) external; - function onCloseIbcChannel(bytes32 channelId, string calldata counterpartyPortId, bytes32 counterpartyChannelId) - external; + function onCloseIbcChannel( + bytes32 channelId, + string calldata counterpartyPortId, + bytes32 counterpartyChannelId + ) external; } /** @@ -47,7 +53,9 @@ interface IbcPacketReceiver { * @notice IBC receiver interface must be implemented by a IBC-enabled contract. * The implementer, aka. dApp devs, should implement channel handshake and packet handling methods. */ -interface IbcReceiver is IbcChannelReceiver, IbcPacketReceiver {} +interface IbcReceiver is IbcChannelReceiver, IbcPacketReceiver { + +} contract IbcReceiverBase is Ownable { IbcDispatcher public dispatcher; @@ -70,7 +78,7 @@ contract IbcReceiverBase is Ownable { * Should add this modifier to all IBC-related callback functions. */ modifier onlyIbcDispatcher() { - require(msg.sender == address(dispatcher), "only IBC dispatcher"); + require(msg.sender == address(dispatcher), 'only IBC dispatcher'); _; } } diff --git a/contracts/Mars.sol b/contracts/Mars.sol index b3c16834..9f2e4626 100644 --- a/contracts/Mars.sol +++ b/contracts/Mars.sol @@ -2,9 +2,9 @@ pragma solidity ^0.8.9; -import "./Ibc.sol"; -import "./IbcReceiver.sol"; -import "./IbcDispatcher.sol"; +import './Ibc.sol'; +import './IbcReceiver.sol'; +import './IbcDispatcher.sol'; contract Mars is IbcReceiverBase, IbcReceiver { // received packet as chain B @@ -15,7 +15,7 @@ contract Mars is IbcReceiverBase, IbcReceiver { IbcPacket[] public timeoutPackets; bytes32[] public connectedChannels; - string[] supportedVersions = ["1.0", "2.0"]; + string[] supportedVersions = ['1.0', '2.0']; constructor(IbcDispatcher _dispatcher) IbcReceiverBase(_dispatcher) {} @@ -51,30 +51,32 @@ contract Mars is IbcReceiverBase, IbcReceiver { * In both cases, the selected version should be in the supported versions list. */ bool foundVersion = false; - selectedVersion = - keccak256(abi.encodePacked(version)) == keccak256(abi.encodePacked("")) ? counterpartyVersion : version; + selectedVersion = keccak256(abi.encodePacked(version)) == keccak256(abi.encodePacked('')) + ? counterpartyVersion + : version; for (uint256 i = 0; i < supportedVersions.length; i++) { if (keccak256(abi.encodePacked(selectedVersion)) == keccak256(abi.encodePacked(supportedVersions[i]))) { foundVersion = true; break; } } - require(foundVersion, "Unsupported version"); + require(foundVersion, 'Unsupported version'); // if counterpartyVersion is not empty, then it must be the same foundVersion - if (keccak256(abi.encodePacked(counterpartyVersion)) != keccak256(abi.encodePacked(""))) { + if (keccak256(abi.encodePacked(counterpartyVersion)) != keccak256(abi.encodePacked(''))) { require( keccak256(abi.encodePacked(counterpartyVersion)) == keccak256(abi.encodePacked(selectedVersion)), - "Version mismatch" + 'Version mismatch' ); } return selectedVersion; } - function onConnectIbcChannel(bytes32 channelId, bytes32 counterpartyChannelId, string calldata counterpartyVersion) - external - onlyIbcDispatcher - { + function onConnectIbcChannel( + bytes32 channelId, + bytes32 counterpartyChannelId, + string calldata counterpartyVersion + ) external onlyIbcDispatcher { // ensure negotiated version is supported bool foundVersion = false; for (uint256 i = 0; i < supportedVersions.length; i++) { @@ -83,14 +85,15 @@ contract Mars is IbcReceiverBase, IbcReceiver { break; } } - require(foundVersion, "Unsupported version"); + require(foundVersion, 'Unsupported version'); connectedChannels.push(channelId); } - function onCloseIbcChannel(bytes32 channelId, string calldata counterpartyPortId, bytes32 counterpartyChannelId) - external - onlyIbcDispatcher - { + function onCloseIbcChannel( + bytes32 channelId, + string calldata counterpartyPortId, + bytes32 counterpartyChannelId + ) external onlyIbcDispatcher { // logic to determin if the channel should be closed bool channelFound = false; for (uint256 i = 0; i < connectedChannels.length; i++) { @@ -100,7 +103,7 @@ contract Mars is IbcReceiverBase, IbcReceiver { break; } } - require(channelFound, "Channel not found"); + require(channelFound, 'Channel not found'); } /** @@ -110,6 +113,7 @@ contract Mars is IbcReceiverBase, IbcReceiver { function triggerChannelClose(bytes32 channelId) external onlyOwner { dispatcher.closeIbcChannel(channelId); } + /** * @dev Sends a packet with a greeting message over a specified channel. * @param message The greeting message to be sent. diff --git a/contracts/OpConsensusStateManager.sol b/contracts/OpConsensusStateManager.sol index 32d04a13..c1c9e039 100644 --- a/contracts/OpConsensusStateManager.sol +++ b/contracts/OpConsensusStateManager.sol @@ -1,9 +1,9 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; -import "./IbcVerifier.sol"; -import "./Ibc.sol"; -import "./ConsensusStateManager.sol"; +import './IbcVerifier.sol'; +import './Ibc.sol'; +import './ConsensusStateManager.sol'; // OptimisticConsensusStateManager manages the appHash at different // heights and track the fraud proof end time for them. @@ -26,11 +26,10 @@ contract OptimisticConsensusStateManager is ConsensusStateManager { // returns the fraud proof end time, and a bool flag indicating if // the fraud proof window has passed according to the block's // timestamp. - function addOpConsensusState(uint256 height, uint256 appHash) - external - override - returns (uint256 fraudProofEndTime, bool ended) - { + function addOpConsensusState( + uint256 height, + uint256 appHash + ) external override returns (uint256 fraudProofEndTime, bool ended) { uint256 hash = consensusStates[height]; if (hash == 0) { // a new appHash @@ -47,7 +46,7 @@ contract OptimisticConsensusStateManager is ConsensusStateManager { } revert( - "cannot update a pending optimistic consensus state with a different appHash, please submit fraud proof instead" + 'cannot update a pending optimistic consensus state with a different appHash, please submit fraud proof instead' ); } @@ -60,11 +59,9 @@ contract OptimisticConsensusStateManager is ConsensusStateManager { return getInternalState(height); } - function getInternalState(uint256 height) - public - view - returns (uint256 appHash, uint256 fraudProofEndTime, bool ended) - { + function getInternalState( + uint256 height + ) public view returns (uint256 appHash, uint256 fraudProofEndTime, bool ended) { uint256 hash = consensusStates[height]; return (hash, fraudProofEndtime[hash], hash != 0 && block.timestamp >= fraudProofEndtime[hash]); } @@ -79,17 +76,19 @@ contract OptimisticConsensusStateManager is ConsensusStateManager { * can be used to perform the membership test and if so, it uses * the verifier to perform membership check. */ - function verifyMembership(Proof calldata proof, bytes memory key, bytes memory expectedValue, string memory message) - external - view - { - (uint256 appHash,, bool ended) = getInternalState(proof.proofHeight.revision_height); + function verifyMembership( + Proof calldata proof, + bytes memory key, + bytes memory expectedValue, + string memory message + ) external view { + (uint256 appHash, , bool ended) = getInternalState(proof.proofHeight.revision_height); require(ended, "appHash hasn't passed the fraud proof window"); require(verifier.verifyMembership(appHash, proof, key, expectedValue), message); } function verifyNonMembership(Proof calldata proof, bytes memory key, string memory message) external view { - (uint256 appHash,, bool ended) = getInternalState(proof.proofHeight.revision_height); + (uint256 appHash, , bool ended) = getInternalState(proof.proofHeight.revision_height); require(ended, "appHash hasn't passed the fraud proof window"); require(verifier.verifyNonMembership(appHash, proof, key), message); } diff --git a/contracts/UniversalChannelHandler.sol b/contracts/UniversalChannelHandler.sol index 925da1d8..4ce4125f 100644 --- a/contracts/UniversalChannelHandler.sol +++ b/contracts/UniversalChannelHandler.sol @@ -2,17 +2,17 @@ pragma solidity ^0.8.9; -import "@openzeppelin/contracts/access/Ownable.sol"; -import "./IbcDispatcher.sol"; -import "./IbcMiddleware.sol"; -import {IbcReceiver} from "./IbcReceiver.sol"; -import "./Ibc.sol"; +import '@openzeppelin/contracts/access/Ownable.sol'; +import './IbcDispatcher.sol'; +import './IbcMiddleware.sol'; +import {IbcReceiver} from './IbcReceiver.sol'; +import './Ibc.sol'; contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { constructor(IbcDispatcher _dispatcher) IbcReceiverBase(_dispatcher) {} bytes32[] public connectedChannels; - string constant VERSION = "1.0"; + string constant VERSION = '1.0'; uint256 public constant MW_ID = 1; // Key: middleware bitmap, Value: middleware address from receiver(chain B)'s perspective @@ -40,32 +40,37 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { ) external onlyIbcDispatcher returns (string memory selectedVersion) { if (counterpartyChannelId == bytes32(0)) { // ChanOpenInit - require(keccak256(abi.encodePacked(version)) == keccak256(abi.encodePacked(VERSION)), "Unsupported version"); + require( + keccak256(abi.encodePacked(version)) == keccak256(abi.encodePacked(VERSION)), + 'Unsupported version' + ); } else { // ChanOpenTry require( keccak256(abi.encodePacked(counterpartyVersion)) == keccak256(abi.encodePacked(VERSION)), - "Unsupported version" + 'Unsupported version' ); } return VERSION; } - function onConnectIbcChannel(bytes32 channelId, bytes32 counterpartyChannelId, string calldata counterpartyVersion) - external - onlyIbcDispatcher - { + function onConnectIbcChannel( + bytes32 channelId, + bytes32 counterpartyChannelId, + string calldata counterpartyVersion + ) external onlyIbcDispatcher { require( keccak256(abi.encodePacked(counterpartyVersion)) == keccak256(abi.encodePacked(VERSION)), - "Unsupported version" + 'Unsupported version' ); connectedChannels.push(channelId); } - function onCloseIbcChannel(bytes32 channelId, string calldata counterpartyPortId, bytes32 counterpartyChannelId) - external - onlyIbcDispatcher - { + function onCloseIbcChannel( + bytes32 channelId, + string calldata counterpartyPortId, + bytes32 counterpartyChannelId + ) external onlyIbcDispatcher { // logic to determin if the channel should be closed bool channelFound = false; for (uint256 i = 0; i < connectedChannels.length; i++) { @@ -75,7 +80,7 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { break; } } - require(channelFound, "Channel not found"); + require(channelFound, 'Channel not found'); } function sendUniversalPacket( @@ -84,8 +89,9 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { bytes calldata appData, uint64 timeoutTimestamp ) external { - bytes memory packetData = - Ibc.toUniversalPacketBytes(UniversalPacket(Ibc.toBytes32(msg.sender), MW_ID, destPortAddr, appData)); + bytes memory packetData = Ibc.toUniversalPacketBytes( + UniversalPacket(Ibc.toBytes32(msg.sender), MW_ID, destPortAddr, appData) + ); dispatcher.sendPacket(channelId, packetData, timeoutTimestamp); } @@ -100,41 +106,42 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { bytes calldata appData, uint64 timeoutTimestamp ) external { - bytes memory packetData = - Ibc.toUniversalPacketBytes(UniversalPacket(srcPortAddr, srcMwIds | MW_ID, destPortAddr, appData)); + bytes memory packetData = Ibc.toUniversalPacketBytes( + UniversalPacket(srcPortAddr, srcMwIds | MW_ID, destPortAddr, appData) + ); dispatcher.sendPacket(channelId, packetData, timeoutTimestamp); } - function onRecvPacket(IbcPacket calldata packet) - external - override - onlyIbcDispatcher - returns (AckPacket memory ackPacket) - { + function onRecvPacket( + IbcPacket calldata packet + ) external override onlyIbcDispatcher returns (AckPacket memory ackPacket) { UniversalPacket memory ucPacket = Ibc.fromUniversalPacketBytes(packet.data); address[] storage mwAddrs = mwStackAddrs[ucPacket.mwBitmap]; if (mwAddrs.length == 0) { // no other middleware stack registered for this packet. Deliver packet to dApp directly. - return IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.destPortAddr)).onRecvUniversalPacket( - packet.dest.channelId, ucPacket - ); + return + IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.destPortAddr)).onRecvUniversalPacket( + packet.dest.channelId, + ucPacket + ); } else { // send packet to first MW in the stack return IbcMwPacketReceiver(mwAddrs[0]).onRecvMWPacket(packet.dest.channelId, ucPacket, 0, mwAddrs); } } - function onAcknowledgementPacket(IbcPacket calldata packet, AckPacket calldata ack) - external - override - onlyIbcDispatcher - { + function onAcknowledgementPacket( + IbcPacket calldata packet, + AckPacket calldata ack + ) external override onlyIbcDispatcher { UniversalPacket memory ucPacket = Ibc.fromUniversalPacketBytes(packet.data); address[] storage mwAddrs = mwStackAddrs[ucPacket.mwBitmap]; if (mwAddrs.length == 0) { // no other middleware stack registered for this packet. Deliver ack to dApp directly. IbcUniversalPacketReceiver(Ibc.toAddress(ucPacket.srcPortAddr)).onUniversalAcknowledgement( - packet.src.channelId, ucPacket, ack + packet.src.channelId, + ucPacket, + ack ); } else { // send ack to last MW in the stack @@ -148,7 +155,8 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { if (mwAddrs.length == 0) { // no other middleware stack registered for this packet. Deliver timeout to dApp directly. IbcUniversalPacketReceiver(Ibc.toAddress(ucPacketData.srcPortAddr)).onTimeoutUniversalPacket( - packet.src.channelId, ucPacketData + packet.src.channelId, + ucPacketData ); } else { // send timeout to last MW in the stack @@ -165,7 +173,7 @@ contract UniversalChannelHandler is IbcReceiverBase, IbcUniversalChannelMW { * MW closer to UniversalChannel MW has smaller index. MW stack must be in the same order on both chains. */ function registerMwStack(uint256 mwBitmap, address[] calldata mwAddrs) external onlyOwner { - require(mwBitmap != 0, "mwBitmap cannot be 0"); + require(mwBitmap != 0, 'mwBitmap cannot be 0'); mwStackAddrs[mwBitmap] = mwAddrs; } } diff --git a/test/Dispatcher.base.t.sol b/test/Dispatcher.base.t.sol index ecc62823..1e155c5e 100644 --- a/test/Dispatcher.base.t.sol +++ b/test/Dispatcher.base.t.sol @@ -1,16 +1,16 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; -import "forge-std/Test.sol"; -import "../contracts/Ibc.sol"; -import {Dispatcher, InitClientMsg, UpgradeClientMsg} from "../contracts/Dispatcher.sol"; -import {IbcEventsEmitter} from "../contracts/IbcDispatcher.sol"; -import {IbcChannelReceiver} from "../contracts/IbcReceiver.sol"; -import "../contracts/IbcVerifier.sol"; -import "../contracts/Verifier.sol"; -import "../contracts/Mars.sol"; -import "../contracts/OpConsensusStateManager.sol"; -import "../contracts/DummyConsensusStateManager.sol"; +import 'forge-std/Test.sol'; +import '../contracts/Ibc.sol'; +import {Dispatcher, InitClientMsg, UpgradeClientMsg} from '../contracts/Dispatcher.sol'; +import {IbcEventsEmitter} from '../contracts/IbcDispatcher.sol'; +import {IbcChannelReceiver} from '../contracts/IbcReceiver.sol'; +import '../contracts/IbcVerifier.sol'; +import '../contracts/Verifier.sol'; +import '../contracts/Mars.sol'; +import '../contracts/OpConsensusStateManager.sol'; +import '../contracts/DummyConsensusStateManager.sol'; struct LocalEnd { IbcChannelReceiver receiver; @@ -39,35 +39,44 @@ struct ChannelHandshakeSetting { contract Base is Test, IbcEventsEmitter { uint64 UINT64_MAX = 18446744073709551615; - ConsensusState untrustedState = ConsensusState( - 80990, 590199110038530808131927832294665177527506259518072095333098842116767351199, 7000040, 1000 - ); - ConsensusState trustedState = ConsensusState( - 10934, 7064503680087416120706887577693908749828198688716609274705703517077803898371, 7002040, 1020 - ); - InitClientMsg initClientMsg = InitClientMsg(bytes("Polymer"), untrustedState); + ConsensusState untrustedState = + ConsensusState( + 80990, + 590199110038530808131927832294665177527506259518072095333098842116767351199, + 7000040, + 1000 + ); + ConsensusState trustedState = + ConsensusState( + 10934, + 7064503680087416120706887577693908749828198688716609274705703517077803898371, + 7002040, + 1020 + ); + InitClientMsg initClientMsg = InitClientMsg(bytes('Polymer'), untrustedState); ZKMintVerifier verifier = new Verifier(); - ZkProof proof = ZkProof( - [ - 13449388914393258752883032560537386278857542833249142697090243871249761501123, - 5963894333042515966217276339656894890750758020607775733717462915787234629927 - ], - [ + ZkProof proof = + ZkProof( + [ + 13449388914393258752883032560537386278857542833249142697090243871249761501123, + 5963894333042515966217276339656894890750758020607775733717462915787234629927 + ], [ - 4811559872397934450173412387101758297072581261546553338353504577141293696514, - 18400634037991283592418145553628778322894277765243742619561207628896194710939 + [ + 4811559872397934450173412387101758297072581261546553338353504577141293696514, + 18400634037991283592418145553628778322894277765243742619561207628896194710939 + ], + [ + 17903685207039300384995795331083569887497623740119108595975170464164316221644, + 9246628133289276308945311797896077179503891414159382179119544904154776510385 + ] ], [ - 17903685207039300384995795331083569887497623740119108595975170464164316221644, - 9246628133289276308945311797896077179503891414159382179119544904154776510385 + 17432552394458345841788798376121543520587716339044416231610790827968220675517, + 15082220514596158133191868403239442750535261032426474092101151620016661078026 ] - ], - [ - 17432552394458345841788798376121543520587716339044416231610790827968220675517, - 15082220514596158133191868403239442750535261032426474092101151620016661078026 - ] - ); + ); Height ZERO_HEIGHT = Height(0, 0); uint64 maxTimeout = UINT64_MAX; @@ -76,12 +85,12 @@ contract Base is Test, IbcEventsEmitter { // Proofs from Polymer chain, to verify packet or channel state on Polymer Proof emptyProof; - Proof invalidProof = Proof(Height(0, 42), bytes("")); // invalid proof with empty proof bytes - Proof validProof = Proof(Height(0, 42), bytes("valid proof")); + Proof invalidProof = Proof(Height(0, 42), bytes('')); // invalid proof with empty proof bytes + Proof validProof = Proof(Height(0, 42), bytes('valid proof')); Dispatcher dispatcher; - string portPrefix = "polyibc.eth."; - string[] connectionHops = ["connection-1", "connection-2"]; + string portPrefix = 'polyibc.eth.'; + string[] connectionHops = ['connection-1', 'connection-2']; // ⬇️ Utility functions for testing @@ -110,9 +119,12 @@ contract Base is Test, IbcEventsEmitter { * @param expPass Expected pass status of the operation. * If expPass is false, `vm.expectRevert` should be called before this function. */ - function openChannel(LocalEnd memory le, RemoteEnd memory re, ChannelHandshakeSetting memory s, bool expPass) - public - { + function openChannel( + LocalEnd memory le, + RemoteEnd memory re, + ChannelHandshakeSetting memory s, + bool expPass + ) public { CounterParty memory cp; cp.portId = re.portId; if (!s.localInitiate) { @@ -131,7 +143,15 @@ contract Base is Test, IbcEventsEmitter { cp.channelId ); } - dispatcher.openIbcChannel(le.receiver, le.versionCall, s.ordering, s.feeEnabled, le.connectionHops, cp, s.proof); + dispatcher.openIbcChannel( + le.receiver, + le.versionCall, + s.ordering, + s.feeEnabled, + le.connectionHops, + cp, + s.proof + ); } /** @@ -142,9 +162,12 @@ contract Base is Test, IbcEventsEmitter { * @param expPass Expected pass status of the operation. * If expPass is false, `vm.expectRevert` should be called before this function. */ - function connectChannel(LocalEnd memory le, RemoteEnd memory re, ChannelHandshakeSetting memory s, bool expPass) - public - { + function connectChannel( + LocalEnd memory le, + RemoteEnd memory re, + ChannelHandshakeSetting memory s, + bool expPass + ) public { if (expPass) { vm.expectEmit(true, true, true, true); emit ConnectIbcChannel(address(le.receiver), le.channelId); @@ -165,6 +188,6 @@ contract Base is Test, IbcEventsEmitter { // A helper function to expect revert with message when contract is called with non-owner. // Error msg is defined by OpenZeppelin Ownable contract. function expectRevertNonOwner() internal { - vm.expectRevert("Ownable: caller is not the owner"); + vm.expectRevert('Ownable: caller is not the owner'); } } diff --git a/test/Dispatcher.client.t.sol b/test/Dispatcher.client.t.sol index bf7241bf..9f3d00e4 100644 --- a/test/Dispatcher.client.t.sol +++ b/test/Dispatcher.client.t.sol @@ -1,15 +1,15 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; -import "../contracts/Ibc.sol"; -import {Dispatcher, InitClientMsg, UpgradeClientMsg} from "../contracts/Dispatcher.sol"; -import {IbcEventsEmitter} from "../contracts/IbcDispatcher.sol"; -import {IbcReceiver} from "../contracts/IbcReceiver.sol"; -import "../contracts/IbcVerifier.sol"; -import "../contracts/Verifier.sol"; -import "../contracts/Mars.sol"; -import "../contracts/OpConsensusStateManager.sol"; -import "./Dispatcher.base.t.sol"; +import '../contracts/Ibc.sol'; +import {Dispatcher, InitClientMsg, UpgradeClientMsg} from '../contracts/Dispatcher.sol'; +import {IbcEventsEmitter} from '../contracts/IbcDispatcher.sol'; +import {IbcReceiver} from '../contracts/IbcReceiver.sol'; +import '../contracts/IbcVerifier.sol'; +import '../contracts/Verifier.sol'; +import '../contracts/Mars.sol'; +import '../contracts/OpConsensusStateManager.sol'; +import './Dispatcher.base.t.sol'; contract ClientTestBase is Base { function setUp() public virtual { @@ -23,14 +23,14 @@ contract DispatcherCreateClientTest is ClientTestBase { } function test_mustByOwner() public { - vm.prank(deriveAddress("non-onwer")); + vm.prank(deriveAddress('non-onwer')); expectRevertNonOwner(); dispatcher.createClient(initClientMsg); } function test_onlyOnce() public { dispatcher.createClient(initClientMsg); - vm.expectRevert(abi.encodeWithSignature("clientAlreadyCreated()")); + vm.expectRevert(abi.encodeWithSignature('clientAlreadyCreated()')); dispatcher.createClient(initClientMsg); } } @@ -46,10 +46,10 @@ contract DispatcherUpdateClientTest is ClientTestBase { } function test_updateConsensusState_invalid() public { - vm.expectRevert(abi.encodeWithSignature("consensusStateVerificationFailed()")); + vm.expectRevert(abi.encodeWithSignature('consensusStateVerificationFailed()')); dispatcher.updateClientWithConsensusState(untrustedState, proof); - vm.expectRevert(abi.encodeWithSignature("consensusStateVerificationFailed()")); + vm.expectRevert(abi.encodeWithSignature('consensusStateVerificationFailed()')); ConsensusState memory invalidConsensusState; dispatcher.updateClientWithConsensusState(invalidConsensusState, proof); } @@ -63,12 +63,12 @@ contract DispatcherUpgradeClientTest is ClientTestBase { } function test_success() public { - dispatcher.upgradeClient(UpgradeClientMsg(bytes("upgradeOptimisticConsensusState"), trustedState)); + dispatcher.upgradeClient(UpgradeClientMsg(bytes('upgradeOptimisticConsensusState'), trustedState)); } function test_ownerOnly() public { - vm.prank(deriveAddress("non-onwer")); + vm.prank(deriveAddress('non-onwer')); expectRevertNonOwner(); - dispatcher.upgradeClient(UpgradeClientMsg(bytes("upgradeOptimisticConsensusState"), trustedState)); + dispatcher.upgradeClient(UpgradeClientMsg(bytes('upgradeOptimisticConsensusState'), trustedState)); } } diff --git a/test/Dispatcher.t.sol b/test/Dispatcher.t.sol index 34040f27..a6704d95 100644 --- a/test/Dispatcher.t.sol +++ b/test/Dispatcher.t.sol @@ -1,15 +1,15 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; -import "../contracts/Ibc.sol"; -import {Dispatcher, InitClientMsg, UpgradeClientMsg} from "../contracts/Dispatcher.sol"; -import {IbcEventsEmitter} from "../contracts/IbcDispatcher.sol"; -import {IbcReceiver} from "../contracts/IbcReceiver.sol"; -import "../contracts/IbcVerifier.sol"; -import "../contracts/Verifier.sol"; -import "../contracts/Mars.sol"; -import "../contracts/OpConsensusStateManager.sol"; -import "./Dispatcher.base.t.sol"; +import '../contracts/Ibc.sol'; +import {Dispatcher, InitClientMsg, UpgradeClientMsg} from '../contracts/Dispatcher.sol'; +import {IbcEventsEmitter} from '../contracts/IbcDispatcher.sol'; +import {IbcReceiver} from '../contracts/IbcReceiver.sol'; +import '../contracts/IbcVerifier.sol'; +import '../contracts/Verifier.sol'; +import '../contracts/Mars.sol'; +import '../contracts/OpConsensusStateManager.sol'; +import './Dispatcher.base.t.sol'; contract ChannelHandshakeTest is Base { LocalEnd _local; @@ -19,13 +19,13 @@ contract ChannelHandshakeTest is Base { function setUp() public { dispatcher = new Dispatcher(verifier, portPrefix, dummyConsStateManager); mars = new Mars(dispatcher); - _local = LocalEnd(mars, "channel-1", connectionHops, "1.0", "1.0"); - _remote = RemoteEnd("eth2.7E5F4552091A69125d5DfCb7b8C2659029395Bdf", "channel-2", "1.0"); + _local = LocalEnd(mars, 'channel-1', connectionHops, '1.0', '1.0'); + _remote = RemoteEnd('eth2.7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'channel-2', '1.0'); } function test_openChannel_initiator_ok() public { ChannelHandshakeSetting[4] memory settings = createSettings(true, true); - string[2] memory versions = ["1.0", "2.0"]; + string[2] memory versions = ['1.0', '2.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; @@ -40,7 +40,7 @@ contract ChannelHandshakeTest is Base { function test_openChannel_receiver_ok() public { ChannelHandshakeSetting[4] memory settings = createSettings(false, true); - string[2] memory versions = ["1.0", "2.0"]; + string[2] memory versions = ['1.0', '2.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; @@ -53,7 +53,7 @@ contract ChannelHandshakeTest is Base { openChannel(le, re, settings[i], true); // auto version selection - le.versionCall = ""; + le.versionCall = ''; openChannel(le, re, settings[i], true); } } @@ -62,7 +62,7 @@ contract ChannelHandshakeTest is Base { function test_connectChannel_ok() public { ChannelHandshakeSetting[8] memory settings = createSettings2(true); - string[2] memory versions = ["1.0", "2.0"]; + string[2] memory versions = ['1.0', '2.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; @@ -78,16 +78,16 @@ contract ChannelHandshakeTest is Base { function test_openChannel_receiver_fail_versionMismatch() public { ChannelHandshakeSetting[4] memory settings = createSettings(false, true); - string[2] memory versions = ["1.0", "2.0"]; + string[2] memory versions = ['1.0', '2.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; RemoteEnd memory re = _remote; re.version = versions[j]; // always select the wrong version - bool isVersionOne = keccak256(abi.encodePacked(versions[j])) == keccak256(abi.encodePacked("1.0")); - le.versionCall = isVersionOne ? "2.0" : "1.0"; - vm.expectRevert(bytes("Version mismatch")); + bool isVersionOne = keccak256(abi.encodePacked(versions[j])) == keccak256(abi.encodePacked('1.0')); + le.versionCall = isVersionOne ? '2.0' : '1.0'; + vm.expectRevert(bytes('Version mismatch')); openChannel(le, re, settings[i], false); } } @@ -95,14 +95,14 @@ contract ChannelHandshakeTest is Base { function test_openChannel_initiator_fail_unsupportedVersion() public { ChannelHandshakeSetting[4] memory settings = createSettings(true, true); - string[2] memory versions = ["", "xxxxxxx"]; + string[2] memory versions = ['', 'xxxxxxx']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; RemoteEnd memory re = _remote; le.versionCall = versions[j]; le.versionExpected = versions[j]; - vm.expectRevert(bytes("Unsupported version")); + vm.expectRevert(bytes('Unsupported version')); openChannel(le, re, settings[i], false); } } @@ -111,14 +111,14 @@ contract ChannelHandshakeTest is Base { function test_openChannel_receiver_fail_invalidProof() public { // When localEnd initiates, no proof verification is done in openIbcChannel ChannelHandshakeSetting[4] memory settings = createSettings(false, false); - string[1] memory versions = ["1.0"]; + string[1] memory versions = ['1.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; RemoteEnd memory re = _remote; le.versionCall = versions[j]; le.versionExpected = versions[j]; - vm.expectRevert("Fail to prove channel state"); + vm.expectRevert('Fail to prove channel state'); openChannel(le, re, settings[i], false); } } @@ -127,7 +127,7 @@ contract ChannelHandshakeTest is Base { function test_connectChannel_fail_unsupportedVersion() public { // When localEnd initiates, counterparty version is only available in connectIbcChannel ChannelHandshakeSetting[4] memory settings = createSettings(true, true); - string[2] memory versions = ["", "xxxxxxx"]; + string[2] memory versions = ['', 'xxxxxxx']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; @@ -135,7 +135,7 @@ contract ChannelHandshakeTest is Base { // no remote version applied in openChannel openChannel(le, re, settings[i], true); re.version = versions[j]; - vm.expectRevert(bytes("Unsupported version")); + vm.expectRevert(bytes('Unsupported version')); connectChannel(le, re, settings[i], false); } } @@ -144,7 +144,7 @@ contract ChannelHandshakeTest is Base { function test_connectChannel_fail_invalidProof() public { // When localEnd initiates, counterparty version is only available in connectIbcChannel ChannelHandshakeSetting[8] memory settings = createSettings2(true); - string[1] memory versions = ["1.0"]; + string[1] memory versions = ['1.0']; for (uint256 i = 0; i < settings.length; i++) { for (uint256 j = 0; j < versions.length; j++) { LocalEnd memory le = _local; @@ -153,17 +153,16 @@ contract ChannelHandshakeTest is Base { openChannel(le, re, settings[i], true); re.version = versions[j]; settings[i].proof = invalidProof; - vm.expectRevert("Fail to prove channel state"); + vm.expectRevert('Fail to prove channel state'); connectChannel(le, re, settings[i], false); } } } - function createSettings(bool localInitiate, bool isProofValid) - internal - view - returns (ChannelHandshakeSetting[4] memory) - { + function createSettings( + bool localInitiate, + bool isProofValid + ) internal view returns (ChannelHandshakeSetting[4] memory) { Proof memory proof = isProofValid ? validProof : invalidProof; ChannelHandshakeSetting[4] memory settings = [ ChannelHandshakeSetting(ChannelOrder.ORDERED, false, localInitiate, proof), @@ -190,8 +189,8 @@ contract ChannelHandshakeTest is Base { // This Base contract provides an open channel for sub-contract tests contract ChannelOpenTestBase is Base { - bytes32 channelId = "channel-1"; - address relayer = deriveAddress("relayer"); + bytes32 channelId = 'channel-1'; + address relayer = deriveAddress('relayer'); bool feeEnabled = false; LocalEnd _local; @@ -208,8 +207,8 @@ contract ChannelOpenTestBase is Base { vm.deal(relayer, 100000 ether); mars = new Mars(dispatcher); - _local = LocalEnd(mars, channelId, connectionHops, "1.0", "1.0"); - _remote = RemoteEnd("eth2.7E5F4552091A69125d5DfCb7b8C2659029395Bdf", "channel-2", "1.0"); + _local = LocalEnd(mars, channelId, connectionHops, '1.0', '1.0'); + _remote = RemoteEnd('eth2.7E5F4552091A69125d5DfCb7b8C2659029395Bdf', 'channel-2', '1.0'); openChannel(_local, _remote, setting, true); connectChannel(_local, _remote, setting, true); @@ -225,7 +224,7 @@ contract DispatcherCloseChannelTest is ChannelOpenTestBase { function test_closeChannelInit_mustOwner() public { Mars earth = new Mars(dispatcher); - vm.expectRevert(abi.encodeWithSignature("channelNotOwnedBySender()")); + vm.expectRevert(abi.encodeWithSignature('channelNotOwnedBySender()')); earth.triggerChannelClose(channelId); } @@ -236,19 +235,19 @@ contract DispatcherCloseChannelTest is ChannelOpenTestBase { } function test_closeChannelConfirm_mustOwner() public { - vm.expectRevert(abi.encodeWithSignature("channelNotOwnedByPortAddress()")); - dispatcher.onCloseIbcChannel(address(mars), "channel-999", validProof); + vm.expectRevert(abi.encodeWithSignature('channelNotOwnedByPortAddress()')); + dispatcher.onCloseIbcChannel(address(mars), 'channel-999', validProof); } function test_closeChannelConfirm_invalidProof() public { - vm.expectRevert("Fail to prove channel state"); + vm.expectRevert('Fail to prove channel state'); dispatcher.onCloseIbcChannel(address(mars), channelId, invalidProof); } } contract DispatcherSendPacketTest is ChannelOpenTestBase { // default params - string payload = "msgPayload"; + string payload = 'msgPayload'; uint64 timeoutTimestamp = 1000; function test_success() public { @@ -264,15 +263,15 @@ contract DispatcherSendPacketTest is ChannelOpenTestBase { // sendPacket fails if calling dApp doesn't own the channel function test_mustOwner() public { Mars earth = new Mars(dispatcher); - vm.expectRevert(abi.encodeWithSignature("channelNotOwnedBySender()")); + vm.expectRevert(abi.encodeWithSignature('channelNotOwnedBySender()')); earth.greet(payload, channelId, timeoutTimestamp); } } contract PacketSenderTestBase is ChannelOpenTestBase { - IbcEndpoint dest = IbcEndpoint("polyibc.bsc.9876543210", "channel-99"); + IbcEndpoint dest = IbcEndpoint('polyibc.bsc.9876543210', 'channel-99'); IbcEndpoint src; - string payloadStr = "msgPayload"; + string payloadStr = 'msgPayload'; bytes payload = bytes(payloadStr); bytes appAck = abi.encodePacked('{ "account": "account", "reply": "got the message" }'); @@ -303,15 +302,15 @@ contract PacketSenderTestBase is ChannelOpenTestBase { // genAckPacket generates an ack packet for the given packet sequence function genAckPacket(uint64 packetSeq) internal pure returns (AckPacket memory) { - return AckPacket(true, abi.encodePacked("ackPacket", packetSeq)); + return AckPacket(true, abi.encodePacked('ackPacket', packetSeq)); } } // Test Chains B receives a packet from Chain A contract DispatcherRecvPacketTest is ChannelOpenTestBase { - IbcEndpoint src = IbcEndpoint("polyibc.bsc.9876543210", "channel-99"); + IbcEndpoint src = IbcEndpoint('polyibc.bsc.9876543210', 'channel-99'); IbcEndpoint dest; - bytes payload = bytes("msgPayload"); + bytes payload = bytes('msgPayload'); bytes appAck = abi.encodePacked('{ "account": "account", "reply": "got the message" }'); function setUp() public override { @@ -328,7 +327,9 @@ contract DispatcherRecvPacketTest is ChannelOpenTestBase { vm.expectEmit(true, true, false, true, address(dispatcher)); emit WriteAckPacket(address(mars), channelId, packetSeq, AckPacket(true, appAck)); dispatcher.recvPacket( - IbcReceiver(mars), IbcPacket(src, dest, packetSeq, payload, ZERO_HEIGHT, maxTimeout), validProof + IbcReceiver(mars), + IbcPacket(src, dest, packetSeq, payload, ZERO_HEIGHT, maxTimeout), + validProof ); } } @@ -358,7 +359,7 @@ contract DispatcherRecvPacketTest is ChannelOpenTestBase { // cannot receive packets out of order for ordered channel function test_outOfOrder() public { dispatcher.recvPacket(IbcReceiver(mars), IbcPacket(src, dest, 1, payload, ZERO_HEIGHT, maxTimeout), validProof); - vm.expectRevert(abi.encodeWithSignature("unexpectedPacketSequence()")); + vm.expectRevert(abi.encodeWithSignature('unexpectedPacketSequence()')); dispatcher.recvPacket(IbcReceiver(mars), IbcPacket(src, dest, 3, payload, ZERO_HEIGHT, maxTimeout), validProof); } @@ -383,14 +384,14 @@ contract DispatcherAckPacketTest is PacketSenderTestBase { // cannot ack packets if packet commitment is missing function test_missingPacket() public { - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); dispatcher.acknowledgement(IbcReceiver(mars), genPacket(1), genAckPacket(1), validProof); sendPacket(); dispatcher.acknowledgement(IbcReceiver(mars), sentPacket, ackPacket, validProof); // packet commitment is removed after ack - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); dispatcher.acknowledgement(IbcReceiver(mars), sentPacket, ackPacket, validProof); } @@ -403,7 +404,7 @@ contract DispatcherAckPacketTest is PacketSenderTestBase { dispatcher.acknowledgement(IbcReceiver(mars), genPacket(1), genAckPacket(1), validProof); // only 2nd ack is allowed; so the 3rd ack fails - vm.expectRevert(abi.encodeWithSignature("unexpectedPacketSequence()")); + vm.expectRevert(abi.encodeWithSignature('unexpectedPacketSequence()')); dispatcher.acknowledgement(IbcReceiver(mars), genPacket(3), genAckPacket(3), validProof); } @@ -419,7 +420,7 @@ contract DispatcherAckPacketTest is PacketSenderTestBase { IbcPacket memory packetEarth = sentPacket; packetEarth.src = earthEnd; - vm.expectRevert(abi.encodeWithSignature("receiverNotOriginPacketSender()")); + vm.expectRevert(abi.encodeWithSignature('receiverNotOriginPacketSender()')); dispatcher.acknowledgement(IbcReceiver(mars), packetEarth, ackPacket, validProof); } @@ -427,11 +428,11 @@ contract DispatcherAckPacketTest is PacketSenderTestBase { function test_invalidChannel() public { sendPacket(); - IbcEndpoint memory invalidSrc = IbcEndpoint(src.portId, "channel-invalid"); + IbcEndpoint memory invalidSrc = IbcEndpoint(src.portId, 'channel-invalid'); IbcPacket memory packet = sentPacket; packet.src = invalidSrc; - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); dispatcher.acknowledgement(IbcReceiver(mars), packet, ackPacket, validProof); } } @@ -453,14 +454,14 @@ contract DispatcherTimeoutPacketTest is PacketSenderTestBase { // cannot timeout packets if packet commitment is missing function test_missingPacket() public { - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); dispatcher.timeout(IbcReceiver(mars), genPacket(1), validProof); sendPacket(); dispatcher.timeout(IbcReceiver(mars), sentPacket, validProof); // packet commitment is removed after timeout - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); dispatcher.timeout(IbcReceiver(mars), sentPacket, validProof); } @@ -476,7 +477,7 @@ contract DispatcherTimeoutPacketTest is PacketSenderTestBase { IbcPacket memory packetEarth = sentPacket; packetEarth.src = earthEnd; - vm.expectRevert(abi.encodeWithSignature("receiverNotIndtendedPacketDestination()")); + vm.expectRevert(abi.encodeWithSignature('receiverNotIndtendedPacketDestination()')); dispatcher.timeout(IbcReceiver(mars), packetEarth, validProof); } @@ -484,11 +485,11 @@ contract DispatcherTimeoutPacketTest is PacketSenderTestBase { function test_invalidChannel() public { sendPacket(); - IbcEndpoint memory invalidSrc = IbcEndpoint(src.portId, "channel-invalid"); + IbcEndpoint memory invalidSrc = IbcEndpoint(src.portId, 'channel-invalid'); IbcPacket memory packet = sentPacket; packet.src = invalidSrc; - vm.expectRevert(abi.encodeWithSignature("packetCommitmentNotFound()")); + vm.expectRevert(abi.encodeWithSignature('packetCommitmentNotFound()')); /* vm.expectRevert('Packet commitment not found'); */ dispatcher.timeout(IbcReceiver(mars), packet, validProof); } @@ -497,7 +498,7 @@ contract DispatcherTimeoutPacketTest is PacketSenderTestBase { function test_invalidProof() public { sendPacket(); - vm.expectRevert("Fail to prove timeout"); + vm.expectRevert('Fail to prove timeout'); dispatcher.timeout(IbcReceiver(mars), sentPacket, invalidProof); } } diff --git a/test/OpConsensusStateManager.t.sol b/test/OpConsensusStateManager.t.sol index d807b4d1..cf4ca97e 100644 --- a/test/OpConsensusStateManager.t.sol +++ b/test/OpConsensusStateManager.t.sol @@ -8,7 +8,7 @@ import '../contracts/DummyVerifier.sol'; contract OptimisticConsensusStateManagerTest is Test { OptimisticConsensusStateManager manager; DummyVerifier verifier; - + function setUp() public { verifier = new DummyVerifier(); manager = new OptimisticConsensusStateManager(1, verifier); @@ -35,7 +35,11 @@ contract OptimisticConsensusStateManagerTest is Test { function test_addOpConsensusState_addingPendingOpConsensusStateWithDifferentValuesIsError() public { manager.addOpConsensusState(1, 1); - vm.expectRevert(bytes('cannot update a pending optimistic consensus state with a different appHash, please submit fraud proof instead')); + vm.expectRevert( + bytes( + 'cannot update a pending optimistic consensus state with a different appHash, please submit fraud proof instead' + ) + ); manager.addOpConsensusState(1, 2); } @@ -59,7 +63,7 @@ contract OptimisticConsensusStateManagerTest is Test { manager.addOpConsensusState(1, 1); (, uint256 endTime, bool ended) = manager.getState(1); assertEq(true, ended); - } + } function test_getState_nonExist() public { (uint256 appHash, , bool ended) = manager.getState(1); diff --git a/test/VirtualChain.sol b/test/VirtualChain.sol index ac3503ca..3b19eb0b 100644 --- a/test/VirtualChain.sol +++ b/test/VirtualChain.sol @@ -1,17 +1,17 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; -import "forge-std/Test.sol"; -import "@openzeppelin/contracts/utils/Strings.sol"; -import "../contracts/Ibc.sol"; -import "../contracts/Dispatcher.sol"; -import "../contracts/Verifier.sol"; -import {UniversalChannelHandler} from "../contracts/UniversalChannelHandler.sol"; -import {Mars} from "../contracts/Mars.sol"; -import {Earth} from "../contracts/Earth.sol"; -import {IbcMiddleware} from "../contracts/IbcMiddleware.sol"; -import {GeneralMiddleware} from "../contracts/GeneralMiddleware.sol"; -import "../contracts/DummyConsensusStateManager.sol"; +import 'forge-std/Test.sol'; +import '@openzeppelin/contracts/utils/Strings.sol'; +import '../contracts/Ibc.sol'; +import '../contracts/Dispatcher.sol'; +import '../contracts/Verifier.sol'; +import {UniversalChannelHandler} from '../contracts/UniversalChannelHandler.sol'; +import {Mars} from '../contracts/Mars.sol'; +import {Earth} from '../contracts/Earth.sol'; +import {IbcMiddleware} from '../contracts/IbcMiddleware.sol'; +import {GeneralMiddleware} from '../contracts/GeneralMiddleware.sol'; +import '../contracts/DummyConsensusStateManager.sol'; struct ChannelSetting { ChannelOrder ordering; @@ -83,14 +83,15 @@ contract VirtualChain is Test, IbcEventsEmitter { string[] memory counterpartyConnectionHops, ChannelSetting memory setting ) public view returns (Channel memory) { - return Channel( - setting.version, - setting.ordering, - setting.feeEnabled, - counterpartyConnectionHops, - portIds[localAddr], - localChanId - ); + return + Channel( + setting.version, + setting.ordering, + setting.feeEnabled, + counterpartyConnectionHops, + portIds[localAddr], + localChanId + ); } function getConnectionHops() external view returns (string[] memory) { @@ -98,9 +99,11 @@ contract VirtualChain is Test, IbcEventsEmitter { } // Assign new channelIds to both ends of the channel - function assignChanelIds(IbcChannelReceiver localEnd, IbcChannelReceiver remoteEnd, VirtualChain remoteChain) - external - { + function assignChanelIds( + IbcChannelReceiver localEnd, + IbcChannelReceiver remoteEnd, + VirtualChain remoteChain + ) external { bytes32 localChannelId = this.newChannelId(); bytes32 remoteChannelId = remoteChain.newChannelId(); // save channelIds on each virtual chain @@ -144,7 +147,7 @@ contract VirtualChain is Test, IbcEventsEmitter { bool expPass ) external { string memory cpPortId = remoteChain.portIds(address(remoteEnd)); - require(bytes(cpPortId).length > 0, "channelOpenTry: portId does not exist"); + require(bytes(cpPortId).length > 0, 'channelOpenTry: portId does not exist'); // set dispatcher's msg.sender to this function's msg.sender vm.prank(msg.sender); @@ -168,7 +171,7 @@ contract VirtualChain is Test, IbcEventsEmitter { setting.feeEnabled, connectionHops, // counterparty channelId and version are not known at this point - CounterParty(cpPortId, bytes32(0), ""), + CounterParty(cpPortId, bytes32(0), ''), setting.proof ); } @@ -181,10 +184,10 @@ contract VirtualChain is Test, IbcEventsEmitter { bool expPass ) external { bytes32 cpChanId = remoteChain.channelIds(address(remoteEnd), address(localEnd)); - require(cpChanId != bytes32(0), "channelOpenTry: channel does not exist"); + require(cpChanId != bytes32(0), 'channelOpenTry: channel does not exist'); string memory cpPortId = remoteChain.portIds(address(remoteEnd)); - require(bytes(cpPortId).length > 0, "channelOpenTry: portId does not exist"); + require(bytes(cpPortId).length > 0, 'channelOpenTry: portId does not exist'); // set dispatcher's msg.sender to this function's msg.sender vm.prank(msg.sender); @@ -221,13 +224,13 @@ contract VirtualChain is Test, IbcEventsEmitter { ) external { // local channel Id must be known bytes32 chanId = channelIds[address(localEnd)][address(remoteEnd)]; - require(chanId != bytes32(0), "channelOpenAckOrConfirm: channel does not exist"); + require(chanId != bytes32(0), 'channelOpenAckOrConfirm: channel does not exist'); bytes32 cpChanId = remoteChain.channelIds(address(remoteEnd), address(localEnd)); - require(cpChanId != bytes32(0), "channelOpenAckOrConfirm: channel does not exist"); + require(cpChanId != bytes32(0), 'channelOpenAckOrConfirm: channel does not exist'); string memory cpPortId = remoteChain.portIds(address(remoteEnd)); - require(bytes(cpPortId).length > 0, "channelOpenAckOrConfirm: counterparty portId does not exist"); + require(bytes(cpPortId).length > 0, 'channelOpenAckOrConfirm: counterparty portId does not exist'); // set dispatcher's msg.sender to this function's msg.sender vm.prank(msg.sender); @@ -251,7 +254,7 @@ contract VirtualChain is Test, IbcEventsEmitter { // Converts a local dApp address on this virtual chain to a Counterparty struct for a remote chain function localEndToCounterparty(address localEnd) external view returns (CounterParty memory) { - return CounterParty(portIds[localEnd], channelIds[localEnd][address(this)], ""); + return CounterParty(portIds[localEnd], channelIds[localEnd][address(this)], ''); } function setChannelId(IbcChannelReceiver localEnd, IbcChannelReceiver remoteEnd, bytes32 channelId) external { @@ -259,13 +262,13 @@ contract VirtualChain is Test, IbcEventsEmitter { } function newChannelId() external returns (bytes32) { - bytes memory channelId = abi.encodePacked("channel-", Strings.toString(_seed)); + bytes memory channelId = abi.encodePacked('channel-', Strings.toString(_seed)); _seed += 1; return bytes32(channelId); } function newConnectionId() internal returns (string memory) { - string memory connectionId = string(abi.encodePacked("connection-", Strings.toString(_seed))); + string memory connectionId = string(abi.encodePacked('connection-', Strings.toString(_seed))); _seed += 1; return connectionId; } diff --git a/test/universal.channel.t.sol b/test/universal.channel.t.sol index 8c03d18e..12fc0a24 100644 --- a/test/universal.channel.t.sol +++ b/test/universal.channel.t.sol @@ -1,17 +1,17 @@ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; -import "../contracts/Ibc.sol"; -import {Dispatcher, InitClientMsg, UpgradeClientMsg} from "../contracts/Dispatcher.sol"; -import {IbcEventsEmitter} from "../contracts/IbcDispatcher.sol"; -import {IbcReceiver} from "../contracts/IbcReceiver.sol"; -import "../contracts/IbcVerifier.sol"; -import "../contracts/UniversalChannelHandler.sol"; -import "../contracts/Verifier.sol"; -import "../contracts/Mars.sol"; -import "../contracts/OpConsensusStateManager.sol"; -import "./Dispatcher.base.t.sol"; -import "./VirtualChain.sol"; +import '../contracts/Ibc.sol'; +import {Dispatcher, InitClientMsg, UpgradeClientMsg} from '../contracts/Dispatcher.sol'; +import {IbcEventsEmitter} from '../contracts/IbcDispatcher.sol'; +import {IbcReceiver} from '../contracts/IbcReceiver.sol'; +import '../contracts/IbcVerifier.sol'; +import '../contracts/UniversalChannelHandler.sol'; +import '../contracts/Verifier.sol'; +import '../contracts/Mars.sol'; +import '../contracts/OpConsensusStateManager.sol'; +import './Dispatcher.base.t.sol'; +import './VirtualChain.sol'; contract UniversalChannelTest is Base { function test_channel_settings_ok() public { @@ -20,9 +20,9 @@ contract UniversalChannelTest is Base { for (uint256 i = 0; i < orders.length; i++) { for (uint256 j = 0; j < feesEnabled.length; j++) { - VirtualChain eth1 = new VirtualChain(100, "polyibc.eth1."); - VirtualChain eth2 = new VirtualChain(200, "polyibc.eth2."); - ChannelSetting memory setting = ChannelSetting(orders[i], "1.0", feesEnabled[j], validProof); + VirtualChain eth1 = new VirtualChain(100, 'polyibc.eth1.'); + VirtualChain eth2 = new VirtualChain(200, 'polyibc.eth2.'); + ChannelSetting memory setting = ChannelSetting(orders[i], '1.0', feesEnabled[j], validProof); eth1.finishHandshake(eth1.ucHandler(), eth2, eth2.ucHandler(), setting); assert_channel(eth1, eth2, setting); @@ -38,25 +38,33 @@ contract UniversalChannelTest is Base { Channel memory channel1 = vc1.dispatcher().getChannel(address(vc1.ucHandler()), channelId1); Channel memory channel2 = vc2.dispatcher().getChannel(address(vc2.ucHandler()), channelId2); - Channel memory channel2Expected = - vc1.expectedChannel(address(vc1.ucHandler()), channelId1, vc2.getConnectionHops(), setting); - Channel memory channel1Expected = - vc2.expectedChannel(address(vc2.ucHandler()), channelId2, vc1.getConnectionHops(), setting); + Channel memory channel2Expected = vc1.expectedChannel( + address(vc1.ucHandler()), + channelId1, + vc2.getConnectionHops(), + setting + ); + Channel memory channel1Expected = vc2.expectedChannel( + address(vc2.ucHandler()), + channelId2, + vc1.getConnectionHops(), + setting + ); assertEq(abi.encode(channel1), abi.encode(channel1Expected)); assertEq(abi.encode(channel2), abi.encode(channel2Expected)); } // anyone can open channels, universal or not. But only "official channels" are shown in public IBC dashboards function test_channel_ok_by_anyone() public { - VirtualChain eth1 = new VirtualChain(100, "polyibc.eth1."); - VirtualChain eth2 = new VirtualChain(200, "polyibc.eth2."); - ChannelSetting memory setting = ChannelSetting(ChannelOrder.UNORDERED, "1.0", true, validProof); + VirtualChain eth1 = new VirtualChain(100, 'polyibc.eth1.'); + VirtualChain eth2 = new VirtualChain(200, 'polyibc.eth2.'); + ChannelSetting memory setting = ChannelSetting(ChannelOrder.UNORDERED, '1.0', true, validProof); IbcChannelReceiver ucHandler1 = eth1.ucHandler(); IbcChannelReceiver ucHandler2 = eth2.ucHandler(); eth1.assignChanelIds(ucHandler1, ucHandler2, eth2); - address unauthorized = deriveAddress("unauthorized"); + address unauthorized = deriveAddress('unauthorized'); vm.deal(unauthorized, 100 ether); vm.prank(unauthorized); eth1.channelOpenInit(ucHandler1, eth2, ucHandler2, setting, true); @@ -81,11 +89,11 @@ struct UcPacket { contract UniversalChannelPacketTest is Base, IbcMwEventsEmitter { VirtualChain eth1; VirtualChain eth2; - ChannelSetting setting = ChannelSetting(ChannelOrder.UNORDERED, "1.0", true, validProof); + ChannelSetting setting = ChannelSetting(ChannelOrder.UNORDERED, '1.0', true, validProof); VirtualChainData v1; VirtualChainData v2; - bytes appData = bytes("msg-1"); + bytes appData = bytes('msg-1'); bytes packetData; bytes ackPacketBytes; // AckPacket generated by chainB.Earth and received by chainA.Earth @@ -103,8 +111,8 @@ contract UniversalChannelPacketTest is Base, IbcMwEventsEmitter { bytes32 gotChannelId; function setUp() public virtual { - eth1 = new VirtualChain(100, "polyibc.eth1."); - eth2 = new VirtualChain(200, "polyibc.eth2."); + eth1 = new VirtualChain(100, 'polyibc.eth1.'); + eth2 = new VirtualChain(200, 'polyibc.eth2.'); eth1.finishHandshake(eth1.ucHandler(), eth2, eth2.ucHandler(), setting); v1 = eth1.getVirtualChainData(); v2 = eth2.getVirtualChainData(); @@ -214,10 +222,14 @@ contract UniversalChannelPacketTest is Base, IbcMwEventsEmitter { for (uint64 packetSeq = 1; packetSeq <= numOfPackets; packetSeq++) { uint64 factor = packetSeq; // change packet settings for each iteration uint64 timeout = 1 seconds * 10 ** 9; - appData = abi.encodePacked("msg-", packetSeq); + appData = abi.encodePacked('msg-', packetSeq); - ucPacket = - UniversalPacket(Ibc.toBytes32(address(v1.earth)), mwBitmap, Ibc.toBytes32(address(v2.earth)), appData); + ucPacket = UniversalPacket( + Ibc.toBytes32(address(v1.earth)), + mwBitmap, + Ibc.toBytes32(address(v2.earth)), + appData + ); packetData = Ibc.toUniversalPacketBytes(ucPacket); // iterate over sending middleware contracts to verify each MW has witnessed the packet @@ -299,10 +311,14 @@ contract UniversalChannelPacketTest is Base, IbcMwEventsEmitter { for (uint64 packetSeq = 1; packetSeq <= numOfPackets; packetSeq++) { uint64 factor = packetSeq; // change packet settings for each iteration uint64 timeout = 1 days * 10 ** 9 * factor; - appData = abi.encodePacked("msg-", packetSeq); + appData = abi.encodePacked('msg-', packetSeq); - ucPacket = - UniversalPacket(Ibc.toBytes32(address(v1.earth)), mwBitmap, Ibc.toBytes32(address(v2.earth)), appData); + ucPacket = UniversalPacket( + Ibc.toBytes32(address(v1.earth)), + mwBitmap, + Ibc.toBytes32(address(v2.earth)), + appData + ); packetData = Ibc.toUniversalPacketBytes(ucPacket); // iterate over sending middleware contracts to verify each MW has witnessed the packet