├── .assets └── xchain-helpers.png ├── audits ├── v100-cantina-audit.pdf ├── v110-cantina-audit.pdf ├── v100-chainsecurity-audit.pdf └── v110-chainsecurity-audit.pdf ├── .gitignore ├── test ├── mocks │ └── TargetContractMock.sol ├── ArbitrumReceiver.t.sol ├── OptimismReceiver.t.sol ├── ArbitrumIntegration.t.sol ├── AMBReceiver.t.sol ├── CCTPReceiver.t.sol ├── OptimismIntegration.t.sol ├── GnosisIntegration.t.sol ├── IntegrationBase.t.sol ├── LZIntegrationWithLZToken.t.sol ├── RecordedLogs.t.sol ├── LZReceiver.t.sol ├── CircleCCTPIntegration.t.sol └── LZIntegration.t.sol ├── .gitmodules ├── src ├── testing │ ├── Bridge.sol │ ├── Domain.sol │ ├── bridges │ │ ├── AMBBridgeTesting.sol │ │ ├── OptimismBridgeTesting.sol │ │ ├── CCTPBridgeTesting.sol │ │ ├── ArbitrumBridgeTesting.sol │ │ └── LZBridgeTesting.sol │ └── utils │ │ └── RecordedLogs.sol ├── receivers │ ├── ArbitrumReceiver.sol │ ├── OptimismReceiver.sol │ ├── CCTPReceiver.sol │ ├── AMBReceiver.sol │ └── LZReceiver.sol └── forwarders │ ├── OptimismForwarder.sol │ ├── AMBForwarder.sol │ ├── ArbitrumForwarder.sol │ ├── CCTPForwarder.sol │ └── LZForwarder.sol ├── foundry.toml ├── README.md ├── .github └── workflows │ └── ci.yml └── LICENSE /.assets/xchain-helpers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/xchain-helpers/HEAD/.assets/xchain-helpers.png -------------------------------------------------------------------------------- /audits/v100-cantina-audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/xchain-helpers/HEAD/audits/v100-cantina-audit.pdf -------------------------------------------------------------------------------- /audits/v110-cantina-audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/xchain-helpers/HEAD/audits/v110-cantina-audit.pdf -------------------------------------------------------------------------------- /audits/v100-chainsecurity-audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/xchain-helpers/HEAD/audits/v100-chainsecurity-audit.pdf -------------------------------------------------------------------------------- /audits/v110-chainsecurity-audit.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sparkdotfi/xchain-helpers/HEAD/audits/v110-chainsecurity-audit.pdf -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiler files 2 | cache/ 3 | out/ 4 | 5 | # Ignores development broadcast logs 6 | !/broadcast 7 | /broadcast/*/31337/ 8 | /broadcast/**/dry-run/ 9 | 10 | # Docs 11 | docs/ 12 | 13 | # Dotenv file 14 | .env 15 | -------------------------------------------------------------------------------- /test/mocks/TargetContractMock.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | contract TargetContractMock { 5 | 6 | uint256 public count; 7 | 8 | function increment() external { 9 | count++; 10 | } 11 | 12 | function revertFunc() external pure { 13 | revert("TargetContract/error"); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "lib/forge-std"] 2 | path = lib/forge-std 3 | url = https://github.com/foundry-rs/forge-std 4 | [submodule "lib/openzeppelin-contracts"] 5 | path = lib/openzeppelin-contracts 6 | url = https://github.com/openzeppelin/openzeppelin-contracts 7 | [submodule "lib/devtools"] 8 | path = lib/devtools 9 | url = https://github.com/layerzero-labs/devtools 10 | [submodule "lib/solidity-bytes-utils"] 11 | path = lib/solidity-bytes-utils 12 | url = https://github.com/GNSPS/solidity-bytes-utils 13 | [submodule "lib/LayerZero-v2"] 14 | path = lib/LayerZero-v2 15 | url = https://github.com/layerzero-labs/LayerZero-v2 16 | -------------------------------------------------------------------------------- /src/testing/Bridge.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Domain } from "./Domain.sol"; 5 | 6 | enum BridgeType { 7 | OPTIMISM, 8 | ARBITRUM, 9 | CCTP, 10 | AMB, 11 | LZ 12 | } 13 | 14 | struct Bridge { 15 | BridgeType bridgeType; 16 | Domain source; 17 | Domain destination; 18 | address sourceCrossChainMessenger; 19 | address destinationCrossChainMessenger; 20 | // These are used internally for log tracking 21 | uint256 lastSourceLogIndex; 22 | uint256 lastDestinationLogIndex; 23 | bytes extraData; 24 | } 25 | -------------------------------------------------------------------------------- /foundry.toml: -------------------------------------------------------------------------------- 1 | [profile.default] 2 | src = "src" 3 | out = "out" 4 | libs = ["lib"] 5 | 6 | remappings = [ 7 | '@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/', 8 | 'layerzerolabs/oapp-evm/=lib/devtools/packages/oapp-evm/', 9 | '@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/', 10 | '@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/', 11 | '@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/', 12 | 'solidity-bytes-utils/=lib/solidity-bytes-utils/', 13 | ] 14 | 15 | # See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options 16 | -------------------------------------------------------------------------------- /src/receivers/ArbitrumReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { Address } from "openzeppelin-contracts/contracts/utils/Address.sol"; 5 | 6 | /** 7 | * @title ArbitrumReceiver 8 | * @notice Receive messages to an Arbitrum-style chain. 9 | */ 10 | contract ArbitrumReceiver { 11 | 12 | using Address for address; 13 | 14 | address public immutable l1Authority; 15 | address public immutable target; 16 | 17 | constructor( 18 | address _l1Authority, 19 | address _target 20 | ) { 21 | l1Authority = _l1Authority; 22 | target = _target; 23 | } 24 | 25 | function _getL1MessageSender() internal view returns (address) { 26 | unchecked { 27 | return address(uint160(msg.sender) - uint160(0x1111000000000000000000000000000000001111)); 28 | } 29 | } 30 | 31 | fallback(bytes calldata message) external returns (bytes memory) { 32 | require(_getL1MessageSender() == l1Authority, "ArbitrumReceiver/invalid-l1Authority"); 33 | 34 | return target.functionCall(message); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/receivers/OptimismReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { Address } from "openzeppelin-contracts/contracts/utils/Address.sol"; 5 | 6 | interface ICrossDomainOptimism { 7 | function xDomainMessageSender() external view returns (address); 8 | } 9 | 10 | /** 11 | * @title OptimismReceiver 12 | * @notice Receive messages to an Optimism-style chain. 13 | */ 14 | contract OptimismReceiver { 15 | 16 | using Address for address; 17 | 18 | ICrossDomainOptimism public constant l2CrossDomain = ICrossDomainOptimism(0x4200000000000000000000000000000000000007); 19 | 20 | address public immutable l1Authority; 21 | address public immutable target; 22 | 23 | constructor( 24 | address _l1Authority, 25 | address _target 26 | ) { 27 | l1Authority = _l1Authority; 28 | target = _target; 29 | } 30 | 31 | fallback(bytes calldata message) external returns (bytes memory) { 32 | require(msg.sender == address(l2CrossDomain), "OptimismReceiver/invalid-sender"); 33 | require(l2CrossDomain.xDomainMessageSender() == l1Authority, "OptimismReceiver/invalid-l1Authority"); 34 | 35 | return target.functionCall(message); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/forwarders/OptimismForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | interface ICrossDomainOptimism { 5 | function sendMessage(address _target, bytes calldata _message, uint32 _gasLimit) external; 6 | } 7 | 8 | library OptimismForwarder { 9 | 10 | address constant internal L1_CROSS_DOMAIN_BASE = 0x866E82a600A1414e583f7F13623F1aC5d58b0Afa; 11 | address constant internal L1_CROSS_DOMAIN_OPTIMISM = 0x25ace71c97B33Cc4729CF772ae268934F7ab5fA1; 12 | address constant internal L1_CROSS_DOMAIN_UNICHAIN = 0x9A3D64E386C18Cb1d6d5179a9596A4B5736e98A6; 13 | address constant internal L1_CROSS_DOMAIN_WORLD_CHAIN = 0xf931a81D18B1766d15695ffc7c1920a62b7e710a; 14 | 15 | address constant internal L2_CROSS_DOMAIN = 0x4200000000000000000000000000000000000007; 16 | 17 | function sendMessageL1toL2( 18 | address l1CrossDomain, 19 | address target, 20 | bytes memory message, 21 | uint32 gasLimit 22 | ) internal { 23 | ICrossDomainOptimism(l1CrossDomain).sendMessage( 24 | target, 25 | message, 26 | gasLimit 27 | ); 28 | } 29 | 30 | function sendMessageL2toL1( 31 | address target, 32 | bytes memory message, 33 | uint32 gasLimit 34 | ) internal { 35 | ICrossDomainOptimism(L2_CROSS_DOMAIN).sendMessage( 36 | target, 37 | message, 38 | gasLimit 39 | ); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/receivers/CCTPReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { Address } from "openzeppelin-contracts/contracts/utils/Address.sol"; 5 | 6 | /** 7 | * @title CCTPReceiver 8 | * @notice Receive messages from CCTP-style bridge. 9 | */ 10 | contract CCTPReceiver { 11 | 12 | using Address for address; 13 | 14 | address public immutable destinationMessenger; 15 | uint32 public immutable sourceDomainId; 16 | bytes32 public immutable sourceAuthority; 17 | address public immutable target; 18 | 19 | constructor( 20 | address _destinationMessenger, 21 | uint32 _sourceDomainId, 22 | bytes32 _sourceAuthority, 23 | address _target 24 | ) { 25 | destinationMessenger = _destinationMessenger; 26 | sourceDomainId = _sourceDomainId; 27 | sourceAuthority = _sourceAuthority; 28 | target = _target; 29 | } 30 | 31 | function handleReceiveMessage( 32 | uint32 sourceDomain, 33 | bytes32 sender, 34 | bytes calldata messageBody 35 | ) external returns (bool) { 36 | require(msg.sender == destinationMessenger, "CCTPReceiver/invalid-sender"); 37 | require(sourceDomainId == sourceDomain, "CCTPReceiver/invalid-sourceDomain"); 38 | require(sender == sourceAuthority, "CCTPReceiver/invalid-sourceAuthority"); 39 | 40 | target.functionCall(messageBody); 41 | 42 | return true; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/forwarders/AMBForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | interface IArbitraryMessagingBridge { 5 | function requireToPassMessage(address _contract, bytes memory _data, uint256 _gas) external returns (bytes32); 6 | } 7 | 8 | library AMBForwarder { 9 | 10 | address constant internal GNOSIS_AMB_ETHEREUM = 0x4C36d2919e407f0Cc2Ee3c993ccF8ac26d9CE64e; 11 | address constant internal GNOSIS_AMB_GNOSIS_CHAIN = 0x75Df5AF045d91108662D8080fD1FEFAd6aA0bb59; 12 | 13 | function sendMessage( 14 | address amb, 15 | address target, 16 | bytes memory message, 17 | uint256 gasLimit 18 | ) internal { 19 | IArbitraryMessagingBridge(amb).requireToPassMessage( 20 | target, 21 | message, 22 | gasLimit 23 | ); 24 | } 25 | 26 | function sendMessageEthereumToGnosisChain( 27 | address target, 28 | bytes memory message, 29 | uint256 gasLimit 30 | ) internal { 31 | sendMessage( 32 | GNOSIS_AMB_ETHEREUM, 33 | target, 34 | message, 35 | gasLimit 36 | ); 37 | } 38 | 39 | function sendMessageGnosisChainToEthereum( 40 | address target, 41 | bytes memory message, 42 | uint256 gasLimit 43 | ) internal { 44 | sendMessage( 45 | GNOSIS_AMB_GNOSIS_CHAIN, 46 | target, 47 | message, 48 | gasLimit 49 | ); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/receivers/AMBReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { Address } from "openzeppelin-contracts/contracts/utils/Address.sol"; 5 | 6 | interface IArbitraryMessagingBridge { 7 | function messageSender() external view returns (address); 8 | function messageSourceChainId() external view returns (bytes32); 9 | } 10 | 11 | /** 12 | * @title AMBReceiver 13 | * @notice Receive messages to AMB-style chain. 14 | */ 15 | contract AMBReceiver { 16 | 17 | using Address for address; 18 | 19 | address public immutable amb; 20 | bytes32 public immutable sourceChainId; 21 | address public immutable sourceAuthority; 22 | address public immutable target; 23 | 24 | constructor( 25 | address _amb, 26 | bytes32 _sourceChainId, 27 | address _sourceAuthority, 28 | address _target 29 | ) { 30 | amb = _amb; 31 | sourceChainId = _sourceChainId; 32 | sourceAuthority = _sourceAuthority; 33 | target = _target; 34 | } 35 | 36 | fallback(bytes calldata message) external returns (bytes memory) { 37 | require(msg.sender == amb, "AMBReceiver/invalid-sender"); 38 | require(IArbitraryMessagingBridge(amb).messageSourceChainId() == sourceChainId, "AMBReceiver/invalid-sourceChainId"); 39 | require(IArbitraryMessagingBridge(amb).messageSender() == sourceAuthority, "AMBReceiver/invalid-sourceAuthority"); 40 | 41 | return target.functionCall(message); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # xchain-helpers 2 | 3 | This repository has three tools for use with multi-chain development. Domains refer to blockchains which are connected by bridges. Domains may have multiple bridges connecting them, for example both the Optimism Native Bridge and Circle CCTP connect Ethereum and Optimism domains. 4 | 5 | ## Forwarders 6 | 7 | These libraries provide standardized syntax for sending a message to a bridge. 8 | 9 | ## Receivers 10 | 11 | ![xchain-helpers](.assets/xchain-helpers.png) 12 | 13 | The most common pattern is to have an authorized contract forward a message to another "business logic" contract to abstract away bridge dependencies. Receivers are contracts which perform this generic translation - decoding the bridge-specific message and forwarding to another `target` contract. The `target` contract should have logic to restrict who can call it and permission this to one or more bridge receivers. 14 | 15 | Most receivers implement a `fallback()` function which after validating that the call came from an authorized party on the other side of the bridge will forward the call to the `target` contract with the same function signature. This separation of concerns makes it easy for the receiver contract to focus on validating the bridge message, and the business logic `target` contract can validate the `msg.sender` comes from the receiver which validates the whole process. This ensures no chain-specific code is required for the business logic contract. 16 | 17 | ## E2E Testing Infrastructure 18 | 19 | Provides tooling to record messages sent to supported bridges and relay them on the other side simulating a real message going across. 20 | -------------------------------------------------------------------------------- /src/receivers/LZReceiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { Address } from "openzeppelin-contracts/contracts/utils/Address.sol"; 5 | import { Ownable } from "openzeppelin-contracts/contracts/access/Ownable.sol"; 6 | 7 | import { OAppReceiver, Origin, OAppCore } from "layerzerolabs/oapp-evm/contracts/oapp/OApp.sol"; 8 | 9 | /** 10 | * @title LZReceiver 11 | * @notice Receive messages from LayerZero-style bridge. 12 | */ 13 | contract LZReceiver is OAppReceiver { 14 | 15 | using Address for address; 16 | 17 | address public immutable target; 18 | 19 | uint32 public immutable srcEid; 20 | 21 | bytes32 public immutable sourceAuthority; 22 | 23 | constructor( 24 | address _destinationEndpoint, 25 | uint32 _srcEid, 26 | bytes32 _sourceAuthority, 27 | address _target, 28 | address _delegate, 29 | address _owner 30 | ) OAppCore(_destinationEndpoint, _delegate) Ownable(_owner) { 31 | target = _target; 32 | sourceAuthority = _sourceAuthority; 33 | srcEid = _srcEid; 34 | 35 | _setPeer(_srcEid, _sourceAuthority); 36 | } 37 | 38 | function _lzReceive( 39 | Origin calldata _origin, 40 | bytes32, // _guid 41 | bytes calldata _message, 42 | address, // _executor 43 | bytes calldata // _extraData 44 | ) internal override { 45 | require(_origin.srcEid == srcEid, "LZReceiver/invalid-srcEid"); 46 | require(_origin.sender == sourceAuthority, "LZReceiver/invalid-sourceAuthority"); 47 | 48 | target.functionCallWithValue(_message, msg.value); 49 | } 50 | 51 | function allowInitializePath(Origin calldata origin) public view override returns (bool) { 52 | return super.allowInitializePath(origin) 53 | && origin.srcEid == srcEid 54 | && origin.sender == sourceAuthority; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/testing/Domain.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { StdChains } from "forge-std/StdChains.sol"; 5 | import { Vm } from "forge-std/Vm.sol"; 6 | 7 | struct Domain { 8 | StdChains.Chain chain; 9 | uint256 forkId; 10 | } 11 | 12 | library DomainHelpers { 13 | 14 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 15 | 16 | function createFork(StdChains.Chain memory chain, uint256 blockNumber) internal returns (Domain memory domain) { 17 | domain = Domain({ 18 | chain: chain, 19 | forkId: vm.createFork(chain.rpcUrl, blockNumber) 20 | }); 21 | } 22 | 23 | function createFork(StdChains.Chain memory chain) internal returns (Domain memory domain) { 24 | domain = Domain({ 25 | chain: chain, 26 | forkId: vm.createFork(chain.rpcUrl) 27 | }); 28 | } 29 | 30 | function createSelectFork(StdChains.Chain memory chain, uint256 blockNumber) internal returns (Domain memory domain) { 31 | domain = Domain({ 32 | chain: chain, 33 | forkId: vm.createSelectFork(chain.rpcUrl, blockNumber) 34 | }); 35 | _assertExpectedRpc(chain); 36 | } 37 | 38 | function createSelectFork(StdChains.Chain memory chain) internal returns (Domain memory domain) { 39 | domain = Domain({ 40 | chain: chain, 41 | forkId: vm.createSelectFork(chain.rpcUrl) 42 | }); 43 | _assertExpectedRpc(chain); 44 | } 45 | 46 | function selectFork(Domain memory domain) internal { 47 | vm.selectFork(domain.forkId); 48 | _assertExpectedRpc(domain.chain); 49 | } 50 | 51 | function rollFork(Domain memory domain, uint256 blockNumber) internal { 52 | vm.rollFork(domain.forkId, blockNumber); 53 | } 54 | 55 | function _assertExpectedRpc(StdChains.Chain memory chain) private view { 56 | require(block.chainid == chain.chainId, string(abi.encodePacked(chain.chainAlias, " is pointing to the wrong RPC endpoint '", chain.rpcUrl, "'"))); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/forwarders/ArbitrumForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | interface ICrossDomainArbitrum { 5 | function createRetryableTicket( 6 | address to, 7 | uint256 l2CallValue, 8 | uint256 maxSubmissionCost, 9 | address excessFeeRefundAddress, 10 | address callValueRefundAddress, 11 | uint256 gasLimit, 12 | uint256 maxFeePerGas, 13 | bytes calldata data 14 | ) external payable returns (uint256); 15 | function calculateRetryableSubmissionFee(uint256 dataLength, uint256 baseFee) external view returns (uint256); 16 | } 17 | 18 | interface IArbSys { 19 | function sendTxToL1(address target, bytes calldata message) external; 20 | } 21 | 22 | library ArbitrumForwarder { 23 | 24 | address constant internal L1_CROSS_DOMAIN_ARBITRUM_ONE = 0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f; 25 | address constant internal L1_CROSS_DOMAIN_ARBITRUM_NOVA = 0xc4448b71118c9071Bcb9734A0EAc55D18A153949; 26 | address constant internal L2_CROSS_DOMAIN = 0x0000000000000000000000000000000000000064; 27 | 28 | function sendMessageL1toL2( 29 | address l1CrossDomain, 30 | address target, 31 | bytes memory message, 32 | uint256 gasLimit, 33 | uint256 maxFeePerGas, 34 | uint256 baseFee 35 | ) internal { 36 | uint256 maxSubmission = ICrossDomainArbitrum(l1CrossDomain).calculateRetryableSubmissionFee(message.length, baseFee); 37 | uint256 maxRedemption = gasLimit * maxFeePerGas; 38 | ICrossDomainArbitrum(l1CrossDomain).createRetryableTicket{value: maxSubmission + maxRedemption}( 39 | target, 40 | 0, // we always assume that l2CallValue = 0 41 | maxSubmission, 42 | address(0), // burn the excess gas 43 | address(0), // burn the excess gas 44 | gasLimit, 45 | maxFeePerGas, 46 | message 47 | ); 48 | } 49 | 50 | function sendMessageL2toL1( 51 | address target, 52 | bytes memory message 53 | ) internal { 54 | IArbSys(L2_CROSS_DOMAIN).sendTxToL1( 55 | target, 56 | message 57 | ); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /test/ArbitrumReceiver.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { TargetContractMock } from "test/mocks/TargetContractMock.sol"; 7 | 8 | import { ArbitrumReceiver } from "src/receivers/ArbitrumReceiver.sol"; 9 | 10 | contract ArbitrumReceiverTest is Test { 11 | 12 | TargetContractMock target; 13 | 14 | ArbitrumReceiver receiver; 15 | 16 | address sourceAuthority = makeAddr("sourceAuthority"); 17 | address sourceAuthorityWithOffset; 18 | address randomAddress = makeAddr("randomAddress"); 19 | 20 | function setUp() public { 21 | target = new TargetContractMock(); 22 | 23 | receiver = new ArbitrumReceiver( 24 | sourceAuthority, 25 | address(target) 26 | ); 27 | unchecked { 28 | sourceAuthorityWithOffset = address(uint160(sourceAuthority) + uint160(0x1111000000000000000000000000000000001111)); 29 | } 30 | } 31 | 32 | function test_constructor() public { 33 | receiver = new ArbitrumReceiver( 34 | sourceAuthority, 35 | address(target) 36 | ); 37 | 38 | assertEq(receiver.l1Authority(), sourceAuthority); 39 | assertEq(receiver.target(), address(target)); 40 | } 41 | 42 | function test_forward_invalidL1Authority() public { 43 | vm.prank(randomAddress); 44 | vm.expectRevert("ArbitrumReceiver/invalid-l1Authority"); 45 | TargetContractMock(address(receiver)).increment(); 46 | } 47 | 48 | function test_forward_invalidL1AuthoritySourceAuthorityNoOffset() public { 49 | vm.prank(sourceAuthority); 50 | vm.expectRevert("ArbitrumReceiver/invalid-l1Authority"); 51 | TargetContractMock(address(receiver)).increment(); 52 | } 53 | 54 | function test_forward_success() public { 55 | assertEq(target.count(), 0); 56 | vm.prank(sourceAuthorityWithOffset); 57 | TargetContractMock(address(receiver)).increment(); 58 | assertEq(target.count(), 1); 59 | } 60 | 61 | function test_forward_revert() public { 62 | vm.prank(sourceAuthorityWithOffset); 63 | vm.expectRevert("TargetContract/error"); 64 | TargetContractMock(address(receiver)).revertFunc(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/forwarders/CCTPForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | interface IMessageTransmitter { 5 | function sendMessage( 6 | uint32 destinationDomain, 7 | bytes32 recipient, 8 | bytes calldata messageBody 9 | ) external; 10 | } 11 | 12 | library CCTPForwarder { 13 | 14 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_ETHEREUM = 0x0a992d191DEeC32aFe36203Ad87D7d289a738F81; 15 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_AVALANCHE = 0x8186359aF5F57FbB40c6b14A588d2A59C0C29880; 16 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_OPTIMISM = 0x4D41f22c5a0e5c74090899E5a8Fb597a8842b3e8; 17 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_ARBITRUM_ONE = 0xC30362313FBBA5cf9163F0bb16a0e01f01A896ca; 18 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_BASE = 0xAD09780d193884d503182aD4588450C416D6F9D4; 19 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_POLYGON_POS = 0xF3be9355363857F3e001be68856A2f96b4C39Ba9; 20 | address constant internal MESSAGE_TRANSMITTER_CIRCLE_UNICHAIN = 0x353bE9E2E38AB1D19104534e4edC21c643Df86f4; 21 | 22 | uint32 constant internal DOMAIN_ID_CIRCLE_ETHEREUM = 0; 23 | uint32 constant internal DOMAIN_ID_CIRCLE_AVALANCHE = 1; 24 | uint32 constant internal DOMAIN_ID_CIRCLE_OPTIMISM = 2; 25 | uint32 constant internal DOMAIN_ID_CIRCLE_ARBITRUM_ONE = 3; 26 | uint32 constant internal DOMAIN_ID_CIRCLE_NOBLE = 4; 27 | uint32 constant internal DOMAIN_ID_CIRCLE_SOLANA = 5; 28 | uint32 constant internal DOMAIN_ID_CIRCLE_BASE = 6; 29 | uint32 constant internal DOMAIN_ID_CIRCLE_POLYGON_POS = 7; 30 | uint32 constant internal DOMAIN_ID_CIRCLE_UNICHAIN = 10; 31 | 32 | function sendMessage( 33 | address messageTransmitter, 34 | uint32 destinationDomainId, 35 | bytes32 recipient, 36 | bytes memory messageBody 37 | ) internal { 38 | IMessageTransmitter(messageTransmitter).sendMessage( 39 | destinationDomainId, 40 | recipient, 41 | messageBody 42 | ); 43 | } 44 | 45 | function sendMessage( 46 | address messageTransmitter, 47 | uint32 destinationDomainId, 48 | address recipient, 49 | bytes memory messageBody 50 | ) internal { 51 | sendMessage( 52 | messageTransmitter, 53 | destinationDomainId, 54 | bytes32(uint256(uint160(recipient))), 55 | messageBody 56 | ); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /test/OptimismReceiver.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { TargetContractMock } from "test/mocks/TargetContractMock.sol"; 7 | 8 | import { OptimismReceiver } from "src/receivers/OptimismReceiver.sol"; 9 | 10 | contract OptimismMessengerMock { 11 | 12 | address public xDomainMessageSender; 13 | 14 | function __setSender(address _xDomainMessageSender) public { 15 | xDomainMessageSender = _xDomainMessageSender; 16 | } 17 | 18 | } 19 | 20 | contract OptimismReceiverTest is Test { 21 | 22 | OptimismMessengerMock l2CrossDomain; 23 | TargetContractMock target; 24 | 25 | OptimismReceiver receiver; 26 | 27 | address l2CrossDomainAddr = 0x4200000000000000000000000000000000000007; 28 | 29 | address sourceAuthority = makeAddr("sourceAuthority"); 30 | address randomAddress = makeAddr("randomAddress"); 31 | 32 | function setUp() public { 33 | // Set the code at the particular address 34 | l2CrossDomain = new OptimismMessengerMock(); 35 | vm.etch(l2CrossDomainAddr, address(l2CrossDomain).code); 36 | l2CrossDomain = OptimismMessengerMock(l2CrossDomainAddr); 37 | l2CrossDomain.__setSender(sourceAuthority); 38 | 39 | target = new TargetContractMock(); 40 | 41 | receiver = new OptimismReceiver( 42 | sourceAuthority, 43 | address(target) 44 | ); 45 | } 46 | 47 | function test_constructor() public { 48 | receiver = new OptimismReceiver( 49 | sourceAuthority, 50 | address(target) 51 | ); 52 | 53 | assertEq(receiver.l1Authority(), sourceAuthority); 54 | assertEq(receiver.target(), address(target)); 55 | } 56 | 57 | function test_forward_invalidSender() public { 58 | vm.prank(randomAddress); 59 | vm.expectRevert("OptimismReceiver/invalid-sender"); 60 | TargetContractMock(address(receiver)).increment(); 61 | } 62 | 63 | function test_forward_invalidL1Authority() public { 64 | l2CrossDomain.__setSender(randomAddress); 65 | 66 | vm.prank(address(l2CrossDomain)); 67 | vm.expectRevert("OptimismReceiver/invalid-l1Authority"); 68 | TargetContractMock(address(receiver)).increment(); 69 | } 70 | 71 | function test_forward_success() public { 72 | assertEq(target.count(), 0); 73 | vm.prank(address(l2CrossDomain)); 74 | TargetContractMock(address(receiver)).increment(); 75 | assertEq(target.count(), 1); 76 | } 77 | 78 | function test_forward_revert() public { 79 | vm.prank(address(l2CrossDomain)); 80 | vm.expectRevert("TargetContract/error"); 81 | TargetContractMock(address(receiver)).revertFunc(); 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /test/ArbitrumIntegration.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "./IntegrationBase.t.sol"; 5 | 6 | import { ArbitrumBridgeTesting } from "src/testing/bridges/ArbitrumBridgeTesting.sol"; 7 | import { ArbitrumForwarder } from "src/forwarders/ArbitrumForwarder.sol"; 8 | import { ArbitrumReceiver } from "src/receivers/ArbitrumReceiver.sol"; 9 | 10 | contract ArbitrumIntegrationTest is IntegrationBaseTest { 11 | 12 | using ArbitrumBridgeTesting for *; 13 | using DomainHelpers for *; 14 | 15 | function initBaseContracts(Domain memory _destination) internal override { 16 | super.initBaseContracts(_destination); 17 | 18 | // Needed for arbitrum cross-chain messages 19 | deal(sourceAuthority, 100 ether); 20 | deal(randomAddress, 100 ether); 21 | } 22 | 23 | // Use Arbitrum One for failure test as the code logic is the same 24 | 25 | function test_invalidSourceAuthority() public { 26 | initBaseContracts(getChain("arbitrum_one").createFork()); 27 | 28 | destination.selectFork(); 29 | vm.expectRevert("ArbitrumReceiver/invalid-l1Authority"); 30 | vm.prank(randomAddress); 31 | MessageOrdering(destinationReceiver).push(1); 32 | } 33 | 34 | function test_arbitrumOne() public { 35 | runCrossChainTests(getChain("arbitrum_one").createFork()); 36 | } 37 | 38 | function test_arbitrumNova() public { 39 | runCrossChainTests(getChain("arbitrum_nova").createFork()); 40 | } 41 | 42 | function initSourceReceiver() internal override pure returns (address) { 43 | return address(0); 44 | } 45 | 46 | function initDestinationReceiver() internal override returns (address) { 47 | return address(new ArbitrumReceiver(sourceAuthority, address(moDestination))); 48 | } 49 | 50 | function initBridgeTesting() internal override returns (Bridge memory) { 51 | return ArbitrumBridgeTesting.createNativeBridge(source, destination); 52 | } 53 | 54 | function queueSourceToDestination(bytes memory message) internal override { 55 | ArbitrumForwarder.sendMessageL1toL2( 56 | bridge.sourceCrossChainMessenger, 57 | destinationReceiver, 58 | message, 59 | 100000, 60 | 1 gwei, 61 | block.basefee + 10 gwei 62 | ); 63 | } 64 | 65 | function queueDestinationToSource(bytes memory message) internal override { 66 | ArbitrumForwarder.sendMessageL2toL1( 67 | address(moSource), // No receiver so send directly to the message ordering contract 68 | message 69 | ); 70 | } 71 | 72 | function relaySourceToDestination() internal override { 73 | bridge.relayMessagesToDestination(true); 74 | } 75 | 76 | function relayDestinationToSource() internal override { 77 | bridge.relayMessagesToSource(true); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /test/AMBReceiver.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { TargetContractMock } from "test/mocks/TargetContractMock.sol"; 7 | 8 | import { AMBReceiver } from "src/receivers/AMBReceiver.sol"; 9 | 10 | contract AMBMock { 11 | 12 | bytes32 public messageSourceChainId; 13 | address public messageSender; 14 | 15 | constructor(bytes32 _messageSourceChainId, address _messageSender) { 16 | messageSourceChainId = _messageSourceChainId; 17 | messageSender = _messageSender; 18 | } 19 | 20 | function __setSourceChainId(bytes32 _messageSourceChainId) public { 21 | messageSourceChainId = _messageSourceChainId; 22 | } 23 | 24 | function __setSender(address _messageSender) public { 25 | messageSender = _messageSender; 26 | } 27 | 28 | } 29 | 30 | contract AMBReceiverTest is Test { 31 | 32 | AMBMock amb; 33 | TargetContractMock target; 34 | 35 | AMBReceiver receiver; 36 | 37 | bytes32 sourceChainId = bytes32(uint256(1)); 38 | address sourceAuthority = makeAddr("sourceAuthority"); 39 | address randomAddress = makeAddr("randomAddress"); 40 | 41 | function setUp() public { 42 | amb = new AMBMock(sourceChainId, sourceAuthority); 43 | target = new TargetContractMock(); 44 | 45 | receiver = new AMBReceiver( 46 | address(amb), 47 | sourceChainId, 48 | sourceAuthority, 49 | address(target) 50 | ); 51 | } 52 | 53 | function test_constructor() public { 54 | receiver = new AMBReceiver( 55 | address(amb), 56 | sourceChainId, 57 | sourceAuthority, 58 | address(target) 59 | ); 60 | 61 | assertEq(receiver.amb(), address(amb)); 62 | assertEq(receiver.sourceChainId(), sourceChainId); 63 | assertEq(receiver.sourceAuthority(), sourceAuthority); 64 | assertEq(receiver.target(), address(target)); 65 | } 66 | 67 | function test_forward_invalidSender() public { 68 | vm.prank(randomAddress); 69 | vm.expectRevert("AMBReceiver/invalid-sender"); 70 | TargetContractMock(address(receiver)).increment(); 71 | } 72 | 73 | function test_forward_invalidSourceChainId() public { 74 | amb.__setSourceChainId(bytes32(uint256(2))); 75 | 76 | vm.prank(address(amb)); 77 | vm.expectRevert("AMBReceiver/invalid-sourceChainId"); 78 | TargetContractMock(address(receiver)).increment(); 79 | } 80 | 81 | function test_forward_invalidSourceAuthority() public { 82 | amb.__setSender(randomAddress); 83 | 84 | vm.prank(address(amb)); 85 | vm.expectRevert("AMBReceiver/invalid-sourceAuthority"); 86 | TargetContractMock(address(receiver)).increment(); 87 | } 88 | 89 | function test_forward_success() public { 90 | assertEq(target.count(), 0); 91 | vm.prank(address(amb)); 92 | TargetContractMock(address(receiver)).increment(); 93 | assertEq(target.count(), 1); 94 | } 95 | 96 | function test_forward_revert() public { 97 | vm.prank(address(amb)); 98 | vm.expectRevert("TargetContract/error"); 99 | TargetContractMock(address(receiver)).revertFunc(); 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /test/CCTPReceiver.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { TargetContractMock } from "test/mocks/TargetContractMock.sol"; 7 | 8 | import { CCTPReceiver } from "src/receivers/CCTPReceiver.sol"; 9 | 10 | contract CCTPReceiverTest is Test { 11 | 12 | TargetContractMock target; 13 | 14 | CCTPReceiver receiver; 15 | 16 | address destinationMessenger = makeAddr("destinationMessenger"); 17 | uint32 sourceDomainId = 1; 18 | bytes32 sourceAuthority = bytes32(uint256(uint160(makeAddr("sourceAuthority")))); 19 | address randomAddress = makeAddr("randomAddress"); 20 | 21 | function setUp() public { 22 | target = new TargetContractMock(); 23 | 24 | receiver = new CCTPReceiver( 25 | destinationMessenger, 26 | sourceDomainId, 27 | sourceAuthority, 28 | address(target) 29 | ); 30 | } 31 | 32 | function test_constructor() public { 33 | receiver = new CCTPReceiver( 34 | destinationMessenger, 35 | sourceDomainId, 36 | sourceAuthority, 37 | address(target) 38 | ); 39 | 40 | assertEq(receiver.destinationMessenger(), destinationMessenger); 41 | assertEq(receiver.sourceDomainId(), sourceDomainId); 42 | assertEq(receiver.sourceAuthority(), sourceAuthority); 43 | assertEq(receiver.target(), address(target)); 44 | } 45 | 46 | function test_handleReceiveMessage_invalidSender() public { 47 | vm.prank(randomAddress); 48 | vm.expectRevert("CCTPReceiver/invalid-sender"); 49 | receiver.handleReceiveMessage( 50 | sourceDomainId, 51 | sourceAuthority, 52 | abi.encodeCall(TargetContractMock.increment, ()) 53 | ); 54 | } 55 | 56 | function test_handleReceiveMessage_invalidSourceChainId() public { 57 | vm.prank(destinationMessenger); 58 | vm.expectRevert("CCTPReceiver/invalid-sourceDomain"); 59 | receiver.handleReceiveMessage( 60 | 2, 61 | sourceAuthority, 62 | abi.encodeCall(TargetContractMock.increment, ()) 63 | ); 64 | } 65 | 66 | function test_handleReceiveMessage_invalidSourceAuthority() public { 67 | vm.prank(destinationMessenger); 68 | vm.expectRevert("CCTPReceiver/invalid-sourceAuthority"); 69 | receiver.handleReceiveMessage( 70 | sourceDomainId, 71 | bytes32(uint256(uint160(randomAddress))), 72 | abi.encodeCall(TargetContractMock.increment, ()) 73 | ); 74 | } 75 | 76 | function test_handleReceiveMessage_success() public { 77 | assertEq(target.count(), 0); 78 | vm.prank(destinationMessenger); 79 | bool result = receiver.handleReceiveMessage( 80 | sourceDomainId, 81 | sourceAuthority, 82 | abi.encodeCall(TargetContractMock.increment, ()) 83 | ); 84 | assertEq(result, true); 85 | assertEq(target.count(), 1); 86 | } 87 | 88 | function test_handleReceiveMessage_revert() public { 89 | vm.prank(destinationMessenger); 90 | vm.expectRevert("TargetContract/error"); 91 | receiver.handleReceiveMessage( 92 | sourceDomainId, 93 | sourceAuthority, 94 | abi.encodeCall(TargetContractMock.revertFunc, ()) 95 | ); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/forwarders/LZForwarder.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity ^0.8.0; 3 | 4 | import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; 5 | import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; 6 | 7 | struct MessagingParams { 8 | uint32 dstEid; 9 | bytes32 receiver; 10 | bytes message; 11 | bytes options; 12 | bool payInLzToken; 13 | } 14 | 15 | struct MessagingReceipt { 16 | bytes32 guid; 17 | uint64 nonce; 18 | MessagingFee fee; 19 | } 20 | 21 | struct MessagingFee { 22 | uint256 nativeFee; 23 | uint256 lzTokenFee; 24 | } 25 | 26 | interface ILayerZeroEndpointV2 { 27 | function lzToken() external view returns (address); 28 | function send( 29 | MessagingParams calldata _params, 30 | address _refundAddress 31 | ) external payable returns (MessagingReceipt memory); 32 | function setLzToken(address _lzToken) external; 33 | function quote( 34 | MessagingParams calldata _params, 35 | address _sender 36 | ) external view returns (MessagingFee memory); 37 | } 38 | 39 | library LZForwarder { 40 | 41 | error LzTokenUnavailable(); 42 | 43 | uint32 public constant ENDPOINT_ID_AVALANCHE = 30106; 44 | uint32 public constant ENDPOINT_ID_BASE = 30184; 45 | uint32 public constant ENDPOINT_ID_BNB = 30102; 46 | uint32 public constant ENDPOINT_ID_ETHEREUM = 30101; 47 | 48 | address public constant ENDPOINT_AVALANCHE = 0x1a44076050125825900e736c501f859c50fE728c; 49 | address public constant ENDPOINT_BASE = 0x1a44076050125825900e736c501f859c50fE728c; 50 | address public constant ENDPOINT_BNB = 0x1a44076050125825900e736c501f859c50fE728c; 51 | address public constant ENDPOINT_ETHEREUM = 0x1a44076050125825900e736c501f859c50fE728c; 52 | 53 | address public constant RECEIVE_LIBRARY_AVALANCHE = 0xbf3521d309642FA9B1c91A08609505BA09752c61; 54 | address public constant RECEIVE_LIBRARY_BASE = 0xc70AB6f32772f59fBfc23889Caf4Ba3376C84bAf; 55 | address public constant RECEIVE_LIBRARY_BNB = 0xB217266c3A98C8B2709Ee26836C98cf12f6cCEC1; 56 | address public constant RECEIVE_LIBRARY_ETHEREUM = 0xc02Ab410f0734EFa3F14628780e6e695156024C2; 57 | 58 | function sendMessage( 59 | uint32 _dstEid, 60 | bytes32 _receiver, 61 | ILayerZeroEndpointV2 endpoint, 62 | bytes memory _message, 63 | bytes memory _options, 64 | address _refundAddress, 65 | bool _payInLzToken 66 | ) internal { 67 | MessagingParams memory params = MessagingParams({ 68 | dstEid: _dstEid, 69 | receiver: _receiver, 70 | message: _message, 71 | options: _options, 72 | payInLzToken: _payInLzToken 73 | }); 74 | 75 | MessagingFee memory fee = endpoint.quote(params, address(this)); 76 | if (fee.lzTokenFee > 0) _payLzToken(endpoint, fee.lzTokenFee); 77 | 78 | endpoint.send{ value: fee.nativeFee }(params, _refundAddress); 79 | } 80 | 81 | function _payLzToken(ILayerZeroEndpointV2 endpoint, uint256 _lzTokenFee) internal { 82 | // @dev Cannot cache the token because it is not immutable in the endpoint. 83 | address lzToken = endpoint.lzToken(); 84 | if (lzToken == address(0)) revert LzTokenUnavailable(); 85 | 86 | // Pay LZ token fee by sending tokens to the endpoint. 87 | SafeERC20.safeTransfer(IERC20(lzToken), address(endpoint), _lzTokenFee); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /test/OptimismIntegration.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "./IntegrationBase.t.sol"; 5 | 6 | import { OptimismBridgeTesting } from "src/testing/bridges/OptimismBridgeTesting.sol"; 7 | import { OptimismForwarder } from "src/forwarders/OptimismForwarder.sol"; 8 | import { OptimismReceiver } from "src/receivers/OptimismReceiver.sol"; 9 | 10 | contract OptimismIntegrationTest is IntegrationBaseTest { 11 | 12 | using OptimismBridgeTesting for *; 13 | using DomainHelpers for *; 14 | 15 | event FailedRelayedMessage(bytes32); 16 | 17 | // Use Optimism mainnet for failure test as the code logic is the same 18 | 19 | function test_invalidSender() public { 20 | initBaseContracts(getChain("optimism").createFork()); 21 | 22 | destination.selectFork(); 23 | 24 | vm.prank(randomAddress); 25 | vm.expectRevert("OptimismReceiver/invalid-sender"); 26 | MessageOrdering(destinationReceiver).push(1); 27 | } 28 | 29 | function test_invalidSourceAuthority() public { 30 | initBaseContracts(getChain("optimism").createFork()); 31 | 32 | vm.startPrank(randomAddress); 33 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (1))); 34 | vm.stopPrank(); 35 | 36 | // The revert is caught so it doesn't propagate 37 | // Just look at the no change to verify it didn't go through 38 | relaySourceToDestination(); 39 | assertEq(moDestination.length(), 0); 40 | } 41 | 42 | function test_optimism() public { 43 | runCrossChainTests(getChain("optimism").createFork()); 44 | } 45 | 46 | function test_base() public { 47 | runCrossChainTests(getChain("base").createFork()); 48 | } 49 | 50 | function test_world_chain() public { 51 | setChain("world_chain", ChainData({ 52 | name: "World Chain", 53 | rpcUrl: vm.envString("WORLD_CHAIN_RPC_URL"), 54 | chainId: 480 55 | })); 56 | runCrossChainTests(getChain("world_chain").createFork()); 57 | } 58 | 59 | function test_unichain() public { 60 | setChain("unichain", ChainData({ 61 | name: "Unichain", 62 | rpcUrl: vm.envString("UNICHAIN_RPC_URL"), 63 | chainId: 130 64 | })); 65 | runCrossChainTests(getChain("unichain").createFork()); 66 | } 67 | 68 | function initSourceReceiver() internal override pure returns (address) { 69 | return address(0); 70 | } 71 | 72 | function initDestinationReceiver() internal override returns (address) { 73 | return address(new OptimismReceiver(sourceAuthority, address(moDestination))); 74 | } 75 | 76 | function initBridgeTesting() internal override returns (Bridge memory) { 77 | return OptimismBridgeTesting.createNativeBridge(source, destination); 78 | } 79 | 80 | function queueSourceToDestination(bytes memory message) internal override { 81 | OptimismForwarder.sendMessageL1toL2( 82 | bridge.sourceCrossChainMessenger, 83 | destinationReceiver, 84 | message, 85 | 100000 86 | ); 87 | } 88 | 89 | function queueDestinationToSource(bytes memory message) internal override { 90 | OptimismForwarder.sendMessageL2toL1( 91 | address(moSource), // No receiver so send directly to the message ordering contract 92 | message, 93 | 100000 94 | ); 95 | } 96 | 97 | function relaySourceToDestination() internal override { 98 | bridge.relayMessagesToDestination(true); 99 | } 100 | 101 | function relayDestinationToSource() internal override { 102 | bridge.relayMessagesToSource(true); 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /test/GnosisIntegration.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "./IntegrationBase.t.sol"; 5 | 6 | import { AMBBridgeTesting } from "src/testing/bridges/AMBBridgeTesting.sol"; 7 | import { AMBForwarder } from "src/forwarders/AMBForwarder.sol"; 8 | import { AMBReceiver } from "src/receivers/AMBReceiver.sol"; 9 | 10 | contract GnosisIntegrationTest is IntegrationBaseTest { 11 | 12 | using AMBBridgeTesting for *; 13 | using DomainHelpers for *; 14 | 15 | function test_invalidSourceAuthority() public { 16 | initBaseContracts(getChain("gnosis_chain").createFork()); 17 | 18 | vm.startPrank(randomAddress); 19 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (1))); 20 | vm.stopPrank(); 21 | 22 | // The revert is caught so it doesn't propagate 23 | // Just look at the no change to verify it didn't go through 24 | relaySourceToDestination(); 25 | assertEq(moDestination.length(), 0); 26 | } 27 | 28 | function test_invalidSender() public { 29 | initBaseContracts(getChain("gnosis_chain").createFork()); 30 | 31 | destination.selectFork(); 32 | 33 | vm.prank(randomAddress); 34 | vm.expectRevert("AMBReceiver/invalid-sender"); 35 | MessageOrdering(destinationReceiver).push(1); 36 | } 37 | 38 | function test_invalidSourceChainId() public { 39 | initBaseContracts(getChain("gnosis_chain").createFork()); 40 | 41 | destination.selectFork(); 42 | destinationReceiver = address(new AMBReceiver( 43 | bridge.destinationCrossChainMessenger, 44 | bytes32(uint256(2)), // Random chain id (not Ethereum) 45 | sourceAuthority, 46 | address(moDestination) 47 | )); 48 | 49 | source.selectFork(); 50 | vm.startPrank(sourceAuthority); 51 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (1))); 52 | vm.stopPrank(); 53 | 54 | // The revert is caught so it doesn't propagate 55 | // Just look at the no change to verify it didn't go through 56 | relaySourceToDestination(); 57 | assertEq(moDestination.length(), 0); 58 | } 59 | 60 | function test_gnosisChain() public { 61 | runCrossChainTests(getChain('gnosis_chain').createFork()); 62 | } 63 | 64 | function initSourceReceiver() internal override returns (address) { 65 | return address(new AMBReceiver(bridge.sourceCrossChainMessenger, bytes32(uint256(100)), destinationAuthority, address(moSource))); 66 | } 67 | 68 | function initDestinationReceiver() internal override returns (address) { 69 | return address(new AMBReceiver(bridge.destinationCrossChainMessenger, bytes32(uint256(1)), sourceAuthority, address(moDestination))); 70 | } 71 | 72 | function initBridgeTesting() internal override returns (Bridge memory) { 73 | return AMBBridgeTesting.createGnosisBridge(source, destination); 74 | } 75 | 76 | function queueSourceToDestination(bytes memory message) internal override { 77 | AMBForwarder.sendMessageEthereumToGnosisChain( 78 | destinationReceiver, 79 | message, 80 | 100000 81 | ); 82 | } 83 | 84 | function queueDestinationToSource(bytes memory message) internal override { 85 | AMBForwarder.sendMessageGnosisChainToEthereum( 86 | sourceReceiver, 87 | message, 88 | 100000 89 | ); 90 | } 91 | 92 | function relaySourceToDestination() internal override { 93 | bridge.relayMessagesToDestination(true); 94 | } 95 | 96 | function relayDestinationToSource() internal override { 97 | bridge.relayMessagesToSource(true); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | workflow_dispatch: 5 | pull_request: 6 | push: 7 | branches: 8 | - master 9 | 10 | env: 11 | FOUNDRY_PROFILE: ci 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Install Foundry 20 | uses: foundry-rs/foundry-toolchain@v1 21 | 22 | - name: Build contracts 23 | run: | 24 | forge --version 25 | forge build --sizes 26 | 27 | test: 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v3 31 | 32 | - name: Install Foundry 33 | uses: foundry-rs/foundry-toolchain@v1 34 | 35 | - name: Run tests 36 | env: 37 | MAINNET_RPC_URL: ${{secrets.MAINNET_RPC_URL}} 38 | OPTIMISM_RPC_URL: ${{secrets.OPTIMISM_RPC_URL}} 39 | ARBITRUM_ONE_RPC_URL: ${{secrets.ARBITRUM_ONE_RPC_URL}} 40 | ARBITRUM_NOVA_RPC_URL: ${{secrets.ARBITRUM_NOVA_RPC_URL}} 41 | GNOSIS_CHAIN_RPC_URL: ${{secrets.GNOSIS_CHAIN_RPC_URL}} 42 | BASE_RPC_URL: ${{secrets.BASE_RPC_URL}} 43 | POLYGON_RPC_URL: ${{secrets.POLYGON_RPC_URL}} 44 | WORLD_CHAIN_RPC_URL: ${{secrets.WORLD_CHAIN_RPC_URL}} 45 | UNICHAIN_RPC_URL: ${{secrets.UNICHAIN_RPC_URL}} 46 | run: FOUNDRY_PROFILE=ci forge test 47 | 48 | coverage: 49 | runs-on: ubuntu-latest 50 | steps: 51 | - uses: actions/checkout@v3 52 | 53 | - name: Install Foundry 54 | uses: foundry-rs/foundry-toolchain@v1 55 | 56 | - name: Run coverage 57 | env: 58 | MAINNET_RPC_URL: ${{secrets.MAINNET_RPC_URL}} 59 | OPTIMISM_RPC_URL: ${{secrets.OPTIMISM_RPC_URL}} 60 | ARBITRUM_ONE_RPC_URL: ${{secrets.ARBITRUM_ONE_RPC_URL}} 61 | ARBITRUM_NOVA_RPC_URL: ${{secrets.ARBITRUM_NOVA_RPC_URL}} 62 | GNOSIS_CHAIN_RPC_URL: ${{secrets.GNOSIS_CHAIN_RPC_URL}} 63 | BASE_RPC_URL: ${{secrets.BASE_RPC_URL}} 64 | POLYGON_RPC_URL: ${{secrets.POLYGON_RPC_URL}} 65 | WORLD_CHAIN_RPC_URL: ${{secrets.WORLD_CHAIN_RPC_URL}} 66 | UNICHAIN_RPC_URL: ${{secrets.UNICHAIN_RPC_URL}} 67 | run: forge coverage --report summary --report lcov 68 | 69 | # To ignore coverage for certain directories modify the paths in this step as needed. The 70 | # below default ignores coverage results for the test and script directories. Alternatively, 71 | # to include coverage in all directories, comment out this step. Note that because this 72 | # filtering applies to the lcov file, the summary table generated in the previous step will 73 | # still include all files and directories. 74 | # The `--rc lcov_branch_coverage=1` part keeps branch info in the filtered report, since lcov 75 | # defaults to removing branch info. 76 | - name: Filter directories 77 | run: | 78 | sudo apt update && sudo apt install -y lcov 79 | lcov --remove lcov.info 'test/*' 'src/testing/*' --output-file lcov.info --rc lcov_branch_coverage=1 80 | 81 | # This step posts a detailed coverage report as a comment and deletes previous comments on 82 | # each push. The below step is used to fail coverage if the specified coverage threshold is 83 | # not met. The below step can post a comment (when it's `github-token` is specified) but it's 84 | # not as useful, and this action cannot fail CI based on a minimum coverage threshold, which 85 | # is why we use both in this way. 86 | - name: Post coverage report 87 | if: github.event_name == 'pull_request' # This action fails when ran outside of a pull request. 88 | uses: romeovs/lcov-reporter-action@v0.3.1 89 | with: 90 | delete-old-comments: true 91 | lcov-file: ./lcov.info 92 | github-token: ${{ secrets.GITHUB_TOKEN }} # Adds a coverage summary comment to the PR. 93 | 94 | - name: Verify minimum coverage 95 | uses: zgosalvez/github-actions-report-lcov@v2 96 | with: 97 | coverage-files: ./lcov.info 98 | minimum-coverage: 90 # Set coverage threshold. 99 | -------------------------------------------------------------------------------- /test/IntegrationBase.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { Bridge } from "src/testing/Bridge.sol"; 7 | import { Domain, DomainHelpers } from "src/testing/Domain.sol"; 8 | 9 | contract MessageOrdering { 10 | 11 | address public receiver; 12 | uint256[] public messages; 13 | 14 | function push(uint256 messageId) external { 15 | // Null receiver means there is no code for this path so we ignore the check 16 | require(receiver == address(0) || msg.sender == receiver, "only-receiver"); 17 | 18 | messages.push(messageId); 19 | } 20 | 21 | function length() public view returns (uint256) { 22 | return messages.length; 23 | } 24 | 25 | function setReceiver(address _receiver) external { 26 | receiver = _receiver; 27 | } 28 | 29 | } 30 | 31 | abstract contract IntegrationBaseTest is Test { 32 | 33 | using DomainHelpers for *; 34 | 35 | address sourceAuthority = makeAddr("sourceAuthority"); 36 | address destinationAuthority = makeAddr("destinationAuthority"); 37 | address randomAddress = makeAddr("randomAddress"); 38 | 39 | Domain source; 40 | Domain destination; 41 | 42 | MessageOrdering moSource; 43 | MessageOrdering moDestination; 44 | 45 | address sourceReceiver; 46 | address destinationReceiver; 47 | 48 | Bridge bridge; 49 | 50 | function setUp() public virtual { 51 | source = getChain("mainnet").createFork(); 52 | } 53 | 54 | function initBaseContracts(Domain memory _destination) internal virtual { 55 | destination = _destination; 56 | 57 | bridge = initBridgeTesting(); 58 | 59 | source.selectFork(); 60 | moSource = new MessageOrdering(); 61 | sourceReceiver = initSourceReceiver(); 62 | moSource.setReceiver(sourceReceiver); 63 | 64 | destination.selectFork(); 65 | moDestination = new MessageOrdering(); 66 | destinationReceiver = initDestinationReceiver(); 67 | moDestination.setReceiver(destinationReceiver); 68 | 69 | // Default to source fork as it's an obvious default 70 | source.selectFork(); 71 | } 72 | 73 | function runCrossChainTests(Domain memory _destination) internal { 74 | initBaseContracts(_destination); 75 | 76 | destination.selectFork(); 77 | 78 | // Queue up some Destination -> Source messages 79 | vm.startPrank(destinationAuthority); 80 | queueDestinationToSource(abi.encodeCall(MessageOrdering.push, (3))); 81 | queueDestinationToSource(abi.encodeCall(MessageOrdering.push, (4))); 82 | vm.stopPrank(); 83 | 84 | assertEq(moDestination.length(), 0); 85 | 86 | // Do not relay right away 87 | source.selectFork(); 88 | 89 | // Queue up two more Source -> Destination messages 90 | vm.startPrank(sourceAuthority); 91 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (1))); 92 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (2))); 93 | vm.stopPrank(); 94 | 95 | assertEq(moSource.length(), 0); 96 | 97 | relaySourceToDestination(); 98 | 99 | assertEq(moDestination.length(), 2); 100 | assertEq(moDestination.messages(0), 1); 101 | assertEq(moDestination.messages(1), 2); 102 | 103 | relayDestinationToSource(); 104 | 105 | assertEq(moSource.length(), 2); 106 | assertEq(moSource.messages(0), 3); 107 | assertEq(moSource.messages(1), 4); 108 | 109 | // Do one more message both ways to ensure subsequent calls don't repeat already sent messages 110 | vm.startPrank(sourceAuthority); 111 | queueSourceToDestination(abi.encodeCall(MessageOrdering.push, (5))); 112 | vm.stopPrank(); 113 | 114 | relaySourceToDestination(); 115 | 116 | assertEq(moDestination.length(), 3); 117 | assertEq(moDestination.messages(2), 5); 118 | 119 | vm.startPrank(destinationAuthority); 120 | queueDestinationToSource(abi.encodeCall(MessageOrdering.push, (6))); 121 | vm.stopPrank(); 122 | 123 | relayDestinationToSource(); 124 | 125 | assertEq(moSource.length(), 3); 126 | assertEq(moSource.messages(2), 6); 127 | } 128 | 129 | function initSourceReceiver() internal virtual returns (address); 130 | function initDestinationReceiver() internal virtual returns (address); 131 | function initBridgeTesting() internal virtual returns (Bridge memory); 132 | function queueSourceToDestination(bytes memory message) internal virtual; 133 | function queueDestinationToSource(bytes memory message) internal virtual; 134 | function relaySourceToDestination() internal virtual; 135 | function relayDestinationToSource() internal virtual; 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/testing/bridges/AMBBridgeTesting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { Bridge, BridgeType } from "../Bridge.sol"; 7 | import { Domain, DomainHelpers } from "../Domain.sol"; 8 | import { RecordedLogs } from "../utils/RecordedLogs.sol"; 9 | 10 | interface IAMB { 11 | function validatorContract() external view returns (address); 12 | function executeSignatures(bytes memory, bytes memory) external; 13 | function executeAffirmation(bytes memory) external; 14 | } 15 | 16 | interface IValidatorContract { 17 | function validatorList() external view returns (address[] memory); 18 | function requiredSignatures() external view returns (uint256); 19 | } 20 | 21 | library AMBBridgeTesting { 22 | 23 | using DomainHelpers for *; 24 | using RecordedLogs for *; 25 | 26 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 27 | 28 | bytes32 private constant USER_REQUEST_FOR_AFFIRMATION_TOPIC = keccak256("UserRequestForAffirmation(bytes32,bytes)"); 29 | bytes32 private constant USER_REQUEST_FOR_SIGNATURE_TOPIC = keccak256("UserRequestForSignature(bytes32,bytes)"); 30 | 31 | function createGnosisBridge(Domain memory source, Domain memory destination) internal returns (Bridge memory bridge) { 32 | return init(Bridge({ 33 | bridgeType: BridgeType.AMB, 34 | source: source, 35 | destination: destination, 36 | sourceCrossChainMessenger: getGnosisMessengerFromChainAlias(source.chain.chainAlias), 37 | destinationCrossChainMessenger: getGnosisMessengerFromChainAlias(destination.chain.chainAlias), 38 | lastSourceLogIndex: 0, 39 | lastDestinationLogIndex: 0, 40 | extraData: "" 41 | })); 42 | } 43 | 44 | function getGnosisMessengerFromChainAlias(string memory chainAlias) internal pure returns (address) { 45 | bytes32 name = keccak256(bytes(chainAlias)); 46 | if (name == keccak256("mainnet")) { 47 | return 0x4C36d2919e407f0Cc2Ee3c993ccF8ac26d9CE64e; 48 | } else if (name == keccak256("gnosis_chain")) { 49 | return 0x75Df5AF045d91108662D8080fD1FEFAd6aA0bb59; 50 | } else { 51 | revert("Unsupported chain"); 52 | } 53 | } 54 | 55 | function init(Bridge memory bridge) internal returns (Bridge memory) { 56 | RecordedLogs.init(); 57 | 58 | // Set minimum required signatures to zero for both domains 59 | bridge.destination.selectFork(); 60 | vm.store( 61 | IAMB(bridge.destinationCrossChainMessenger).validatorContract(), 62 | 0x8a247e09a5673bd4d93a4e76d8fb9553523aa0d77f51f3d576e7421f5295b9bc, 63 | 0 64 | ); 65 | bridge.source.selectFork(); 66 | vm.store( 67 | IAMB(bridge.sourceCrossChainMessenger).validatorContract(), 68 | 0x8a247e09a5673bd4d93a4e76d8fb9553523aa0d77f51f3d576e7421f5295b9bc, 69 | 0 70 | ); 71 | 72 | return bridge; 73 | } 74 | 75 | function relayMessagesToDestination(Bridge storage bridge, bool switchToDestinationFork) internal { 76 | bridge.destination.selectFork(); 77 | 78 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(true, USER_REQUEST_FOR_AFFIRMATION_TOPIC, USER_REQUEST_FOR_SIGNATURE_TOPIC, bridge.sourceCrossChainMessenger); 79 | _relayAllMessages(logs, bridge.destinationCrossChainMessenger); 80 | 81 | if (!switchToDestinationFork) { 82 | bridge.source.selectFork(); 83 | } 84 | } 85 | 86 | function relayMessagesToSource(Bridge storage bridge, bool switchToSourceFork) internal { 87 | bridge.source.selectFork(); 88 | 89 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(false, USER_REQUEST_FOR_AFFIRMATION_TOPIC, USER_REQUEST_FOR_SIGNATURE_TOPIC, bridge.destinationCrossChainMessenger); 90 | _relayAllMessages(logs, bridge.sourceCrossChainMessenger); 91 | 92 | if (!switchToSourceFork) { 93 | bridge.destination.selectFork(); 94 | } 95 | } 96 | 97 | function _relayAllMessages(Vm.Log[] memory logs, address amb) private { 98 | for (uint256 i = 0; i < logs.length; i++) { 99 | Vm.Log memory log = logs[i]; 100 | bytes memory messageToRelay = abi.decode(log.data, (bytes)); 101 | if (log.topics[0] == USER_REQUEST_FOR_AFFIRMATION_TOPIC) { 102 | vm.prank(IValidatorContract(IAMB(amb).validatorContract()).validatorList()[0]); 103 | IAMB(amb).executeAffirmation(messageToRelay); 104 | } else if (log.topics[0] == USER_REQUEST_FOR_SIGNATURE_TOPIC) { 105 | IAMB(amb).executeSignatures(messageToRelay, abi.encodePacked(uint256(0))); 106 | } 107 | } 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /test/LZIntegrationWithLZToken.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { IERC20 } from "forge-std/interfaces/IERC20.sol"; 5 | 6 | import { OptionsBuilder } from "layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol"; 7 | 8 | import { LZBridgeTesting } from "src/testing/bridges/LZBridgeTesting.sol"; 9 | import { LZForwarder, ILayerZeroEndpointV2 } from "src/forwarders/LZForwarder.sol"; 10 | import { LZReceiver, Origin } from "src/receivers/LZReceiver.sol"; 11 | import { RecordedLogs } from "src/testing/utils/RecordedLogs.sol"; 12 | 13 | import "./IntegrationBase.t.sol"; 14 | 15 | interface ITreasury { 16 | function setLzTokenEnabled(bool _lzTokenEnabled) external; 17 | function setLzTokenFee(uint256 _lzTokenFee) external; 18 | } 19 | 20 | contract LZIntegrationTestWithLZToken is IntegrationBaseTest { 21 | 22 | using DomainHelpers for *; 23 | using LZBridgeTesting for *; 24 | using OptionsBuilder for bytes; 25 | 26 | uint32 sourceEndpointId = LZForwarder.ENDPOINT_ID_ETHEREUM; 27 | uint32 destinationEndpointId; 28 | 29 | address sourceEndpoint = LZForwarder.ENDPOINT_ETHEREUM; 30 | address destinationEndpoint; 31 | 32 | address lzToken = 0x6985884C4392D348587B19cb9eAAf157F13271cd; 33 | address lzOwner = 0xBe010A7e3686FdF65E93344ab664D065A0B02478; 34 | address treasury = 0x5ebB3f2feaA15271101a927869B3A56837e73056; 35 | 36 | Domain destination2; 37 | Bridge bridge2; 38 | 39 | function setUp() public override { 40 | super.setUp(); 41 | 42 | source.selectFork(); 43 | 44 | vm.startPrank(lzOwner); 45 | ILayerZeroEndpointV2(sourceEndpoint).setLzToken(lzToken); 46 | ITreasury(treasury).setLzTokenEnabled(true); 47 | ITreasury(treasury).setLzTokenFee(1e18); 48 | vm.stopPrank(); 49 | } 50 | 51 | function test_base() public { 52 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 53 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 54 | 55 | runCrossChainTests(getChain("base").createFork()); 56 | } 57 | 58 | function test_binance() public { 59 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BNB; 60 | destinationEndpoint = LZForwarder.ENDPOINT_BNB; 61 | 62 | runCrossChainTests(getChain("bnb_smart_chain").createFork()); 63 | } 64 | 65 | function initSourceReceiver() internal override returns (address) { 66 | return address(new LZReceiver( 67 | sourceEndpoint, 68 | destinationEndpointId, 69 | bytes32(uint256(uint160(destinationAuthority))), 70 | address(moSource), 71 | makeAddr("delegate"), 72 | makeAddr("owner") 73 | )); 74 | } 75 | 76 | function initDestinationReceiver() internal override returns (address) { 77 | return address(new LZReceiver( 78 | destinationEndpoint, 79 | sourceEndpointId, 80 | bytes32(uint256(uint160(sourceAuthority))), 81 | address(moDestination), 82 | makeAddr("delegate"), 83 | makeAddr("owner") 84 | )); 85 | } 86 | 87 | function initBridgeTesting() internal override returns (Bridge memory) { 88 | return LZBridgeTesting.createLZBridge(source, destination); 89 | } 90 | 91 | function queueSourceToDestination(bytes memory message) internal override { 92 | // Gas to queue message 93 | vm.deal(sourceAuthority, 1 ether); 94 | deal(lzToken, sourceAuthority, 1 ether); 95 | 96 | bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200_000, 0); 97 | 98 | assertEq(IERC20(lzToken).balanceOf(address(sourceAuthority)), 1 ether); 99 | assertEq(address(sourceAuthority).balance, 1 ether); 100 | 101 | LZForwarder.sendMessage( 102 | destinationEndpointId, 103 | bytes32(uint256(uint160(destinationReceiver))), 104 | ILayerZeroEndpointV2(bridge.sourceCrossChainMessenger), 105 | message, 106 | options, 107 | sourceAuthority, 108 | true 109 | ); 110 | 111 | // LZ token and ETH spent 112 | assertLt(IERC20(lzToken).balanceOf(address(sourceAuthority)), 1 ether); 113 | assertLt(address(sourceAuthority).balance, 1 ether); 114 | } 115 | 116 | function queueDestinationToSource(bytes memory message) internal override { 117 | vm.deal(destinationAuthority, 1 ether); // Gas to queue message 118 | 119 | bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200_000, 0); 120 | 121 | LZForwarder.sendMessage( 122 | sourceEndpointId, 123 | bytes32(uint256(uint160(sourceReceiver))), 124 | ILayerZeroEndpointV2(bridge.destinationCrossChainMessenger), 125 | message, 126 | options, 127 | destinationAuthority, 128 | false 129 | ); 130 | } 131 | 132 | function relaySourceToDestination() internal override { 133 | bridge.relayMessagesToDestination(true, sourceAuthority, destinationReceiver); 134 | } 135 | 136 | function relayDestinationToSource() internal override { 137 | bridge.relayMessagesToSource(true, destinationAuthority, sourceReceiver); 138 | } 139 | 140 | } 141 | -------------------------------------------------------------------------------- /test/RecordedLogs.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { CCTPForwarder } from "src/forwarders/CCTPForwarder.sol"; 7 | import { CCTPBridgeTesting } from "src/testing/bridges/CCTPBridgeTesting.sol"; 8 | import { Bridge } from "src/testing/Bridge.sol"; 9 | import { Domain, DomainHelpers } from "src/testing/Domain.sol"; 10 | import { RecordedLogs } from "src/testing/utils/RecordedLogs.sol"; 11 | 12 | contract DummyReceiver { 13 | 14 | bytes public data; 15 | 16 | function handleReceiveMessage( 17 | uint32, 18 | bytes32, 19 | bytes calldata _data 20 | ) external returns (bool) { 21 | data = _data; 22 | 23 | return true; 24 | } 25 | 26 | } 27 | 28 | contract LogGenerator { 29 | 30 | event DummyEvent(string label, uint256 num); 31 | 32 | string label; 33 | 34 | constructor(string memory _label) { 35 | label = _label; 36 | } 37 | 38 | function makeLogs(uint256 num) external { 39 | for (uint256 i = 0; i < num; i++) emit DummyEvent(label, i); 40 | } 41 | 42 | } 43 | 44 | contract RecordedLogsTest is Test { 45 | 46 | using DomainHelpers for *; 47 | using CCTPBridgeTesting for *; 48 | 49 | Domain source; 50 | Domain destination; 51 | 52 | Bridge bridge; 53 | 54 | function setUp() public { 55 | RecordedLogs.init(); 56 | } 57 | 58 | function test_logs_fetch() public { 59 | // We use unique label between tests to make sure there is no interference between tests 60 | string memory label = "test1"; 61 | LogGenerator gen = new LogGenerator(label); 62 | gen.makeLogs(2); 63 | 64 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 65 | 66 | assertEq(logs.length, 2); 67 | assertEq(logs[0].data, abi.encode(label, 0)); 68 | assertEq(logs[1].data, abi.encode(label, 1)); 69 | } 70 | 71 | function test_logs_persists() public { 72 | string memory label = "test2"; 73 | LogGenerator gen = new LogGenerator(label); 74 | gen.makeLogs(1); 75 | 76 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 77 | 78 | assertEq(logs.length, 1); 79 | assertEq(logs[0].data, abi.encode(label, 0)); 80 | 81 | gen.makeLogs(2); 82 | 83 | Vm.Log[] memory logs2 = RecordedLogs.getLogs(); 84 | 85 | assertEq(logs2.length, 3); 86 | assertEq(logs2[0].data, abi.encode(label, 0)); 87 | assertEq(logs2[1].data, abi.encode(label, 0)); 88 | assertEq(logs2[2].data, abi.encode(label, 1)); 89 | } 90 | 91 | function test_performance() public { 92 | // This will generate 1k logs 93 | for (uint256 i = 0; i < 10; i++) { 94 | LogGenerator gen = new LogGenerator("performance"); 95 | gen.makeLogs(100); 96 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 97 | assertEq(logs.length, 100 * (i + 1)); 98 | } 99 | } 100 | 101 | function test_multichain() public { 102 | source = getChain("mainnet").createFork(); 103 | destination = getChain("base").createFork(); 104 | 105 | bridge = CCTPBridgeTesting.createCircleBridge(source, destination); 106 | 107 | destination.selectFork(); 108 | 109 | DummyReceiver r1 = new DummyReceiver(); 110 | 111 | source.selectFork(); 112 | 113 | // Generate a bunch of logs 114 | LogGenerator gen = new LogGenerator("multichain"); 115 | gen.makeLogs(10000); 116 | 117 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ETHEREUM, CCTPForwarder.DOMAIN_ID_CIRCLE_BASE, address(r1), "123"); 118 | 119 | destination.selectFork(); 120 | 121 | assertEq(r1.data(), bytes("")); 122 | 123 | bridge.relayMessagesToDestination(true); 124 | 125 | assertEq(r1.data(), bytes("123")); 126 | } 127 | 128 | function test_clearLogs() public { 129 | // Verify clear logs works even on different forks 130 | source = getChain("mainnet").createFork(); 131 | source.selectFork(); 132 | 133 | string memory label = "clearLogs"; 134 | LogGenerator gen = new LogGenerator(label); 135 | gen.makeLogs(1); 136 | 137 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 138 | 139 | assertEq(logs.length, 1); 140 | assertEq(logs[0].data, abi.encode(label, 0)); 141 | 142 | RecordedLogs.clearLogs(); 143 | 144 | Vm.Log[] memory logs2 = RecordedLogs.getLogs(); 145 | 146 | assertEq(logs2.length, 0); 147 | } 148 | 149 | function test_clearLogs_multichain() public { 150 | // Verify clear logs works even on different forks 151 | source = getChain("mainnet").createFork(); 152 | destination = getChain("base").createFork(); 153 | 154 | source.selectFork(); 155 | 156 | string memory label1 = "logs1"; 157 | LogGenerator gen1 = new LogGenerator(label1); 158 | gen1.makeLogs(1); 159 | 160 | Vm.Log[] memory logs1 = RecordedLogs.getLogs(); 161 | 162 | assertEq(logs1.length, 1); 163 | assertEq(logs1[0].data, abi.encode(label1, 0)); 164 | 165 | destination.selectFork(); 166 | 167 | string memory label2 = "logs2"; 168 | LogGenerator gen2 = new LogGenerator(label2); 169 | gen2.makeLogs(1); 170 | 171 | Vm.Log[] memory logs2 = RecordedLogs.getLogs(); 172 | 173 | assertEq(logs2.length, 2); 174 | assertEq(logs2[0].data, abi.encode(label1, 0)); 175 | assertEq(logs2[1].data, abi.encode(label2, 0)); 176 | 177 | RecordedLogs.clearLogs(); 178 | 179 | Vm.Log[] memory logs3 = RecordedLogs.getLogs(); 180 | 181 | assertEq(logs3.length, 0); 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /src/testing/bridges/OptimismBridgeTesting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { Bridge, BridgeType } from "../Bridge.sol"; 7 | import { Domain, DomainHelpers } from "../Domain.sol"; 8 | import { RecordedLogs } from "../utils/RecordedLogs.sol"; 9 | import { OptimismForwarder } from "../../forwarders/OptimismForwarder.sol"; 10 | 11 | interface IMessenger { 12 | function sendMessage( 13 | address target, 14 | bytes memory message, 15 | uint32 gasLimit 16 | ) external; 17 | function relayMessage( 18 | uint256 _nonce, 19 | address _sender, 20 | address _target, 21 | uint256 _value, 22 | uint256 _minGasLimit, 23 | bytes calldata _message 24 | ) external payable; 25 | } 26 | 27 | library OptimismBridgeTesting { 28 | 29 | using DomainHelpers for *; 30 | using RecordedLogs for *; 31 | 32 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 33 | 34 | bytes32 private constant SENT_MESSAGE_TOPIC = keccak256("SentMessage(address,address,bytes,uint256,uint256)"); 35 | 36 | function createNativeBridge(Domain memory ethereum, Domain memory optimismInstance) internal returns (Bridge memory bridge) { 37 | ( 38 | address sourceCrossChainMessenger, 39 | address destinationCrossChainMessenger 40 | ) = getMessengerFromChainAlias(ethereum.chain.chainAlias, optimismInstance.chain.chainAlias); 41 | 42 | return init(Bridge({ 43 | bridgeType: BridgeType.OPTIMISM, 44 | source: ethereum, 45 | destination: optimismInstance, 46 | sourceCrossChainMessenger: sourceCrossChainMessenger, 47 | destinationCrossChainMessenger: destinationCrossChainMessenger, 48 | lastSourceLogIndex: 0, 49 | lastDestinationLogIndex: 0, 50 | extraData: "" 51 | })); 52 | } 53 | 54 | function getMessengerFromChainAlias( 55 | string memory sourceChainAlias, 56 | string memory destinationChainAlias 57 | ) internal pure returns ( 58 | address sourceCrossChainMessenger, 59 | address destinationCrossChainMessenger 60 | ) { 61 | require(keccak256(bytes(sourceChainAlias)) == keccak256("mainnet"), "Source must be Ethereum."); 62 | 63 | bytes32 name = keccak256(bytes(destinationChainAlias)); 64 | if (name == keccak256("optimism")) { 65 | sourceCrossChainMessenger = OptimismForwarder.L1_CROSS_DOMAIN_OPTIMISM; 66 | } else if (name == keccak256("base")) { 67 | sourceCrossChainMessenger = OptimismForwarder.L1_CROSS_DOMAIN_BASE; 68 | } else if (name == keccak256("world_chain")) { 69 | sourceCrossChainMessenger = OptimismForwarder.L1_CROSS_DOMAIN_WORLD_CHAIN; 70 | } else if (name == keccak256("unichain")) { 71 | sourceCrossChainMessenger = OptimismForwarder.L1_CROSS_DOMAIN_UNICHAIN; 72 | } else { 73 | revert("Unsupported destination chain"); 74 | } 75 | destinationCrossChainMessenger = 0x4200000000000000000000000000000000000007; 76 | } 77 | 78 | function init(Bridge memory bridge) internal returns (Bridge memory) { 79 | RecordedLogs.init(); 80 | 81 | // For consistency with other bridges 82 | bridge.source.selectFork(); 83 | 84 | return bridge; 85 | } 86 | 87 | function relayMessagesToDestination(Bridge storage bridge, bool switchToDestinationFork) internal { 88 | bridge.destination.selectFork(); 89 | 90 | address malias; 91 | unchecked { 92 | malias = address(uint160(bridge.sourceCrossChainMessenger) + uint160(0x1111000000000000000000000000000000001111)); 93 | } 94 | 95 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(true, SENT_MESSAGE_TOPIC, bridge.sourceCrossChainMessenger); 96 | for (uint256 i = 0; i < logs.length; i++) { 97 | Vm.Log memory log = logs[i]; 98 | address target = address(uint160(uint256(log.topics[1]))); 99 | (address sender, bytes memory message, uint256 nonce, uint256 gasLimit) = abi.decode(log.data, (address, bytes, uint256, uint256)); 100 | vm.prank(malias); 101 | IMessenger(bridge.destinationCrossChainMessenger).relayMessage(nonce, sender, target, 0, gasLimit, message); 102 | } 103 | 104 | if (!switchToDestinationFork) { 105 | bridge.source.selectFork(); 106 | } 107 | } 108 | 109 | function relayMessagesToSource(Bridge storage bridge, bool switchToSourceFork) internal { 110 | bridge.source.selectFork(); 111 | 112 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(false, SENT_MESSAGE_TOPIC, bridge.destinationCrossChainMessenger); 113 | for (uint256 i = 0; i < logs.length; i++) { 114 | Vm.Log memory log = logs[i]; 115 | address target = address(uint160(uint256(log.topics[1]))); 116 | (address sender, bytes memory message,,) = abi.decode(log.data, (address, bytes, uint256, uint256)); 117 | // Set xDomainMessageSender 118 | vm.store( 119 | bridge.sourceCrossChainMessenger, 120 | bytes32(uint256(204)), 121 | bytes32(uint256(uint160(sender))) 122 | ); 123 | vm.startPrank(bridge.sourceCrossChainMessenger); 124 | (bool success, bytes memory response) = target.call(message); 125 | vm.stopPrank(); 126 | vm.store( 127 | bridge.sourceCrossChainMessenger, 128 | bytes32(uint256(204)), 129 | bytes32(uint256(0)) 130 | ); 131 | if (!success) { 132 | assembly { 133 | revert(add(response, 32), mload(response)) 134 | } 135 | } 136 | } 137 | 138 | if (!switchToSourceFork) { 139 | bridge.destination.selectFork(); 140 | } 141 | } 142 | 143 | } 144 | -------------------------------------------------------------------------------- /src/testing/utils/RecordedLogs.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { Bridge } from "../Bridge.sol"; 7 | 8 | contract RecordedLogsStorage { 9 | 10 | uint256 public forkId; 11 | 12 | function setForkId(uint256 _forkId) external { 13 | forkId = _forkId; 14 | } 15 | 16 | function storeBytes(bytes memory data) external { 17 | uint256 len = data.length; 18 | uint256 chunks = (len + 31) / 32; 19 | 20 | assembly { 21 | tstore(0, len) 22 | } 23 | 24 | for (uint256 i = 0; i < chunks; i++) { 25 | bytes32 chunk; 26 | assembly { 27 | chunk := mload(add(data, add(32, mul(i, 32)))) 28 | tstore(add(i, 1), chunk) 29 | } 30 | } 31 | } 32 | 33 | function getBytes() external view returns (bytes memory data) { 34 | uint256 len; 35 | 36 | assembly { 37 | len := tload(0) 38 | } 39 | 40 | data = new bytes(len); 41 | uint256 chunks = (len + 31) / 32; 42 | 43 | for (uint256 i = 0; i < chunks; i++) { 44 | bytes32 chunk; 45 | assembly { 46 | chunk := tload(add(i, 1)) 47 | mstore(add(data, add(32, mul(i, 32))), chunk) // Store chunk into memory 48 | } 49 | } 50 | } 51 | 52 | function clearLogs() external { 53 | assembly { 54 | tstore(0, 0) 55 | } 56 | } 57 | 58 | } 59 | 60 | library RecordedLogs { 61 | 62 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 63 | 64 | address private constant STORAGE = address(uint160(uint256(keccak256("__RecordedLogsStorage__")))); 65 | 66 | function init() internal { 67 | if (STORAGE.code.length > 0) { 68 | return; 69 | } 70 | 71 | bytes memory bytecode = vm.getCode("RecordedLogs.sol:RecordedLogsStorage"); 72 | address deployed; 73 | assembly { 74 | deployed := create(0, add(bytecode, 0x20), mload(bytecode)) 75 | } 76 | vm.etch(STORAGE, deployed.code); 77 | vm.makePersistent(STORAGE); 78 | // The fork doesn't really matter we just use this to store the logs on the same place 79 | RecordedLogsStorage(STORAGE).setForkId(vm.createFork(vm.envString("MAINNET_RPC_URL"))); 80 | 81 | vm.recordLogs(); 82 | } 83 | 84 | function getLogs() internal returns (Vm.Log[] memory) { 85 | bool isActiveFork = false; 86 | uint256 prevForkId; 87 | try vm.activeFork() returns (uint256 forkId) { 88 | prevForkId = forkId; 89 | vm.selectFork(RecordedLogsStorage(STORAGE).forkId()); 90 | isActiveFork = true; 91 | } catch {} 92 | 93 | // Fetch new logs 94 | Vm.Log[] memory newLogs = vm.getRecordedLogs(); 95 | 96 | // Decode the old logs from storage 97 | Vm.Log[] memory oldLogs; 98 | bytes memory oldEncodedLogsBytes = RecordedLogsStorage(STORAGE).getBytes(); 99 | if (oldEncodedLogsBytes.length > 0) { 100 | bytes[] memory oldEncodedLogs = abi.decode(oldEncodedLogsBytes, (bytes[])); 101 | oldLogs = new Vm.Log[](oldEncodedLogs.length); 102 | for (uint256 i = 0; i < oldEncodedLogs.length; i++) { 103 | (oldLogs[i].topics, oldLogs[i].data, oldLogs[i].emitter) = abi.decode(oldEncodedLogs[i], (bytes32[], bytes, address)); 104 | } 105 | } 106 | 107 | // Merge them together 108 | Vm.Log[] memory logs = new Vm.Log[](oldLogs.length + newLogs.length); 109 | for (uint256 i = 0; i < oldLogs.length; i++) { 110 | logs[i] = oldLogs[i]; 111 | } 112 | for (uint256 i = 0; i < newLogs.length; i++) { 113 | logs[oldLogs.length + i] = newLogs[i]; 114 | } 115 | 116 | // Write the combined logs back to storage 117 | bytes[] memory encodedLogs = new bytes[](logs.length); 118 | for (uint256 i = 0; i < logs.length; i++) { 119 | encodedLogs[i] = abi.encode(logs[i].topics, logs[i].data, logs[i].emitter); 120 | } 121 | RecordedLogsStorage(STORAGE).storeBytes(abi.encode(encodedLogs)); 122 | 123 | if (isActiveFork) vm.selectFork(prevForkId); 124 | 125 | return logs; 126 | } 127 | 128 | function clearLogs() internal { 129 | bool isActiveFork = false; 130 | uint256 prevForkId; 131 | try vm.activeFork() returns (uint256 forkId) { 132 | prevForkId = forkId; 133 | vm.selectFork(RecordedLogsStorage(STORAGE).forkId()); 134 | isActiveFork = true; 135 | } catch {} 136 | 137 | vm.getRecordedLogs(); 138 | RecordedLogsStorage(STORAGE).clearLogs(); 139 | 140 | if (isActiveFork) vm.selectFork(prevForkId); 141 | } 142 | 143 | function ingestAndFilterLogs(Bridge storage bridge, bool sourceToDestination, bytes32 topic0, bytes32 topic1, address emitter) internal returns (Vm.Log[] memory filteredLogs) { 144 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 145 | uint256 lastIndex = sourceToDestination ? bridge.lastSourceLogIndex : bridge.lastDestinationLogIndex; 146 | uint256 pushedIndex = 0; 147 | 148 | filteredLogs = new Vm.Log[](logs.length - lastIndex); 149 | 150 | for (; lastIndex < logs.length; lastIndex++) { 151 | Vm.Log memory log = logs[lastIndex]; 152 | if ((log.topics[0] == topic0 || log.topics[0] == topic1) && log.emitter == emitter) { 153 | filteredLogs[pushedIndex++] = log; 154 | } 155 | } 156 | 157 | if (sourceToDestination) bridge.lastSourceLogIndex = lastIndex; 158 | else bridge.lastDestinationLogIndex = lastIndex; 159 | // Reduce the array length 160 | assembly { mstore(filteredLogs, pushedIndex) } 161 | } 162 | 163 | function ingestAndFilterLogs(Bridge storage bridge, bool sourceToDestination, bytes32 topic, address emitter) internal returns (Vm.Log[] memory filteredLogs) { 164 | return ingestAndFilterLogs(bridge, sourceToDestination, topic, bytes32(0), emitter); 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /src/testing/bridges/CCTPBridgeTesting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { Bridge, BridgeType } from "../Bridge.sol"; 7 | import { Domain, DomainHelpers } from "../Domain.sol"; 8 | import { RecordedLogs } from "../utils/RecordedLogs.sol"; 9 | import { CCTPForwarder } from "../../forwarders/CCTPForwarder.sol"; 10 | 11 | interface IMessenger { 12 | function localDomain() external view returns (uint32); 13 | function receiveMessage(bytes calldata message, bytes calldata attestation) external returns (bool success); 14 | } 15 | 16 | library CCTPBridgeTesting { 17 | 18 | bytes32 private constant SENT_MESSAGE_TOPIC = keccak256("MessageSent(bytes)"); 19 | 20 | using DomainHelpers for *; 21 | using RecordedLogs for *; 22 | 23 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 24 | 25 | function createCircleBridge(Domain memory source, Domain memory destination) internal returns (Bridge memory bridge) { 26 | return init(Bridge({ 27 | bridgeType: BridgeType.CCTP, 28 | source: source, 29 | destination: destination, 30 | sourceCrossChainMessenger: getCircleMessengerFromChainAlias(source.chain.chainAlias), 31 | destinationCrossChainMessenger: getCircleMessengerFromChainAlias(destination.chain.chainAlias), 32 | lastSourceLogIndex: 0, 33 | lastDestinationLogIndex: 0, 34 | extraData: "" 35 | })); 36 | } 37 | 38 | function getCircleMessengerFromChainAlias(string memory chainAlias) internal pure returns (address) { 39 | bytes32 name = keccak256(bytes(chainAlias)); 40 | if (name == keccak256("mainnet")) { 41 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ETHEREUM; 42 | } else if (name == keccak256("avalanche")) { 43 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_AVALANCHE; 44 | } else if (name == keccak256("optimism")) { 45 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_OPTIMISM; 46 | } else if (name == keccak256("arbitrum_one")) { 47 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ARBITRUM_ONE; 48 | } else if (name == keccak256("base")) { 49 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_BASE; 50 | } else if (name == keccak256("polygon")) { 51 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_POLYGON_POS; 52 | } else if (name == keccak256("unichain")) { 53 | return CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_UNICHAIN; 54 | } else { 55 | revert("Unsupported chain"); 56 | } 57 | } 58 | 59 | function init(Bridge memory bridge) internal returns (Bridge memory) { 60 | // Set minimum required signatures to zero for both domains 61 | bridge.destination.selectFork(); 62 | vm.store( 63 | bridge.destinationCrossChainMessenger, 64 | bytes32(uint256(4)), 65 | 0 66 | ); 67 | bridge.source.selectFork(); 68 | vm.store( 69 | bridge.sourceCrossChainMessenger, 70 | bytes32(uint256(4)), 71 | 0 72 | ); 73 | 74 | RecordedLogs.init(); 75 | 76 | return bridge; 77 | } 78 | 79 | function relayMessagesToDestination(Bridge storage bridge, bool switchToDestinationFork) internal { 80 | bridge.destination.selectFork(); 81 | 82 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(true, SENT_MESSAGE_TOPIC, bridge.sourceCrossChainMessenger); 83 | for (uint256 i = 0; i < logs.length; i++) { 84 | bytes memory message = abi.decode(logs[i].data, (bytes)); 85 | uint32 destinationDomain = getDestinationDomain(message); 86 | if (destinationDomain == IMessenger(bridge.destinationCrossChainMessenger).localDomain()) { 87 | IMessenger(bridge.destinationCrossChainMessenger).receiveMessage(message, ""); 88 | } 89 | } 90 | 91 | if (!switchToDestinationFork) { 92 | bridge.source.selectFork(); 93 | } 94 | } 95 | 96 | function relayMessagesToSource(Bridge storage bridge, bool switchToSourceFork) internal { 97 | bridge.source.selectFork(); 98 | 99 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(false, SENT_MESSAGE_TOPIC, bridge.destinationCrossChainMessenger); 100 | for (uint256 i = 0; i < logs.length; i++) { 101 | bytes memory message = abi.decode(logs[i].data, (bytes)); 102 | uint32 destinationDomain = getDestinationDomain(message); 103 | if (destinationDomain == IMessenger(bridge.sourceCrossChainMessenger).localDomain()) { 104 | IMessenger(bridge.sourceCrossChainMessenger).receiveMessage(message, ""); 105 | } 106 | } 107 | 108 | if (!switchToSourceFork) { 109 | bridge.destination.selectFork(); 110 | } 111 | } 112 | 113 | /** 114 | * @notice Extracts the destinationDomain (a uint32) from a message. 115 | * @param message The encoded message as a bytes array. 116 | * @return destinationDomain The extracted destinationDomain. 117 | * 118 | * Message format: 119 | * Field Bytes Type Index 120 | * version 4 uint32 0 121 | * sourceDomain 4 uint32 4 122 | * destinationDomain 4 uint32 8 123 | * nonce 8 uint64 12 124 | * sender 32 bytes32 20 125 | * recipient 32 bytes32 52 126 | * messageBody dynamic bytes 84 127 | */ 128 | function getDestinationDomain(bytes memory message) public pure returns (uint32 destinationDomain) { 129 | require(message.length >= 12, "Message too short"); 130 | 131 | assembly { 132 | // Add 32 to skip the length word, then add 8 to reach the destinationDomain. 133 | // mload loads 32 bytes starting from that position. 134 | // The actual uint32 is in the top 4 bytes, so shift right by 224 bits. 135 | destinationDomain := shr(224, mload(add(message, 40))) 136 | } 137 | } 138 | 139 | } 140 | -------------------------------------------------------------------------------- /test/LZReceiver.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "forge-std/Test.sol"; 5 | 6 | import { TargetContractMock } from "test/mocks/TargetContractMock.sol"; 7 | 8 | import { LZForwarder } from "src/forwarders/LZForwarder.sol"; 9 | import { LZReceiver, Origin } from "src/receivers/LZReceiver.sol"; 10 | 11 | interface ILayerZeroEndpointV2 { 12 | function delegates(address sender) external view returns (address); 13 | } 14 | 15 | contract LZReceiverTest is Test { 16 | 17 | TargetContractMock target; 18 | 19 | LZReceiver receiver; 20 | 21 | address destinationEndpoint = LZForwarder.ENDPOINT_BNB; 22 | address randomAddress = makeAddr("randomAddress"); 23 | address sourceAuthority = makeAddr("sourceAuthority"); 24 | address delegate = makeAddr("delegate"); 25 | address owner = makeAddr("owner"); 26 | 27 | uint32 srcEid = LZForwarder.ENDPOINT_ID_ETHEREUM; 28 | 29 | error NoPeer(uint32 eid); 30 | error OnlyEndpoint(address addr); 31 | error OnlyPeer(uint32 eid, bytes32 sender); 32 | 33 | function setUp() public { 34 | vm.createSelectFork(getChain("bnb_smart_chain").rpcUrl); 35 | 36 | target = new TargetContractMock(); 37 | 38 | receiver = new LZReceiver( 39 | destinationEndpoint, 40 | srcEid, 41 | bytes32(uint256(uint160(sourceAuthority))), 42 | address(target), 43 | delegate, 44 | owner 45 | ); 46 | } 47 | 48 | function test_constructor() public view { 49 | assertEq(receiver.srcEid(), srcEid); 50 | assertEq(receiver.sourceAuthority(), bytes32(uint256(uint160(sourceAuthority)))); 51 | assertEq(receiver.target(), address(target)); 52 | assertEq(receiver.owner(), owner); 53 | assertEq(receiver.peers(srcEid), bytes32(uint256(uint160(sourceAuthority)))); 54 | 55 | assertEq( 56 | ILayerZeroEndpointV2(address(receiver.endpoint())).delegates(address(receiver)), 57 | delegate 58 | ); 59 | } 60 | 61 | function test_invalidEndpoint() public { 62 | vm.prank(randomAddress); 63 | vm.expectRevert(abi.encodeWithSelector(OnlyEndpoint.selector, randomAddress)); 64 | receiver.lzReceive( 65 | Origin({ 66 | srcEid: srcEid, 67 | sender: bytes32(uint256(uint160(randomAddress))), 68 | nonce: 1 69 | }), 70 | bytes32(0), 71 | abi.encodeCall(TargetContractMock.increment, ()), 72 | address(0), 73 | "" 74 | ); 75 | } 76 | 77 | function test_lzReceive_revertsNoPeer() public { 78 | vm.prank(destinationEndpoint); 79 | vm.expectRevert(abi.encodeWithSelector(NoPeer.selector, 0)); 80 | receiver.lzReceive( 81 | Origin({ 82 | srcEid: 0, 83 | sender: bytes32(uint256(uint160(randomAddress))), 84 | nonce: 1 85 | }), 86 | bytes32(0), 87 | abi.encodeCall(TargetContractMock.increment, ()), 88 | address(0), 89 | "" 90 | ); 91 | } 92 | 93 | function test_lzReceive_revertsOnlyPeer() public { 94 | vm.prank(destinationEndpoint); 95 | vm.expectRevert(abi.encodeWithSelector(OnlyPeer.selector, srcEid, bytes32(uint256(uint160(randomAddress))))); 96 | receiver.lzReceive( 97 | Origin({ 98 | srcEid: srcEid, 99 | sender: bytes32(uint256(uint160(randomAddress))), 100 | nonce: 1 101 | }), 102 | bytes32(0), 103 | abi.encodeCall(TargetContractMock.increment, ()), 104 | address(0), 105 | "" 106 | ); 107 | } 108 | 109 | function test_lzReceive_invalidSrcEid() public { 110 | // NOTE: To pass initial check, we set the peer. 111 | vm.prank(owner); 112 | receiver.setPeer(srcEid + 1, bytes32(uint256(uint160(sourceAuthority)))); 113 | 114 | vm.prank(destinationEndpoint); 115 | vm.expectRevert("LZReceiver/invalid-srcEid"); 116 | receiver.lzReceive( 117 | Origin({ 118 | srcEid: srcEid + 1, 119 | sender: bytes32(uint256(uint160(sourceAuthority))), 120 | nonce: 1 121 | }), 122 | bytes32(0), 123 | abi.encodeCall(TargetContractMock.increment, ()), 124 | address(0), 125 | "" 126 | ); 127 | } 128 | 129 | function test_lzReceive_invalidSourceAuthority() public { 130 | // NOTE: To pass initial check, we set the peer. 131 | vm.prank(owner); 132 | receiver.setPeer(srcEid, bytes32(uint256(uint160(randomAddress)))); 133 | 134 | vm.prank(destinationEndpoint); 135 | vm.expectRevert("LZReceiver/invalid-sourceAuthority"); 136 | receiver.lzReceive( 137 | Origin({ 138 | srcEid: srcEid, 139 | sender: bytes32(uint256(uint160(randomAddress))), 140 | nonce: 1 141 | }), 142 | bytes32(0), 143 | abi.encodeCall(TargetContractMock.increment, ()), 144 | address(0), 145 | "" 146 | ); 147 | } 148 | 149 | function test_lzReceive_success() public { 150 | assertEq(target.count(), 0); 151 | vm.prank(destinationEndpoint); 152 | receiver.lzReceive( 153 | Origin({ 154 | srcEid: srcEid, 155 | sender: bytes32(uint256(uint160(sourceAuthority))), 156 | nonce: 1 157 | }), 158 | bytes32(0), 159 | abi.encodeCall(TargetContractMock.increment, ()), 160 | address(0), 161 | "" 162 | ); 163 | assertEq(target.count(), 1); 164 | } 165 | 166 | function test_allowInitializePath() public { 167 | // Should return true when origin.srcEid == srcEid, origin.sender == sourceAuthority and peers[origin.srcEid] == origin.sender 168 | assertTrue(receiver.allowInitializePath(Origin({ 169 | srcEid: srcEid, 170 | sender: bytes32(uint256(uint160(sourceAuthority))), 171 | nonce: 1 172 | }))); 173 | 174 | // Should return false when peers[origin.srcEid] != origin.sender 175 | 176 | assertFalse(receiver.allowInitializePath(Origin({ 177 | srcEid: srcEid, 178 | sender: bytes32(uint256(uint160(randomAddress))), 179 | nonce: 1 180 | }))); 181 | 182 | // Should return false when origin.srcEid != srcEid 183 | 184 | // NOTE: Setting peer to make `super.allowInitializePath(origin)` return true 185 | vm.prank(owner); 186 | receiver.setPeer(srcEid + 1, bytes32(uint256(uint160(sourceAuthority)))); 187 | 188 | assertFalse(receiver.allowInitializePath(Origin({ 189 | srcEid: srcEid + 1, 190 | sender: bytes32(uint256(uint160(sourceAuthority))), 191 | nonce: 1 192 | }))); 193 | 194 | // Should return false when origin.sender != sourceAuthority 195 | 196 | // NOTE: Setting peer to make `super.allowInitializePath(origin)` return true 197 | vm.prank(owner); 198 | receiver.setPeer(srcEid, bytes32(uint256(uint160(randomAddress)))); 199 | 200 | assertFalse(receiver.allowInitializePath(Origin({ 201 | srcEid: srcEid, 202 | sender: bytes32(uint256(uint160(randomAddress))), 203 | nonce: 1 204 | }))); 205 | } 206 | 207 | } 208 | -------------------------------------------------------------------------------- /test/CircleCCTPIntegration.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "./IntegrationBase.t.sol"; 5 | 6 | import { CCTPBridgeTesting } from "src/testing/bridges/CCTPBridgeTesting.sol"; 7 | import { CCTPForwarder } from "src/forwarders/CCTPForwarder.sol"; 8 | import { CCTPReceiver } from "src/receivers/CCTPReceiver.sol"; 9 | 10 | import { RecordedLogs } from "src/testing/utils/RecordedLogs.sol"; 11 | 12 | contract DummyReceiver { 13 | 14 | bytes public message; 15 | 16 | function handleReceiveMessage( 17 | uint32, 18 | bytes32, 19 | bytes calldata _message 20 | ) external returns (bool) { 21 | message = _message; 22 | 23 | return true; 24 | } 25 | 26 | } 27 | 28 | contract CircleCCTPIntegrationTest is IntegrationBaseTest { 29 | 30 | using CCTPBridgeTesting for *; 31 | using DomainHelpers for *; 32 | 33 | uint32 sourceDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_ETHEREUM; 34 | uint32 destinationDomainId; 35 | 36 | Domain destination2; 37 | Bridge bridge2; 38 | 39 | // Use Optimism for failure tests as the code logic is the same 40 | 41 | function test_invalidSender() public { 42 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_OPTIMISM; 43 | initBaseContracts(getChain("optimism").createFork()); 44 | 45 | destination.selectFork(); 46 | 47 | vm.prank(randomAddress); 48 | vm.expectRevert("CCTPReceiver/invalid-sender"); 49 | CCTPReceiver(destinationReceiver).handleReceiveMessage(0, bytes32(uint256(uint160(sourceAuthority))), abi.encodeCall(MessageOrdering.push, (1))); 50 | } 51 | 52 | function test_invalidSourceDomain() public { 53 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_OPTIMISM; 54 | initBaseContracts(getChain("optimism").createFork()); 55 | 56 | destination.selectFork(); 57 | 58 | vm.prank(bridge.destinationCrossChainMessenger); 59 | vm.expectRevert("CCTPReceiver/invalid-sourceDomain"); 60 | CCTPReceiver(destinationReceiver).handleReceiveMessage(1, bytes32(uint256(uint160(sourceAuthority))), abi.encodeCall(MessageOrdering.push, (1))); 61 | } 62 | 63 | function test_invalidSourceAuthority() public { 64 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_OPTIMISM; 65 | initBaseContracts(getChain("optimism").createFork()); 66 | 67 | destination.selectFork(); 68 | 69 | vm.prank(bridge.destinationCrossChainMessenger); 70 | vm.expectRevert("CCTPReceiver/invalid-sourceAuthority"); 71 | CCTPReceiver(destinationReceiver).handleReceiveMessage(0, bytes32(uint256(uint160(randomAddress))), abi.encodeCall(MessageOrdering.push, (1))); 72 | } 73 | 74 | function test_avalanche() public { 75 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_AVALANCHE; 76 | runCrossChainTests(getChain("avalanche").createFork()); 77 | } 78 | 79 | function test_optimism() public { 80 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_OPTIMISM; 81 | runCrossChainTests(getChain("optimism").createFork()); 82 | } 83 | 84 | function test_arbitrum_one() public { 85 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_ARBITRUM_ONE; 86 | runCrossChainTests(getChain("arbitrum_one").createFork()); 87 | } 88 | 89 | function test_base() public { 90 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_BASE; 91 | runCrossChainTests(getChain("base").createFork()); 92 | } 93 | 94 | function test_polygon() public { 95 | destinationDomainId = CCTPForwarder.DOMAIN_ID_CIRCLE_POLYGON_POS; 96 | runCrossChainTests(getChain("polygon").createFork()); 97 | } 98 | 99 | function test_multiple() public { 100 | destination = getChain("base").createFork(); 101 | destination2 = getChain("arbitrum_one").createFork(); 102 | 103 | DummyReceiver r0 = new DummyReceiver(); 104 | assertEq(r0.message().length, 0); 105 | destination.selectFork(); 106 | DummyReceiver r1 = new DummyReceiver(); 107 | assertEq(r1.message().length, 0); 108 | destination2.selectFork(); 109 | DummyReceiver r2 = new DummyReceiver(); 110 | assertEq(r2.message().length, 0); 111 | 112 | bridge = CCTPBridgeTesting.createCircleBridge(source, destination); 113 | bridge2 = CCTPBridgeTesting.createCircleBridge(source, destination2); 114 | 115 | source.selectFork(); 116 | 117 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ETHEREUM, CCTPForwarder.DOMAIN_ID_CIRCLE_BASE, address(r1), abi.encode(1)); 118 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ETHEREUM, CCTPForwarder.DOMAIN_ID_CIRCLE_ARBITRUM_ONE, address(r2), abi.encode(2)); 119 | 120 | bridge.relayMessagesToDestination(true); 121 | bridge2.relayMessagesToDestination(true); 122 | 123 | destination.selectFork(); 124 | assertEq(r1.message(), abi.encode(1)); 125 | destination2.selectFork(); 126 | assertEq(r2.message(), abi.encode(2)); 127 | 128 | destination.selectFork(); 129 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_BASE, CCTPForwarder.DOMAIN_ID_CIRCLE_ETHEREUM, address(r0), abi.encode(3)); 130 | destination2.selectFork(); 131 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ARBITRUM_ONE, CCTPForwarder.DOMAIN_ID_CIRCLE_ETHEREUM, address(r0), abi.encode(4)); 132 | CCTPForwarder.sendMessage(CCTPForwarder.MESSAGE_TRANSMITTER_CIRCLE_ARBITRUM_ONE, CCTPForwarder.DOMAIN_ID_CIRCLE_ETHEREUM, address(r0), abi.encode(5)); 133 | 134 | assertEq(r0.message(), bytes("")); 135 | 136 | bridge.relayMessagesToDestination(true); 137 | bridge2.relayMessagesToDestination(true); 138 | 139 | assertEq(r0.message(), bytes("")); 140 | 141 | bridge2.relayMessagesToSource(true); 142 | 143 | assertEq(r0.message(), abi.encode(5)); 144 | 145 | bridge.relayMessagesToSource(true); 146 | 147 | assertEq(r0.message(), abi.encode(3)); 148 | } 149 | 150 | function initSourceReceiver() internal override returns (address) { 151 | return address(new CCTPReceiver(bridge.sourceCrossChainMessenger, destinationDomainId, bytes32(uint256(uint160(destinationAuthority))), address(moSource))); 152 | } 153 | 154 | function initDestinationReceiver() internal override returns (address) { 155 | return address(new CCTPReceiver(bridge.destinationCrossChainMessenger, sourceDomainId, bytes32(uint256(uint160(sourceAuthority))), address(moDestination))); 156 | } 157 | 158 | function initBridgeTesting() internal override returns (Bridge memory) { 159 | return CCTPBridgeTesting.createCircleBridge(source, destination); 160 | } 161 | 162 | function queueSourceToDestination(bytes memory message) internal override { 163 | CCTPForwarder.sendMessage( 164 | bridge.sourceCrossChainMessenger, 165 | destinationDomainId, 166 | destinationReceiver, 167 | message 168 | ); 169 | } 170 | 171 | function queueDestinationToSource(bytes memory message) internal override { 172 | CCTPForwarder.sendMessage( 173 | bridge.destinationCrossChainMessenger, 174 | sourceDomainId, 175 | sourceReceiver, 176 | message 177 | ); 178 | } 179 | 180 | function relaySourceToDestination() internal override { 181 | bridge.relayMessagesToDestination(true); 182 | } 183 | 184 | function relayDestinationToSource() internal override { 185 | bridge.relayMessagesToSource(true); 186 | } 187 | 188 | } 189 | -------------------------------------------------------------------------------- /src/testing/bridges/ArbitrumBridgeTesting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { Bridge, BridgeType } from "../Bridge.sol"; 7 | import { Domain, DomainHelpers } from "../Domain.sol"; 8 | import { RecordedLogs } from "../utils/RecordedLogs.sol"; 9 | import { ArbitrumForwarder } from "../../forwarders/ArbitrumForwarder.sol"; 10 | 11 | interface InboxLike { 12 | function createRetryableTicket( 13 | address destAddr, 14 | uint256 arbTxCallValue, 15 | uint256 maxSubmissionCost, 16 | address submissionRefundAddress, 17 | address valueRefundAddress, 18 | uint256 maxGas, 19 | uint256 gasPriceBid, 20 | bytes calldata data 21 | ) external payable returns (uint256); 22 | function bridge() external view returns (BridgeLike); 23 | } 24 | 25 | interface BridgeLike { 26 | function rollup() external view returns (address); 27 | function executeCall( 28 | address, 29 | uint256, 30 | bytes calldata 31 | ) external returns (bool, bytes memory); 32 | function setOutbox(address, bool) external; 33 | } 34 | 35 | contract ArbSysOverride { 36 | 37 | event SendTxToL1(address sender, address target, bytes data); 38 | 39 | function sendTxToL1(address target, bytes calldata message) external payable returns (uint256) { 40 | emit SendTxToL1(msg.sender, target, message); 41 | return 0; 42 | } 43 | 44 | } 45 | 46 | library ArbitrumBridgeTesting { 47 | 48 | using DomainHelpers for *; 49 | using RecordedLogs for *; 50 | 51 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 52 | 53 | bytes32 private constant MESSAGE_DELIVERED_TOPIC = keccak256("MessageDelivered(uint256,bytes32,address,uint8,address,bytes32,uint256,uint64)"); 54 | bytes32 private constant SEND_TO_L1_TOPIC = keccak256("SendTxToL1(address,address,bytes)"); 55 | 56 | function createNativeBridge(Domain memory ethereum, Domain memory arbitrumInstance) internal returns (Bridge memory bridge) { 57 | ( 58 | address sourceCrossChainMessenger, 59 | address destinationCrossChainMessenger 60 | ) = getMessengerFromChainAlias(ethereum.chain.chainAlias, arbitrumInstance.chain.chainAlias); 61 | 62 | return init(Bridge({ 63 | bridgeType: BridgeType.ARBITRUM, 64 | source: ethereum, 65 | destination: arbitrumInstance, 66 | sourceCrossChainMessenger: sourceCrossChainMessenger, 67 | destinationCrossChainMessenger: destinationCrossChainMessenger, 68 | lastSourceLogIndex: 0, 69 | lastDestinationLogIndex: 0, 70 | extraData: "" 71 | })); 72 | } 73 | 74 | function getMessengerFromChainAlias( 75 | string memory sourceChainAlias, 76 | string memory destinationChainAlias 77 | ) internal pure returns ( 78 | address sourceCrossChainMessenger, 79 | address destinationCrossChainMessenger 80 | ) { 81 | require(keccak256(bytes(sourceChainAlias)) == keccak256("mainnet"), "Source must be Ethereum."); 82 | 83 | bytes32 name = keccak256(bytes(destinationChainAlias)); 84 | if (name == keccak256("arbitrum_one")) { 85 | sourceCrossChainMessenger = ArbitrumForwarder.L1_CROSS_DOMAIN_ARBITRUM_ONE; 86 | } else if (name == keccak256("arbitrum_nova")) { 87 | sourceCrossChainMessenger = ArbitrumForwarder.L1_CROSS_DOMAIN_ARBITRUM_NOVA; 88 | } else { 89 | revert("Unsupported destination chain"); 90 | } 91 | destinationCrossChainMessenger = 0x0000000000000000000000000000000000000064; 92 | } 93 | 94 | function init(Bridge memory bridge) internal returns (Bridge memory) { 95 | RecordedLogs.init(); 96 | 97 | // Need to replace ArbSys contract with custom code to make it compatible with revm 98 | bridge.destination.selectFork(); 99 | bytes memory bytecode = vm.getCode("ArbitrumBridgeTesting.sol:ArbSysOverride"); 100 | address deployed; 101 | assembly { 102 | deployed := create(0, add(bytecode, 0x20), mload(bytecode)) 103 | } 104 | vm.etch(bridge.destinationCrossChainMessenger, deployed.code); 105 | 106 | bridge.source.selectFork(); 107 | BridgeLike underlyingBridge = InboxLike(bridge.sourceCrossChainMessenger).bridge(); 108 | bridge.extraData = abi.encode(address(underlyingBridge)); 109 | 110 | // Make this contract a valid outbox 111 | address _rollup = underlyingBridge.rollup(); 112 | vm.store( 113 | address(underlyingBridge), 114 | bytes32(uint256(8)), 115 | bytes32(uint256(uint160(address(this)))) 116 | ); 117 | underlyingBridge.setOutbox(address(this), true); 118 | vm.store( 119 | address(underlyingBridge), 120 | bytes32(uint256(8)), 121 | bytes32(uint256(uint160(_rollup))) 122 | ); 123 | 124 | return bridge; 125 | } 126 | 127 | function relayMessagesToDestination(Bridge storage bridge, bool switchToDestinationFork) internal { 128 | bridge.destination.selectFork(); 129 | 130 | Vm.Log[] memory logs = RecordedLogs.getLogs(); 131 | for (; bridge.lastSourceLogIndex < logs.length; bridge.lastSourceLogIndex++) { 132 | Vm.Log memory log = logs[bridge.lastSourceLogIndex]; 133 | if (log.topics[0] == MESSAGE_DELIVERED_TOPIC && log.emitter == abi.decode(bridge.extraData, (address))) { 134 | // We need both the current event and the one that follows for all the relevant data 135 | Vm.Log memory logWithData = logs[bridge.lastSourceLogIndex + 1]; 136 | (,, address sender,,,) = abi.decode(log.data, (address, uint8, address, bytes32, uint256, uint64)); 137 | (address target, bytes memory message) = _parseData(logWithData.data); 138 | vm.startPrank(sender); 139 | (bool success, bytes memory response) = target.call(message); 140 | vm.stopPrank(); 141 | if (!success) { 142 | assembly { 143 | revert(add(response, 32), mload(response)) 144 | } 145 | } 146 | } 147 | } 148 | 149 | if (!switchToDestinationFork) { 150 | bridge.source.selectFork(); 151 | } 152 | } 153 | 154 | function relayMessagesToSource(Bridge storage bridge, bool switchToSourceFork) internal { 155 | bridge.source.selectFork(); 156 | 157 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(false, SEND_TO_L1_TOPIC, bridge.destinationCrossChainMessenger); 158 | for (uint256 i = 0; i < logs.length; i++) { 159 | Vm.Log memory log = logs[i]; 160 | (, address target, bytes memory message) = abi.decode(log.data, (address, address, bytes)); 161 | (bool success, bytes memory response) = InboxLike(bridge.sourceCrossChainMessenger).bridge().executeCall(target, 0, message); 162 | if (!success) { 163 | assembly { 164 | revert(add(response, 32), mload(response)) 165 | } 166 | } 167 | } 168 | 169 | if (!switchToSourceFork) { 170 | bridge.destination.selectFork(); 171 | } 172 | } 173 | 174 | function _parseData(bytes memory orig) private pure returns (address target, bytes memory message) { 175 | // FIXME - this is not robust enough, only handling messages of a specific format 176 | uint256 mlen; 177 | (,,target ,,,,,,,, mlen) = abi.decode(orig, (uint256, uint256, address, uint256, uint256, uint256, address, address, uint256, uint256, uint256)); 178 | message = new bytes(mlen); 179 | for (uint256 i = 0; i < mlen; i++) { 180 | message[i] = orig[i + 352]; 181 | } 182 | } 183 | 184 | } 185 | -------------------------------------------------------------------------------- /test/LZIntegration.t.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import "./IntegrationBase.t.sol"; 5 | 6 | import { OptionsBuilder } from "layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol"; 7 | 8 | import { LZBridgeTesting } from "src/testing/bridges/LZBridgeTesting.sol"; 9 | import { LZForwarder, ILayerZeroEndpointV2 } from "src/forwarders/LZForwarder.sol"; 10 | import { LZReceiver, Origin } from "src/receivers/LZReceiver.sol"; 11 | 12 | import { RecordedLogs } from "src/testing/utils/RecordedLogs.sol"; 13 | 14 | contract LZIntegrationTest is IntegrationBaseTest { 15 | 16 | using DomainHelpers for *; 17 | using LZBridgeTesting for *; 18 | using OptionsBuilder for bytes; 19 | 20 | uint32 sourceEndpointId = LZForwarder.ENDPOINT_ID_ETHEREUM; 21 | uint32 destinationEndpointId; 22 | 23 | address sourceEndpoint = LZForwarder.ENDPOINT_ETHEREUM; 24 | address destinationEndpoint; 25 | 26 | Domain destination2; 27 | Bridge bridge2; 28 | 29 | error NoPeer(uint32 eid); 30 | error OnlyEndpoint(address addr); 31 | error OnlyPeer(uint32 eid, bytes32 sender); 32 | 33 | function test_invalidEndpoint() public { 34 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 35 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 36 | initBaseContracts(getChain("base").createFork()); 37 | 38 | destination.selectFork(); 39 | 40 | vm.prank(randomAddress); 41 | vm.expectRevert(abi.encodeWithSelector(OnlyEndpoint.selector, randomAddress)); 42 | LZReceiver(destinationReceiver).lzReceive( 43 | Origin({ 44 | srcEid: sourceEndpointId, 45 | sender: bytes32(uint256(uint160(sourceAuthority))), 46 | nonce: 1 47 | }), 48 | bytes32(0), 49 | abi.encodeCall(MessageOrdering.push, (1)), 50 | address(0), 51 | "" 52 | ); 53 | } 54 | 55 | function test_lzReceive_revertsNoPeer() public { 56 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 57 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 58 | initBaseContracts(getChain("base").createFork()); 59 | 60 | destination.selectFork(); 61 | 62 | vm.prank(bridge.destinationCrossChainMessenger); 63 | vm.expectRevert(abi.encodeWithSelector(NoPeer.selector, 0)); 64 | LZReceiver(destinationReceiver).lzReceive( 65 | Origin({ 66 | srcEid: 0, 67 | sender: bytes32(uint256(uint160(sourceAuthority))), 68 | nonce: 1 69 | }), 70 | bytes32(0), 71 | abi.encodeCall(MessageOrdering.push, (1)), 72 | address(0), 73 | "" 74 | ); 75 | } 76 | 77 | function test_lzReceive_revertsOnlyPeer() public { 78 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 79 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 80 | initBaseContracts(getChain("base").createFork()); 81 | 82 | destination.selectFork(); 83 | 84 | vm.prank(bridge.destinationCrossChainMessenger); 85 | vm.expectRevert(abi.encodeWithSelector(OnlyPeer.selector, sourceEndpointId, bytes32(uint256(uint160(randomAddress))))); 86 | LZReceiver(destinationReceiver).lzReceive( 87 | Origin({ 88 | srcEid: sourceEndpointId, 89 | sender: bytes32(uint256(uint160(randomAddress))), 90 | nonce: 1 91 | }), 92 | bytes32(0), 93 | abi.encodeCall(MessageOrdering.push, (1)), 94 | address(0), 95 | "" 96 | ); 97 | } 98 | 99 | function test_invalidSourceEid() public { 100 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 101 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 102 | initBaseContracts(getChain("base").createFork()); 103 | 104 | destination.selectFork(); 105 | 106 | // NOTE: To pass initial check, we set the peer. 107 | vm.prank(makeAddr("owner")); 108 | LZReceiver(destinationReceiver).setPeer(0, bytes32(uint256(uint160(sourceAuthority)))); 109 | 110 | vm.prank(bridge.destinationCrossChainMessenger); 111 | vm.expectRevert("LZReceiver/invalid-srcEid"); 112 | LZReceiver(destinationReceiver).lzReceive( 113 | Origin({ 114 | srcEid: 0, 115 | sender: bytes32(uint256(uint160(sourceAuthority))), 116 | nonce: 1 117 | }), 118 | bytes32(0), 119 | abi.encodeCall(MessageOrdering.push, (1)), 120 | address(0), 121 | "" 122 | ); 123 | } 124 | 125 | function test_invalidSourceAuthority() public { 126 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 127 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 128 | initBaseContracts(getChain("base").createFork()); 129 | 130 | destination.selectFork(); 131 | 132 | // NOTE: To pass initial check, we set the peer. 133 | vm.prank(makeAddr("owner")); 134 | LZReceiver(destinationReceiver).setPeer(sourceEndpointId, bytes32(uint256(uint160(randomAddress)))); 135 | 136 | vm.prank(bridge.destinationCrossChainMessenger); 137 | vm.expectRevert("LZReceiver/invalid-sourceAuthority"); 138 | LZReceiver(destinationReceiver).lzReceive( 139 | Origin({ 140 | srcEid: sourceEndpointId, 141 | sender: bytes32(uint256(uint160(randomAddress))), 142 | nonce: 1 143 | }), 144 | bytes32(0), 145 | abi.encodeCall(MessageOrdering.push, (1)), 146 | address(0), 147 | "" 148 | ); 149 | } 150 | 151 | function test_base() public { 152 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BASE; 153 | destinationEndpoint = LZForwarder.ENDPOINT_BASE; 154 | 155 | runCrossChainTests(getChain("base").createFork()); 156 | } 157 | 158 | function test_binance() public { 159 | destinationEndpointId = LZForwarder.ENDPOINT_ID_BNB; 160 | destinationEndpoint = LZForwarder.ENDPOINT_BNB; 161 | 162 | runCrossChainTests(getChain("bnb_smart_chain").createFork()); 163 | } 164 | 165 | function initSourceReceiver() internal override returns (address) { 166 | return address(new LZReceiver( 167 | sourceEndpoint, 168 | destinationEndpointId, 169 | bytes32(uint256(uint160(destinationAuthority))), 170 | address(moSource), 171 | makeAddr("delegate"), 172 | makeAddr("owner") 173 | )); 174 | } 175 | 176 | function initDestinationReceiver() internal override returns (address) { 177 | return address(new LZReceiver( 178 | destinationEndpoint, 179 | sourceEndpointId, 180 | bytes32(uint256(uint160(sourceAuthority))), 181 | address(moDestination), 182 | makeAddr("delegate"), 183 | makeAddr("owner") 184 | )); 185 | } 186 | 187 | function initBridgeTesting() internal override returns (Bridge memory) { 188 | return LZBridgeTesting.createLZBridge(source, destination); 189 | } 190 | 191 | function queueSourceToDestination(bytes memory message) internal override { 192 | vm.deal(sourceAuthority, 1 ether); // Gas to queue message 193 | 194 | bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200_000, 0); 195 | 196 | LZForwarder.sendMessage( 197 | destinationEndpointId, 198 | bytes32(uint256(uint160(destinationReceiver))), 199 | ILayerZeroEndpointV2(bridge.sourceCrossChainMessenger), 200 | message, 201 | options, 202 | sourceAuthority, 203 | false 204 | ); 205 | } 206 | 207 | function queueDestinationToSource(bytes memory message) internal override { 208 | vm.deal(destinationAuthority, 1 ether); // Gas to queue message 209 | 210 | bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(200_000, 0); 211 | 212 | LZForwarder.sendMessage( 213 | sourceEndpointId, 214 | bytes32(uint256(uint160(sourceReceiver))), 215 | ILayerZeroEndpointV2(bridge.destinationCrossChainMessenger), 216 | message, 217 | options, 218 | destinationAuthority, 219 | false 220 | ); 221 | } 222 | 223 | function relaySourceToDestination() internal override { 224 | bridge.relayMessagesToDestination(true, sourceAuthority, destinationReceiver); 225 | } 226 | 227 | function relayDestinationToSource() internal override { 228 | bridge.relayMessagesToSource(true, destinationAuthority, sourceReceiver); 229 | } 230 | 231 | } 232 | -------------------------------------------------------------------------------- /src/testing/bridges/LZBridgeTesting.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: AGPL-3.0-or-later 2 | pragma solidity >=0.8.0; 3 | 4 | import { Vm } from "forge-std/Vm.sol"; 5 | 6 | import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol"; 7 | 8 | import { Bridge, BridgeType } from "../Bridge.sol"; 9 | import { Domain, DomainHelpers } from "../Domain.sol"; 10 | import { RecordedLogs } from "../utils/RecordedLogs.sol"; 11 | import { LZForwarder } from "../../forwarders/LZForwarder.sol"; 12 | 13 | struct Origin { 14 | uint32 srcEid; 15 | bytes32 sender; 16 | uint64 nonce; 17 | } 18 | 19 | interface IEndpoint { 20 | function eid() external view returns (uint32); 21 | function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external; 22 | function lzReceive( 23 | Origin calldata _origin, 24 | address _receiver, 25 | bytes32 _guid, 26 | bytes calldata _message, 27 | bytes calldata _extraData 28 | ) external payable; 29 | } 30 | 31 | contract PacketBytesHelper { 32 | 33 | function srcEid(bytes calldata packetBytes) external pure returns (uint32) { 34 | return PacketV1Codec.srcEid(packetBytes); 35 | } 36 | 37 | function nonce(bytes calldata packetBytes) external pure returns (uint64) { 38 | return PacketV1Codec.nonce(packetBytes); 39 | } 40 | 41 | function dstEid(bytes calldata packetBytes) external pure returns (uint32) { 42 | return PacketV1Codec.dstEid(packetBytes); 43 | } 44 | 45 | function guid(bytes calldata packetBytes) external pure returns (bytes32) { 46 | return PacketV1Codec.guid(packetBytes); 47 | } 48 | 49 | function message(bytes calldata packetBytes) external pure returns (bytes memory) { 50 | return PacketV1Codec.message(packetBytes); 51 | } 52 | 53 | } 54 | 55 | library LZBridgeTesting { 56 | 57 | bytes32 private constant PACKET_SENT_TOPIC = keccak256("PacketSent(bytes,bytes,address)"); 58 | 59 | using DomainHelpers for *; 60 | using RecordedLogs for *; 61 | 62 | Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code"))))); 63 | 64 | function createLZBridge(Domain memory source, Domain memory destination) internal returns (Bridge memory bridge) { 65 | return init(Bridge({ 66 | bridgeType: BridgeType.LZ, 67 | source: source, 68 | destination: destination, 69 | sourceCrossChainMessenger: getLZEndpointFromChainAlias(source.chain.chainAlias), 70 | destinationCrossChainMessenger: getLZEndpointFromChainAlias(destination.chain.chainAlias), 71 | lastSourceLogIndex: 0, 72 | lastDestinationLogIndex: 0, 73 | extraData: abi.encode(getReceiveLibraryFromChainAlias(source.chain.chainAlias), getReceiveLibraryFromChainAlias(destination.chain.chainAlias)) 74 | })); 75 | } 76 | 77 | function getLZEndpointFromChainAlias(string memory chainAlias) internal pure returns (address) { 78 | bytes32 name = keccak256(bytes(chainAlias)); 79 | if (name == keccak256("mainnet")) { 80 | return LZForwarder.ENDPOINT_ETHEREUM; 81 | } else if (name == keccak256("base")) { 82 | return LZForwarder.ENDPOINT_BASE; 83 | } else if (name == keccak256("bnb_smart_chain")) { 84 | return LZForwarder.ENDPOINT_BNB; 85 | } else if (name == keccak256("avalanche")) { 86 | return LZForwarder.ENDPOINT_AVALANCHE; 87 | } else { 88 | revert("Unsupported chain"); 89 | } 90 | } 91 | 92 | function getReceiveLibraryFromChainAlias(string memory chainAlias) internal pure returns (address) { 93 | bytes32 name = keccak256(bytes(chainAlias)); 94 | if (name == keccak256("mainnet")) { 95 | return LZForwarder.RECEIVE_LIBRARY_ETHEREUM; 96 | } else if (name == keccak256("base")) { 97 | return LZForwarder.RECEIVE_LIBRARY_BASE; 98 | } else if (name == keccak256("bnb_smart_chain")) { 99 | return LZForwarder.RECEIVE_LIBRARY_BNB; 100 | } else if (name == keccak256("avalanche")) { 101 | return LZForwarder.RECEIVE_LIBRARY_AVALANCHE; 102 | } else { 103 | revert("Unsupported chain"); 104 | } 105 | } 106 | 107 | function init(Bridge memory bridge) internal returns (Bridge memory) { 108 | RecordedLogs.init(); 109 | 110 | // For consistency with other bridges 111 | bridge.source.selectFork(); 112 | 113 | return bridge; 114 | } 115 | 116 | function relayMessagesToDestination( 117 | Bridge storage bridge, 118 | bool switchToDestinationFork, 119 | address sender, 120 | address receiver 121 | ) internal { 122 | bridge.destination.selectFork(); 123 | 124 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(true, PACKET_SENT_TOPIC, bridge.sourceCrossChainMessenger); 125 | for (uint256 i = 0; i < logs.length; i++) { 126 | ( bytes memory encodedPacket,, ) = abi.decode(logs[i].data, (bytes, bytes, address)); 127 | 128 | // Step 1: Parse data from encoded packet in event 129 | 130 | uint32 destinationEid = getDestinationEid(encodedPacket); 131 | bytes32 guid = getGuid(encodedPacket); 132 | bytes memory message = getMessage(encodedPacket); 133 | 134 | if (destinationEid == IEndpoint(bridge.destinationCrossChainMessenger).eid()) { 135 | ( , address destinationReceiveLibrary ) = abi.decode(bridge.extraData, (address, address)); 136 | bytes32 payloadHash = keccak256(abi.encodePacked(guid, message)); 137 | 138 | // Step 2: Prank as destinationReceiveLibrary to bypass DVN verification step, required before lzReceive can be called 139 | 140 | vm.startPrank(destinationReceiveLibrary); 141 | IEndpoint(bridge.destinationCrossChainMessenger).verify( 142 | Origin({ 143 | srcEid: getSourceEid(encodedPacket), 144 | sender: bytes32(uint256(uint160(sender))), 145 | nonce: getNonce(encodedPacket) 146 | }), 147 | receiver, 148 | payloadHash 149 | ); 150 | vm.stopPrank(); 151 | 152 | // Step 3: Call permissionless lzReceive on endpoint now that payload is verified 153 | 154 | IEndpoint(bridge.destinationCrossChainMessenger).lzReceive( 155 | Origin({ 156 | srcEid: getSourceEid(encodedPacket), 157 | sender: bytes32(uint256(uint160(sender))), 158 | nonce: getNonce(encodedPacket) 159 | }), 160 | receiver, 161 | guid, 162 | message, 163 | "" 164 | ); 165 | } 166 | } 167 | 168 | if (!switchToDestinationFork) { 169 | bridge.source.selectFork(); 170 | } 171 | } 172 | 173 | function relayMessagesToSource( 174 | Bridge storage bridge, 175 | bool switchToSourceFork, 176 | address sender, 177 | address receiver 178 | ) internal { 179 | bridge.source.selectFork(); 180 | 181 | Vm.Log[] memory logs = bridge.ingestAndFilterLogs(false, PACKET_SENT_TOPIC, bridge.destinationCrossChainMessenger); 182 | for (uint256 i = 0; i < logs.length; i++) { 183 | ( bytes memory encodedPacket,, ) = abi.decode(logs[i].data, (bytes, bytes, address)); 184 | 185 | // Step 1: Parse data from encoded packet in event 186 | 187 | uint32 destinationEid = getDestinationEid(encodedPacket); // NOTE: destinationEid in this case is for the source endpoint ID 188 | bytes32 guid = getGuid(encodedPacket); 189 | bytes memory message = getMessage(encodedPacket); 190 | 191 | if (destinationEid == IEndpoint(bridge.sourceCrossChainMessenger).eid()) { 192 | ( address sourceReceiveLibrary, ) = abi.decode(bridge.extraData, (address, address)); 193 | bytes32 payloadHash = keccak256(abi.encodePacked(guid, message)); 194 | 195 | // Step 2: Prank as destinationReceiveLibrary to bypass DVN verification step, required before lzReceive can be called 196 | 197 | vm.startPrank(sourceReceiveLibrary); 198 | IEndpoint(bridge.sourceCrossChainMessenger).verify( 199 | Origin({ 200 | srcEid: getSourceEid(encodedPacket), 201 | sender: bytes32(uint256(uint160(sender))), 202 | nonce: getNonce(encodedPacket) 203 | }), 204 | receiver, 205 | payloadHash 206 | ); 207 | vm.stopPrank(); 208 | 209 | // Step 3: Call permissionless lzReceive on endpoint now that payload is verified 210 | 211 | IEndpoint(bridge.sourceCrossChainMessenger).lzReceive( 212 | Origin({ 213 | srcEid: getSourceEid(encodedPacket), 214 | sender: bytes32(uint256(uint160(sender))), 215 | nonce: getNonce(encodedPacket) 216 | }), 217 | receiver, 218 | guid, 219 | message, 220 | "" 221 | ); 222 | } 223 | } 224 | 225 | if (!switchToSourceFork) { 226 | bridge.destination.selectFork(); 227 | } 228 | } 229 | 230 | function getDestinationEid(bytes memory encodedPacket) public returns (uint32) { 231 | return new PacketBytesHelper().dstEid(encodedPacket); 232 | } 233 | 234 | function getGuid(bytes memory encodedPacket) public returns (bytes32) { 235 | return new PacketBytesHelper().guid(encodedPacket); 236 | } 237 | 238 | function getMessage(bytes memory encodedPacket) public returns (bytes memory) { 239 | return new PacketBytesHelper().message(encodedPacket); 240 | } 241 | 242 | function getSourceEid(bytes memory encodedPacket) public returns (uint32) { 243 | return new PacketBytesHelper().srcEid(encodedPacket); 244 | } 245 | 246 | function getNonce(bytes memory encodedPacket) public returns (uint64) { 247 | return new PacketBytesHelper().nonce(encodedPacket); 248 | } 249 | 250 | } 251 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------