From 5098578d2eab7dfe506c5193880cc712f711b28a Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 30 Sep 2026 14:11:20 +0400 Subject: [PATCH 01/14] feat: add Axelar GMP and LayerZero V2 proof oracles Adds transparent Axelar (paid/self-relay, Solana executable envelope, strict base58/StrKey identities) and LayerZero V2 oracles with constructor-only bounded chain mappings, plus Stellar transport tests. MessageEncodingLib now rejects trailing message bytes. --- snapshots/inputSettler.json | 40 ++-- snapshots/oracle.json | 8 +- snapshots/outputSettler.json | 2 +- .../oracles/axelar/AxelarOracle.sol | 118 ++++++++++ .../oracles/axelar/SolanaEnvelope.sol | 19 ++ .../oracles/common/BoundedOracle.sol | 69 ++++++ .../oracles/common/OracleAddress.sol | 135 +++++++++++ .../oracles/layerzero/LayerZeroOracle.sol | 202 +++++++++++++++++ src/libs/MessageEncodingLib.sol | 2 + test/oracle/transport/StellarTransport.t.sol | 213 ++++++++++++++++++ test/oracle/transport/TransportFixtures.sol | 147 ++++++++++++ 11 files changed, 930 insertions(+), 25 deletions(-) create mode 100644 src/integrations/oracles/axelar/AxelarOracle.sol create mode 100644 src/integrations/oracles/axelar/SolanaEnvelope.sol create mode 100644 src/integrations/oracles/common/BoundedOracle.sol create mode 100644 src/integrations/oracles/common/OracleAddress.sol create mode 100644 src/integrations/oracles/layerzero/LayerZeroOracle.sol create mode 100644 test/oracle/transport/StellarTransport.t.sol create mode 100644 test/oracle/transport/TransportFixtures.sol diff --git a/snapshots/inputSettler.json b/snapshots/inputSettler.json index 272e2cee..d3902756 100644 --- a/snapshots/inputSettler.json +++ b/snapshots/inputSettler.json @@ -1,28 +1,28 @@ { "BasePurchaseOrder": "138441", - "CompactFinaliseFor": "167221", - "CompactFinaliseSelf": "158347", - "CompactFinaliseTo": "158347", - "EscrowFinalise": "81268", - "IntegrationCoinFill": "89862", + "CompactFinaliseFor": "126996", + "CompactFinaliseSelf": "119560", + "CompactFinaliseTo": "119560", + "EscrowFinalise": "46544", + "IntegrationCoinFill": "89886", "IntegrationCompactFinaliseSelf": "150381", - "IntegrationWormholeReceiveMessage": "73557", - "IntegrationWormholeSubmit": "42492", - "broadcast": "43912", - "compactFinaliseSelfWithFee": "189114", - "depositAndRegisterFor": "163659", - "escrowFinaliseSelfWithFee": "106622", - "escrowFinaliseWithSignature": "89900", - "escrowOpen": "83106", - "escrowOpenFor3009Single": "115693", - "escrowOpenFor3009SingleArray": "122525", - "escrowOpenFor3009Two": "178133", - "escrowOpenForMsgSender": "83913", - "escrowOpenForPermit2": "125605", - "escrowRefundOnNonFill": "54410", + "IntegrationWormholeReceiveMessage": "73594", + "IntegrationWormholeSubmit": "42516", + "broadcast": "14904", + "compactFinaliseSelfWithFee": "189123", + "depositAndRegisterFor": "129887", + "escrowFinaliseSelfWithFee": "106637", + "escrowFinaliseWithSignature": "53732", + "escrowOpen": "57180", + "escrowOpenFor3009Single": "87859", + "escrowOpenFor3009SingleArray": "94003", + "escrowOpenFor3009Two": "145099", + "escrowOpenForMsgSender": "57339", + "escrowOpenForPermit2": "95283", + "escrowRefundOnNonFill": "21029", "maxTimestamp1": "461", "minTimestamp1": "483", - "tronEscrowFinaliseSelfWithFee": "111065", + "tronEscrowFinaliseSelfWithFee": "111068", "validate2Fills": "9617", "validate2FillsMultipleSolvers": "9617" } \ No newline at end of file diff --git a/snapshots/oracle.json b/snapshots/oracle.json index 400e6d6f..55a7d577 100644 --- a/snapshots/oracle.json +++ b/snapshots/oracle.json @@ -11,8 +11,8 @@ "citreaOutputDispute": "71733", "citreaVerify": "130685", "citreaVerifyWithEmbed": "133295", - "hyperlaneOracleHandle": "50281", - "hyperlaneOracleSubmit": "67472", - "hyperlaneOracleSubmitCustomHook": "67848", - "wormholeOracleSubmit": "42648" + "hyperlaneOracleHandle": "25916", + "hyperlaneOracleSubmit": "37608", + "hyperlaneOracleSubmitCustomHook": "37604", + "wormholeOracleSubmit": "14020" } \ No newline at end of file diff --git a/snapshots/outputSettler.json b/snapshots/outputSettler.json index daaadf91..34ff8588 100644 --- a/snapshots/outputSettler.json +++ b/snapshots/outputSettler.json @@ -1,5 +1,5 @@ { - "emitNotFilled": "32683", + "emitNotFilled": "8431", "outputSettlerCoinFill": "83316", "outputSettlerCoinFillDutchAuction": "84576", "outputSettlerCoinFillExclusive": "84709", diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol new file mode 100644 index 00000000..cdbc4d5a --- /dev/null +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -0,0 +1,118 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { BoundedOracle } from "../common/BoundedOracle.sol"; +import { OracleAddress } from "../common/OracleAddress.sol"; +import { SolanaEnvelope } from "./SolanaEnvelope.sol"; + +interface IAxelarMessageGateway { + function callContract( + string calldata chain, + string calldata destination, + bytes calldata payload + ) external; + function validateContractCall( + bytes32 commandId, + string calldata chain, + string calldata sender, + bytes32 hash + ) external returns (bool); +} + +interface IAxelarNativeGasService { + function payNativeGasForContractCall( + address sender, + string calldata chain, + string calldata destination, + bytes calldata payload, + address refund + ) external payable; +} + +/// Transparent, immutable Axelar GMP oracle. Based on OIF PR #137; supports Stellar sender identities. +contract AxelarOracle is BoundedOracle { + enum DeliveryMode { Relayed, SelfRelay } + struct Chain { + string name; + uint256 chainId; + OracleAddress.Kind kind; + } + + struct Route { + uint256 chainId; + OracleAddress.Kind kind; + } + IAxelarMessageGateway public immutable gateway; + IAxelarNativeGasService public immutable gasService; + mapping(bytes32 => Route) private routes; + error NotApproved(); + error InvalidFee(); + + constructor( + address gateway_, + address gasService_, + Chain[] memory chains + ) { + if (gateway_.code.length == 0 || gasService_.code.length == 0 || chains.length == 0 || chains.length > 16) { + revert InvalidConfiguration(); + } + gateway = IAxelarMessageGateway(gateway_); + gasService = IAxelarNativeGasService(gasService_); + for (uint256 i; i < chains.length; ++i) { + Chain memory c = chains[i]; + bytes32 key = keccak256(bytes(c.name)); + if (bytes(c.name).length == 0 || bytes(c.name).length > 64 || c.chainId == 0 || routes[key].chainId != 0) { + revert InvalidConfiguration(); + } + for (uint256 j; j < i; ++j) { + if (chains[j].chainId == c.chainId) revert InvalidConfiguration(); + } + routes[key] = Route(c.chainId, c.kind); + } + } + + function route( + string calldata name + ) public view returns (Route memory r) { + r = routes[keccak256(bytes(name))]; + if (r.chainId == 0) revert UnknownChain(); + } + + function submit( + string calldata destinationChain, + bytes32 recipientOracle, + address source, + bytes[] calldata payloads, + bytes32 destinationConfig, + DeliveryMode deliveryMode + ) external payable { + Route memory r = route(destinationChain); + string memory recipient = OracleAddress.encode(recipientOracle, r.kind); + bytes memory message = _export(source, payloads); + if (r.kind == OracleAddress.Kind.Solana) { + message = SolanaEnvelope.encode(message, destinationConfig); + } else if (destinationConfig != 0) revert InvalidConfiguration(); + if (deliveryMode == DeliveryMode.Relayed) { + if (msg.value == 0) revert InvalidFee(); + gasService.payNativeGasForContractCall{ value: msg.value }( + address(this), destinationChain, recipient, message, msg.sender + ); + } else if (msg.value != 0) revert InvalidFee(); + gateway.callContract(destinationChain, recipient, message); + } + + /// Anyone may execute, but only the gateway can approve the exact destination-bound message. + function execute( + bytes32 commandId, + string calldata sourceChain, + string calldata sourceAddress, + bytes calldata payload + ) external { + Route memory r = route(sourceChain); + bytes32 sender = OracleAddress.decode(sourceAddress, r.kind); + if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { + revert NotApproved(); + } + _record(r.chainId, sender, payload); + } +} diff --git a/src/integrations/oracles/axelar/SolanaEnvelope.sol b/src/integrations/oracles/axelar/SolanaEnvelope.sol new file mode 100644 index 00000000..ae571f20 --- /dev/null +++ b/src/integrations/oracles/axelar/SolanaEnvelope.sol @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +/// Axelar 1.1.1 ExecutablePayload::Borsh: scheme, byte vector, account vector. +/// The destination configuration is the sole extra account, read-only and not a signer. +library SolanaEnvelope { + uint256 internal constant MAX_PAYLOAD = 320; + error InvalidSolanaEnvelope(); + + function encode(bytes memory message, bytes32 configuration) internal pure returns (bytes memory) { + if (configuration == 0 || message.length < 36 || message.length > 36 + MAX_PAYLOAD + || uint8(message[32]) != 0 || uint8(message[33]) != 1) revert InvalidSolanaEnvelope(); + uint256 n = message.length; + return abi.encodePacked( + bytes1(0), bytes1(uint8(n)), bytes1(uint8(n >> 8)), bytes2(0), message, + hex"01000000", configuration, bytes1(0) + ); + } +} diff --git a/src/integrations/oracles/common/BoundedOracle.sol b/src/integrations/oracles/common/BoundedOracle.sol new file mode 100644 index 00000000..27e87fc4 --- /dev/null +++ b/src/integrations/oracles/common/BoundedOracle.sol @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { IAttester } from "../../../interfaces/IAttester.sol"; +import { MessageEncodingLib } from "../../../libs/MessageEncodingLib.sol"; +import { BaseInputOracle } from "../../../oracles/BaseInputOracle.sol"; + +/// Shared Stellar-compatible admission limits; transport authentication belongs to each adapter. +abstract contract BoundedOracle is BaseInputOracle { + error InvalidConfiguration(); + error UnknownChain(); + error MessageLimit(); + error NotAttested(); + error InvalidOptions(); + uint256 public constant MAX_PAYLOADS = 4; + uint256 public constant MAX_PAYLOAD = 684; + uint256 public constant MAX_MESSAGE = 2778; + + function _encode( + address source, + bytes[] calldata payloads + ) internal pure returns (bytes memory) { + if (source == address(0) || payloads.length == 0 || payloads.length > MAX_PAYLOADS) revert MessageLimit(); + for (uint256 i; i < payloads.length; ++i) { + if (payloads[i].length > MAX_PAYLOAD) revert MessageLimit(); + } + return MessageEncodingLib.encodeMessage(bytes32(uint256(uint160(source))), payloads); + } + + function _export( + address source, + bytes[] calldata payloads + ) internal view returns (bytes memory message) { + message = _encode(source, payloads); + if (!IAttester(source).hasAttested(payloads)) revert NotAttested(); + } + + function _record( + uint256 chain, + bytes32 sender, + bytes calldata message + ) internal { + if (message.length < 34 || message.length > MAX_MESSAGE) revert MessageLimit(); + uint256 count = uint16(bytes2(message[32:34])); + if (count == 0 || count > MAX_PAYLOADS) revert MessageLimit(); + uint256 cursor = 34; + for (uint256 i; i < count; ++i) { + uint256 size = uint16(bytes2(message[cursor:cursor + 2])); + if (size > MAX_PAYLOAD) revert MessageLimit(); + cursor += 2 + size; + } + (bytes32 application, bytes32[] memory hashes) = MessageEncodingLib.getHashesOfEncodedPayloads(message); + for (uint256 i; i < hashes.length; ++i) { + if (!_attestations[chain][sender][application][hashes[i]]) { + _attestations[chain][sender][application][hashes[i]] = true; + emit OutputProven(chain, sender, application, hashes[i]); + } + } + } + + /// A single Type-3 lzReceive option, positive gas, zero receiver value. No compose/drop/ordered options. + function _checkOptions( + bytes calldata options + ) internal pure { + if (options.length != 22 || bytes6(options[:6]) != hex"000301001101" || uint128(bytes16(options[6:22])) == 0) { + revert InvalidOptions(); + } + } +} diff --git a/src/integrations/oracles/common/OracleAddress.sol b/src/integrations/oracles/common/OracleAddress.sol new file mode 100644 index 00000000..05f8d160 --- /dev/null +++ b/src/integrations/oracles/common/OracleAddress.sol @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +/// Axelar native strings <-> OIF raw identifiers. Stellar CRC16-XModem is stored little-endian. +library OracleAddress { + enum Kind { + Evm, + Stellar, + Solana + } + error InvalidOracleAddress(); + bytes internal constant BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + bytes internal constant HEX = "0123456789abcdef"; + bytes internal constant BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + + function encode( + bytes32 id, + Kind kind + ) internal pure returns (string memory) { + if (kind == Kind.Solana) { + uint256 n = uint256(id); + bytes memory digits = new bytes(44); + uint256 length; + while (n != 0) { + digits[length++] = BASE58[n % 58]; + n /= 58; + } + uint256 zeros; + while (zeros < 32 && id[zeros] == 0) ++zeros; + bytes memory out58 = new bytes(zeros + length); + for (uint256 i; i < zeros; ++i) out58[i] = "1"; + for (uint256 i; i < length; ++i) out58[zeros + i] = digits[length - 1 - i]; + return string(out58); + } + if (kind == Kind.Evm) { + if (uint256(id) >> 160 != 0) revert InvalidOracleAddress(); + bytes memory evm = new bytes(42); + evm[0] = "0"; + evm[1] = "x"; + for (uint256 i; i < 20; ++i) { + uint8 b = uint8(id[i + 12]); + evm[2 + i * 2] = HEX[b >> 4]; + evm[3 + i * 2] = HEX[b & 15]; + } + return string(evm); + } + bytes memory raw = abi.encodePacked(bytes1(0x10), id, bytes2(0)); + uint16 crc = _crc(raw); + raw[33] = bytes1(uint8(crc)); + raw[34] = bytes1(uint8(crc >> 8)); + bytes memory out = new bytes(56); + uint256 acc; + uint256 bits; + uint256 j; + for (uint256 i; i < 35; ++i) { + acc = (acc << 8) | uint8(raw[i]); + bits += 8; + while (bits >= 5) { + bits -= 5; + out[j++] = BASE32[(acc >> bits) & 31]; + } + } + return string(out); + } + + function decode( + string calldata value, + Kind kind + ) internal pure returns (bytes32 id) { + bytes calldata input = bytes(value); + if (kind == Kind.Solana) { + if (input.length < 32 || input.length > 44) revert InvalidOracleAddress(); + uint256 n; + for (uint256 i; i < input.length; ++i) { + uint256 digit; + while (digit < 58 && BASE58[digit] != input[i]) ++digit; + if (digit == 58 || n > (type(uint256).max - digit) / 58) revert InvalidOracleAddress(); + n = n * 58 + digit; + } + id = bytes32(n); + if (keccak256(bytes(encode(id, kind))) != keccak256(input)) revert InvalidOracleAddress(); + return id; + } + if (kind == Kind.Evm) { + if (input.length != 42 || input[0] != "0" || input[1] != "x") revert InvalidOracleAddress(); + uint256 n; + for (uint256 i = 2; i < 42; ++i) { + n = (n << 4) | _hex(uint8(input[i])); + } + return bytes32(n); + } + if (input.length != 56) revert InvalidOracleAddress(); + bytes memory raw = new bytes(35); + uint256 acc; + uint256 bits; + uint256 j; + for (uint256 i; i < 56; ++i) { + uint8 c = uint8(input[i]); + uint256 v; + if (c >= 65 && c <= 90) v = c - 65; + else if (c >= 50 && c <= 55) v = c - 24; + else revert InvalidOracleAddress(); + acc = (acc << 5) | v; + bits += 5; + if (bits >= 8) { + bits -= 8; + raw[j++] = bytes1(uint8(acc >> bits)); + } + } + if (raw[0] != 0x10 || _crc(raw) != (uint16(uint8(raw[33])) | uint16(uint8(raw[34])) << 8)) { + revert InvalidOracleAddress(); + } + assembly ("memory-safe") { id := mload(add(raw, 33)) } + } + + function _hex( + uint8 c + ) private pure returns (uint256) { + if (c >= 48 && c <= 57) return c - 48; + if (c >= 65 && c <= 70) return c - 55; + if (c >= 97 && c <= 102) return c - 87; + revert InvalidOracleAddress(); + } + + function _crc( + bytes memory data + ) private pure returns (uint16 crc) { + for (uint256 i; i < 33; ++i) { + crc ^= uint16(uint8(data[i])) << 8; + for (uint256 k; k < 8; ++k) { + crc = crc & 0x8000 != 0 ? (crc << 1) ^ 0x1021 : crc << 1; + } + } + } +} diff --git a/src/integrations/oracles/layerzero/LayerZeroOracle.sol b/src/integrations/oracles/layerzero/LayerZeroOracle.sol new file mode 100644 index 00000000..649d5712 --- /dev/null +++ b/src/integrations/oracles/layerzero/LayerZeroOracle.sol @@ -0,0 +1,202 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { BoundedOracle } from "../common/BoundedOracle.sol"; + +struct Origin { + uint32 srcEid; + bytes32 sender; + uint64 nonce; +} + +struct MessagingFee { + uint256 nativeFee; + uint256 lzTokenFee; +} + +struct MessagingReceipt { + bytes32 guid; + uint64 nonce; + MessagingFee fee; +} + +struct MessagingParams { + uint32 dstEid; + bytes32 receiver; + bytes message; + bytes options; + bool payInLzToken; +} + +struct SetConfigParam { + uint32 eid; + uint32 configType; + bytes config; +} + +interface IOracleEndpointV2 { + function quote( + MessagingParams calldata params, + address sender + ) external view returns (MessagingFee memory); + function send( + MessagingParams calldata params, + address refundAddress + ) external payable returns (MessagingReceipt memory); + function setSendLibrary( + address oapp, + uint32 eid, + address lib + ) external; + function setReceiveLibrary( + address oapp, + uint32 eid, + address lib, + uint256 gracePeriod + ) external; + function setConfig( + address oapp, + address lib, + SetConfigParam[] calldata params + ) external; +} + +/// Transparent OApp: authenticated Origin.sender is preserved, never replaced by a configured peer. +contract LayerZeroOracle is BoundedOracle { + struct UlnConfig { + uint64 confirmations; + uint8 requiredDVNCount; + uint8 optionalDVNCount; + uint8 optionalDVNThreshold; + address[] requiredDVNs; + address[] optionalDVNs; + } + + struct ExecutorConfig { + uint32 maxMessageSize; + address executor; + } + + struct Chain { + uint32 eid; + uint256 chainId; + address sendLibrary; + address receiveLibrary; + address executor; + uint64 sendConfirmations; + uint64 receiveConfirmations; + address[] sendDvns; + address[] receiveDvns; + } + IOracleEndpointV2 public immutable endpoint; + mapping(uint32 => uint256) public chainIds; + error OnlyEndpoint(); + error UnexpectedValue(); + + constructor( + address endpoint_, + Chain[] memory chains + ) { + if (endpoint_.code.length == 0 || chains.length == 0 || chains.length > 16) revert InvalidConfiguration(); + endpoint = IOracleEndpointV2(endpoint_); + for (uint256 i; i < chains.length; ++i) { + Chain memory c = chains[i]; + if ( + c.eid == 0 || c.chainId == 0 || chainIds[c.eid] != 0 || c.executor == address(0) + || c.sendLibrary == address(0) || c.receiveLibrary == address(0) + ) revert InvalidConfiguration(); + for (uint256 j; j < i; ++j) { + if (chains[j].chainId == c.chainId) revert InvalidConfiguration(); + } + chainIds[c.eid] = c.chainId; + endpoint.setSendLibrary(address(this), c.eid, c.sendLibrary); + endpoint.setReceiveLibrary(address(this), c.eid, c.receiveLibrary, 0); + SetConfigParam[] memory sendConfig = new SetConfigParam[](2); + sendConfig[0] = SetConfigParam(c.eid, 1, abi.encode(ExecutorConfig(uint32(MAX_MESSAGE), c.executor))); + sendConfig[1] = SetConfigParam(c.eid, 2, _uln(c.sendConfirmations, c.sendDvns)); + endpoint.setConfig(address(this), c.sendLibrary, sendConfig); + SetConfigParam[] memory receiveConfig = new SetConfigParam[](1); + receiveConfig[0] = SetConfigParam(c.eid, 2, _uln(c.receiveConfirmations, c.receiveDvns)); + endpoint.setConfig(address(this), c.receiveLibrary, receiveConfig); + } + } + + function _uln( + uint64 confirmations, + address[] memory dvns + ) private pure returns (bytes memory) { + if (confirmations == 0 || dvns.length == 0 || dvns.length > 127) revert InvalidConfiguration(); + address previous; + for (uint256 i; i < dvns.length; ++i) { + if (dvns[i] <= previous) revert InvalidConfiguration(); + previous = dvns[i]; + } + // NIL_DVN_COUNT explicitly disables optional DVNs rather than inheriting a mutable default. + return abi.encode(UlnConfig(confirmations, uint8(dvns.length), 255, 0, dvns, new address[](0))); + } + + function quote( + uint32 dstEid, + bytes32 recipientOracle, + address source, + bytes[] calldata payloads, + bytes calldata options + ) external view returns (MessagingFee memory) { + _checkDestination(dstEid, options); + return endpoint.quote( + MessagingParams(dstEid, recipientOracle, _encode(source, payloads), options, false), address(this) + ); + } + + function submit( + uint32 dstEid, + bytes32 recipientOracle, + address source, + bytes[] calldata payloads, + bytes calldata options + ) external payable returns (MessagingReceipt memory) { + _checkDestination(dstEid, options); + return endpoint.send{ value: msg.value }( + MessagingParams(dstEid, recipientOracle, _export(source, payloads), options, false), msg.sender + ); + } + + function _checkDestination( + uint32 eid, + bytes calldata options + ) private view { + if (chainIds[eid] == 0) revert UnknownChain(); + _checkOptions(options); + } + + function allowInitializePath( + Origin calldata origin + ) external view returns (bool) { + return chainIds[origin.srcEid] != 0; + } + + function nextNonce( + uint32, + bytes32 + ) external pure returns (uint64) { + return 0; + } + + function oAppVersion() external pure returns (uint64, uint64) { + return (1, 1); + } + + function lzReceive( + Origin calldata origin, + bytes32, + bytes calldata message, + address, + bytes calldata + ) external payable { + if (msg.sender != address(endpoint)) revert OnlyEndpoint(); + if (msg.value != 0) revert UnexpectedValue(); + uint256 chain = chainIds[origin.srcEid]; + if (chain == 0) revert UnknownChain(); + _record(chain, origin.sender, message); + } +} diff --git a/src/libs/MessageEncodingLib.sol b/src/libs/MessageEncodingLib.sol index d0f20404..de9b7b0c 100644 --- a/src/libs/MessageEncodingLib.sol +++ b/src/libs/MessageEncodingLib.sol @@ -23,6 +23,7 @@ pragma solidity ^0.8.26; library MessageEncodingLib { error TooLargePayload(uint256 size); error TooManyPayloads(uint256 size); + error TrailingMessageBytes(); /** * @notice Encodes a number of payloads into a single message prepended as reported by an application. @@ -69,6 +70,7 @@ library MessageEncodingLib { bytes32 hashedPayload = keccak256(payload); payloadHashes[index] = hashedPayload; } + if (pointer != encodedPayload.length) revert TrailingMessageBytes(); } } } diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol new file mode 100644 index 00000000..706bcf5d --- /dev/null +++ b/test/oracle/transport/StellarTransport.t.sol @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; +import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; +import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { EndpointFixture, GatewayFixture } from "./TransportFixtures.sol"; +import { Test } from "forge-std/Test.sol"; + +contract BoundAttester { + address public oracle; + + function setOracle( + address o + ) external { + oracle = o; + } + + function hasAttested( + bytes[] calldata + ) external view returns (bool) { + return msg.sender == oracle; + } +} + +contract StellarTransportTest is Test { + GatewayFixture gateway; + EndpointFixture endpoint; + AxelarOracle axelar; + LayerZeroOracle lz; + BoundAttester source; + bytes32 constant SENDER = keccak256("stellar oracle"); + bytes32 constant APP = keccak256("stellar settler"); + uint256 constant CHAIN = 0x53544c; + + function setUp() public { + gateway = new GatewayFixture(); + endpoint = new EndpointFixture(); + source = new BoundAttester(); + AxelarOracle.Chain[] memory a = new AxelarOracle.Chain[](1); + a[0] = AxelarOracle.Chain("stellar", CHAIN, OracleAddress.Kind.Stellar); + axelar = new AxelarOracle(address(gateway), address(gateway), a); + LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); + address[] memory dvns = new address[](1); + dvns[0] = address(0x1234); + c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), 1, 1, dvns, dvns); + lz = new LayerZeroOracle(address(endpoint), c); + } + receive() external payable { } + + function payloads() internal pure returns (bytes[] memory p) { + p = new bytes[](2); + p[0] = hex"d1252dff012345"; + p[1] = hex"830c1e1c987654"; + } + + function encode( + bytes32 application, + bytes[] calldata p + ) external pure returns (bytes memory) { + return MessageEncodingLib.encodeMessage(application, p); + } + + function decodeAddress( + string calldata value, + OracleAddress.Kind kind + ) external pure returns (bytes32) { + return OracleAddress.decode(value, kind); + } + + function decode( + bytes calldata b + ) external pure returns (bytes32, bytes32[] memory) { + return MessageEncodingLib.getHashesOfEncodedPayloads(b); + } + + function options() internal pure returns (bytes memory) { + return abi.encodePacked(hex"000301001101", uint128(200_000)); + } + + function testFuzzStellarAddressRoundtrip( + bytes32 id + ) public { + assertEq( + this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Stellar), OracleAddress.Kind.Stellar), id + ); + } + + function testFuzzSolanaAddressRoundtrip(bytes32 id) public { + assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); + } + + function testSolanaEnvelopeAndExplicitSelfRelay() public { + AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); + routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); + AxelarOracle oracle = new AxelarOracle(address(gateway), address(gateway), routes); + source.setOracle(address(oracle)); + bytes[] memory p = new bytes[](1); + p[0] = new bytes(320); + bytes32 config = keccak256("config"); + oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + assertEq(gateway.paid(), 0); + assertEq(gateway.lastSender(), address(oracle)); + assertEq(gateway.lastMessage(), bytes.concat(hex"0064010000", this.encode(bytes32(uint256(uint160(address(source)))), p), hex"01000000", config, hex"00")); + assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Solana)); + vm.expectRevert(); + oracle.submit{value: 1}("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + vm.expectRevert(); + oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); + oracle.submit{value: 10}("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); + assertEq(gateway.paid(), 10); + vm.expectRevert(); + oracle.submit("solana", SENDER, address(source), p, bytes32(0), AxelarOracle.DeliveryMode.SelfRelay); + p[0] = new bytes(321); + vm.expectRevert(); + oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + vm.expectRevert(); + this.decodeAddress("111111111111111111111111111111111", OracleAddress.Kind.Solana); + vm.expectRevert(); + this.decodeAddress("01111111111111111111111111111111", OracleAddress.Kind.Solana); + } + + function testPublishedStrKeyAndBadChecksum() public { + string memory zero = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4"; + assertEq(OracleAddress.encode(bytes32(0), OracleAddress.Kind.Stellar), zero); + assertEq(this.decodeAddress(zero, OracleAddress.Kind.Stellar), bytes32(0)); + vm.expectRevert(); + this.decodeAddress("CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC5", OracleAddress.Kind.Stellar); + vm.expectRevert(); + this.decodeAddress("GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", OracleAddress.Kind.Stellar); + } + + function testAxelarExportAndAuthenticatedNamespace() public { + source.setOracle(address(axelar)); + axelar.submit{ value: 10 }("stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + assertEq(gateway.lastSender(), address(axelar)); + assertEq(gateway.lastRefund(), address(this)); + assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar)); + bytes memory m = this.encode(APP, payloads()); + string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); + vm.expectRevert(); + axelar.execute(bytes32(0), "stellar", sender, m); + gateway.approve(bytes32(0), "stellar", sender, address(axelar), m); + axelar.execute(bytes32(0), "stellar", sender, m); + assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); + assertFalse(axelar.isProven(CHAIN, bytes32(uint256(1)), APP, keccak256(payloads()[0]))); + vm.expectRevert(); + axelar.execute(bytes32(0), "stellar", sender, m); + gateway.approve(bytes32(uint256(1)), "stellar", sender, address(axelar), m); + axelar.execute(bytes32(uint256(1)), "stellar", sender, m); + } + + function testLayerZeroExportReceiveReplayAndFees() public { + source.setOracle(address(lz)); + uint256 beforeBalance = address(this).balance; + lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); + assertEq(address(this).balance, beforeBalance - 10); + assertEq(endpoint.lastRecipient(), SENDER); + bytes memory m = this.encode(APP, payloads()); + Origin memory o = Origin(30600, SENDER, 1); + vm.expectRevert(); + lz.lzReceive(o, bytes32(0), m, address(this), ""); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); + vm.expectRevert(); + endpoint.deliver(address(lz), o, bytes32(0), m); + } + + function testBoundsMalformedRollbackAndExportNamespace() public { + bytes memory m = bytes.concat(this.encode(APP, payloads()), hex"00"); + string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); + gateway.approve(bytes32(0), "stellar", sender, address(axelar), m); + bytes32 key = keccak256(abi.encode(bytes32(0), "stellar", sender, address(axelar), keccak256(m))); + vm.expectRevert(); + axelar.execute(bytes32(0), "stellar", sender, m); + assertTrue(gateway.approvals(key)); + vm.expectRevert(); + this.decode(m); + vm.expectRevert(); + axelar.submit{ value: 10 }("stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + source.setOracle(address(axelar)); + bytes[] memory big = new bytes[](1); + big[0] = new bytes(685); + vm.expectRevert(); + axelar.submit{ value: 10 }("stellar", SENDER, address(source), big, bytes32(0), AxelarOracle.DeliveryMode.Relayed); + vm.expectRevert(); + lz.quote(30600, SENDER, address(source), payloads(), hex""); + vm.expectRevert(); + lz.quote(999, SENDER, address(source), payloads(), options()); + } + + function testMaximumBatchAndTupleChecks() public { + bytes[] memory p = new bytes[](4); + for (uint256 i; i < 4; ++i) { + p[i] = new bytes(684); + p[i][0] = bytes1(uint8(i)); + } + bytes memory m = this.encode(APP, p); + assertEq(m.length, 2778); + Origin memory o = Origin(30600, SENDER, 1); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + bytes memory proofs; + for (uint256 i; i < 4; ++i) { + proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); + } + lz.efficientRequireProven(proofs); + lz.efficientRequireProven(""); + vm.expectRevert(); + lz.efficientRequireProven(bytes.concat(proofs, hex"00")); + } +} diff --git a/test/oracle/transport/TransportFixtures.sol b/test/oracle/transport/TransportFixtures.sol new file mode 100644 index 00000000..5f0f38e0 --- /dev/null +++ b/test/oracle/transport/TransportFixtures.sol @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { + LayerZeroOracle, + MessagingFee, + MessagingParams, + MessagingReceipt, + Origin, + SetConfigParam +} from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; + +/// Test-only verification boundary. Approvals bind every provider-authenticated field and are consumed atomically. +contract GatewayFixture { + mapping(bytes32 => bool) public approvals; + bytes public lastMessage; + string public lastDestination; + address public lastSender; + address public lastRefund; + uint256 public paid; + + function approve( + bytes32 command, + string memory chain, + string memory sender, + address receiver, + bytes memory payload + ) external { + approvals[keccak256(abi.encode(command, chain, sender, receiver, keccak256(payload)))] = true; + } + + function validateContractCall( + bytes32 command, + string calldata chain, + string calldata sender, + bytes32 hash + ) external returns (bool) { + bytes32 k = keccak256(abi.encode(command, chain, sender, msg.sender, hash)); + bool valid = approvals[k]; + delete approvals[k]; + return valid; + } + + function callContract( + string calldata, + string calldata destination, + bytes calldata payload + ) external { + lastMessage = payload; + lastDestination = destination; + lastSender = msg.sender; + } + + function payNativeGasForContractCall( + address, + string calldata, + string calldata, + bytes calldata, + address refund + ) external payable { + paid += msg.value; + lastRefund = refund; + } +} + +contract EndpointFixture { + mapping(bytes32 => bool) public approvals; + mapping(bytes32 => bytes) public configs; + bytes public lastMessage; + bytes32 public lastRecipient; + address public lastSender; + uint64 public nonce; + + function setSendLibrary( + address oapp, + uint32 eid, + address lib + ) external { + require(msg.sender == oapp); + configs[keccak256(abi.encode(oapp, eid, "send"))] = abi.encode(lib); + } + + function setReceiveLibrary( + address oapp, + uint32 eid, + address lib, + uint256 grace + ) external { + require(msg.sender == oapp && grace == 0); + configs[keccak256(abi.encode(oapp, eid, "receive"))] = abi.encode(lib); + } + + function setConfig( + address oapp, + address lib, + SetConfigParam[] calldata params + ) external { + require(msg.sender == oapp); + for (uint256 i; i < params.length; ++i) { + configs[keccak256(abi.encode(oapp, lib, params[i].eid, params[i].configType))] = params[i].config; + } + } + + function quote( + MessagingParams calldata, + address + ) external pure returns (MessagingFee memory) { + return MessagingFee(10, 0); + } + + function send( + MessagingParams calldata p, + address refund + ) external payable returns (MessagingReceipt memory) { + require(msg.value >= 10 && !p.payInLzToken); + lastMessage = p.message; + lastRecipient = p.receiver; + lastSender = msg.sender; + if (msg.value > 10) { + (bool ok,) = refund.call{ value: msg.value - 10 }(""); + require(ok); + } + return MessagingReceipt(keccak256(abi.encode(msg.sender, ++nonce, p)), nonce, MessagingFee(10, 0)); + } + + function approve( + address receiver, + Origin memory origin, + bytes32 guid, + bytes memory message + ) external { + require(LayerZeroOracle(receiver).allowInitializePath(origin)); + approvals[keccak256(abi.encode(receiver, origin, guid, message))] = true; + } + + function deliver( + address receiver, + Origin memory origin, + bytes32 guid, + bytes memory message + ) external { + bytes32 key = keccak256(abi.encode(receiver, origin, guid, message)); + require(approvals[key], "unverified"); + delete approvals[key]; + LayerZeroOracle(receiver).lzReceive(origin, guid, message, msg.sender, ""); + } +} From bb1cd0717dd08e1f29a8da9db1a4f8eb214719b8 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 30 Sep 2026 17:32:51 +0400 Subject: [PATCH 02/14] fix(layerzero): reject NIL confirmations in pinned ULN config --- .../oracles/layerzero/LayerZeroOracle.sol | 5 ++- test/oracle/transport/StellarTransport.t.sol | 45 ++++++++++++++++--- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/src/integrations/oracles/layerzero/LayerZeroOracle.sol b/src/integrations/oracles/layerzero/LayerZeroOracle.sol index 649d5712..07f1c130 100644 --- a/src/integrations/oracles/layerzero/LayerZeroOracle.sol +++ b/src/integrations/oracles/layerzero/LayerZeroOracle.sol @@ -125,7 +125,10 @@ contract LayerZeroOracle is BoundedOracle { uint64 confirmations, address[] memory dvns ) private pure returns (bytes memory) { - if (confirmations == 0 || dvns.length == 0 || dvns.length > 127) revert InvalidConfiguration(); + // UlnBase reads type(uint64).max (NIL_CONFIRMATIONS) in an OApp config as literal zero confirmations. + if (confirmations == 0 || confirmations == type(uint64).max || dvns.length == 0 || dvns.length > 127) { + revert InvalidConfiguration(); + } address previous; for (uint256 i; i < dvns.length; ++i) { if (dvns[i] <= previous) revert InvalidConfiguration(); diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol index 706bcf5d..1c13b97f 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/StellarTransport.t.sol @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; @@ -86,7 +87,9 @@ contract StellarTransportTest is Test { ); } - function testFuzzSolanaAddressRoundtrip(bytes32 id) public { + function testFuzzSolanaAddressRoundtrip( + bytes32 id + ) public { assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); } @@ -101,13 +104,22 @@ contract StellarTransportTest is Test { oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); assertEq(gateway.paid(), 0); assertEq(gateway.lastSender(), address(oracle)); - assertEq(gateway.lastMessage(), bytes.concat(hex"0064010000", this.encode(bytes32(uint256(uint160(address(source)))), p), hex"01000000", config, hex"00")); + assertEq( + gateway.lastMessage(), + bytes.concat( + hex"0064010000", + this.encode(bytes32(uint256(uint160(address(source)))), p), + hex"01000000", + config, + hex"00" + ) + ); assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Solana)); vm.expectRevert(); - oracle.submit{value: 1}("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + oracle.submit{ value: 1 }("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); vm.expectRevert(); oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); - oracle.submit{value: 10}("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); + oracle.submit{ value: 10 }("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); assertEq(gateway.paid(), 10); vm.expectRevert(); oracle.submit("solana", SENDER, address(source), p, bytes32(0), AxelarOracle.DeliveryMode.SelfRelay); @@ -132,7 +144,9 @@ contract StellarTransportTest is Test { function testAxelarExportAndAuthenticatedNamespace() public { source.setOracle(address(axelar)); - axelar.submit{ value: 10 }("stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + axelar.submit{ value: 10 }( + "stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); assertEq(gateway.lastSender(), address(axelar)); assertEq(gateway.lastRefund(), address(this)); assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar)); @@ -178,18 +192,35 @@ contract StellarTransportTest is Test { vm.expectRevert(); this.decode(m); vm.expectRevert(); - axelar.submit{ value: 10 }("stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + axelar.submit{ value: 10 }( + "stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); source.setOracle(address(axelar)); bytes[] memory big = new bytes[](1); big[0] = new bytes(685); vm.expectRevert(); - axelar.submit{ value: 10 }("stellar", SENDER, address(source), big, bytes32(0), AxelarOracle.DeliveryMode.Relayed); + axelar.submit{ value: 10 }( + "stellar", SENDER, address(source), big, bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); vm.expectRevert(); lz.quote(30600, SENDER, address(source), payloads(), hex""); vm.expectRevert(); lz.quote(999, SENDER, address(source), payloads(), options()); } + function testLayerZeroRejectsNilConfirmations() public { + address[] memory dvns = new address[](1); + dvns[0] = address(0x1234); + LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); + c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), type(uint64).max, 1, dvns, dvns); + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + new LayerZeroOracle(address(endpoint), c); + c[0].sendConfirmations = 1; + c[0].receiveConfirmations = type(uint64).max; + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + new LayerZeroOracle(address(endpoint), c); + } + function testMaximumBatchAndTupleChecks() public { bytes[] memory p = new bytes[](4); for (uint256 i; i < 4; ++i) { From 2531f6ede76b4d1ae806702c292ff922458e8649 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 10:18:07 +0400 Subject: [PATCH 03/14] feat(axelar): permissionless Solana sender cache for execute --- .../oracles/axelar/AxelarOracle.sol | 42 ++++++++++++++++--- test/oracle/transport/StellarTransport.t.sol | 32 ++++++++++++++ 2 files changed, 68 insertions(+), 6 deletions(-) diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index cdbc4d5a..23ee6f21 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -31,7 +31,11 @@ interface IAxelarNativeGasService { /// Transparent, immutable Axelar GMP oracle. Based on OIF PR #137; supports Stellar sender identities. contract AxelarOracle is BoundedOracle { - enum DeliveryMode { Relayed, SelfRelay } + enum DeliveryMode { + Relayed, + SelfRelay + } + struct Chain { string name; uint256 chainId; @@ -45,8 +49,11 @@ contract AxelarOracle is BoundedOracle { IAxelarMessageGateway public immutable gateway; IAxelarNativeGasService public immutable gasService; mapping(bytes32 => Route) private routes; + /// Permissionless memo of canonical Solana base58 decodings: keccak256(address string) => raw ID. + mapping(bytes32 => bytes32) public solanaAddresses; error NotApproved(); error InvalidFee(); + event SolanaAddressCached(bytes32 indexed id, string value); constructor( address gateway_, @@ -89,18 +96,30 @@ contract AxelarOracle is BoundedOracle { Route memory r = route(destinationChain); string memory recipient = OracleAddress.encode(recipientOracle, r.kind); bytes memory message = _export(source, payloads); - if (r.kind == OracleAddress.Kind.Solana) { - message = SolanaEnvelope.encode(message, destinationConfig); - } else if (destinationConfig != 0) revert InvalidConfiguration(); + if (r.kind == OracleAddress.Kind.Solana) message = SolanaEnvelope.encode(message, destinationConfig); + else if (destinationConfig != 0) revert InvalidConfiguration(); if (deliveryMode == DeliveryMode.Relayed) { if (msg.value == 0) revert InvalidFee(); gasService.payNativeGasForContractCall{ value: msg.value }( address(this), destinationChain, recipient, message, msg.sender ); - } else if (msg.value != 0) revert InvalidFee(); + } else if (msg.value != 0) { + revert InvalidFee(); + } gateway.callContract(destinationChain, recipient, message); } + /// Decode a canonical Solana base58 address once (~0.7M gas) and memoize it, so every later + /// `execute` from that sender reads one slot instead of decoding. Anyone may pay for this: + /// the entry is exactly what `OracleAddress.decode` returns, so caching never changes results. + function cacheSolanaAddress( + string calldata value + ) external returns (bytes32 id) { + id = OracleAddress.decode(value, OracleAddress.Kind.Solana); + solanaAddresses[keccak256(bytes(value))] = id; + emit SolanaAddressCached(id, value); + } + /// Anyone may execute, but only the gateway can approve the exact destination-bound message. function execute( bytes32 commandId, @@ -109,10 +128,21 @@ contract AxelarOracle is BoundedOracle { bytes calldata payload ) external { Route memory r = route(sourceChain); - bytes32 sender = OracleAddress.decode(sourceAddress, r.kind); + bytes32 sender = r.kind == OracleAddress.Kind.Solana + ? _solanaSender(sourceAddress) + : OracleAddress.decode(sourceAddress, r.kind); if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { revert NotApproved(); } _record(r.chainId, sender, payload); } + + /// Cached decoding when present; the all-zero ID is never distinguishable from absent, so it + /// always takes the full decode. + function _solanaSender( + string calldata value + ) private view returns (bytes32 id) { + id = solanaAddresses[keccak256(bytes(value))]; + if (id == 0) id = OracleAddress.decode(value, OracleAddress.Kind.Solana); + } } diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol index 1c13b97f..87549a1f 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/StellarTransport.t.sol @@ -164,6 +164,38 @@ contract StellarTransportTest is Test { axelar.execute(bytes32(uint256(1)), "stellar", sender, m); } + function testSolanaSenderCacheIsPermissionlessAndCheapensExecute() public { + AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); + routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); + AxelarOracle oracle = new AxelarOracle(address(gateway), address(gateway), routes); + bytes[] memory p = new bytes[](1); + p[0] = hex"d1252dff012345"; + bytes memory m = this.encode(APP, p); + string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Solana); + + gateway.approve(bytes32(0), "solana", sender, address(oracle), m); + uint256 g = gasleft(); + oracle.execute(bytes32(0), "solana", sender, m); + uint256 uncached = g - gasleft(); + + // Non-canonical spellings are rejected, so they can never be cached. + vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); + oracle.cacheSolanaAddress(string.concat("1", sender)); + vm.prank(address(0xBEEF)); + assertEq(oracle.cacheSolanaAddress(sender), SENDER); + assertEq(oracle.solanaAddresses(keccak256(bytes(sender))), SENDER); + + // A fresh proof, so both measured calls write a new tuple. + p[0] = hex"830c1e1c987654"; + m = this.encode(APP, p); + gateway.approve(bytes32(uint256(1)), "solana", sender, address(oracle), m); + g = gasleft(); + oracle.execute(bytes32(uint256(1)), "solana", sender, m); + uint256 cached = g - gasleft(); + assertTrue(oracle.isProven(9, SENDER, APP, keccak256(p[0]))); + assertLt(cached * 5, uncached); + } + function testLayerZeroExportReceiveReplayAndFees() public { source.setOracle(address(lz)); uint256 beforeBalance = address(this).balance; From bbeec00afe737c1e596490b1130b3234b30cfbc5 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 10:42:49 +0400 Subject: [PATCH 04/14] feat(axelar): memoize Solana senders on first approved execute --- .../oracles/axelar/AxelarOracle.sol | 34 +++++----- test/oracle/transport/StellarTransport.t.sol | 63 +++++++++++++------ 2 files changed, 64 insertions(+), 33 deletions(-) diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index 23ee6f21..1098c3b7 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -109,9 +109,9 @@ contract AxelarOracle is BoundedOracle { gateway.callContract(destinationChain, recipient, message); } - /// Decode a canonical Solana base58 address once (~0.7M gas) and memoize it, so every later - /// `execute` from that sender reads one slot instead of decoding. Anyone may pay for this: - /// the entry is exactly what `OracleAddress.decode` returns, so caching never changes results. + /// Decode a canonical Solana base58 address and memoize it before any message arrives, so even + /// the first `execute` from that sender skips the decode. Anyone may pay for this: the entry is + /// exactly what `OracleAddress.decode` returns, so caching never changes results. function cacheSolanaAddress( string calldata value ) external returns (bytes32 id) { @@ -121,6 +121,7 @@ contract AxelarOracle is BoundedOracle { } /// Anyone may execute, but only the gateway can approve the exact destination-bound message. + /// A Solana sender missing from the memo is decoded once and memoized after validation. function execute( bytes32 commandId, string calldata sourceChain, @@ -128,21 +129,24 @@ contract AxelarOracle is BoundedOracle { bytes calldata payload ) external { Route memory r = route(sourceChain); - bytes32 sender = r.kind == OracleAddress.Kind.Solana - ? _solanaSender(sourceAddress) - : OracleAddress.decode(sourceAddress, r.kind); + bytes32 sender; + bytes32 cacheKey; + if (r.kind == OracleAddress.Kind.Solana) { + cacheKey = keccak256(bytes(sourceAddress)); + sender = solanaAddresses[cacheKey]; + if (sender != 0) cacheKey = 0; + else sender = OracleAddress.decode(sourceAddress, r.kind); + } else { + sender = OracleAddress.decode(sourceAddress, r.kind); + } if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { revert NotApproved(); } + // The all-zero ID is indistinguishable from absent, so it is never memoized. + if (cacheKey != 0 && sender != 0) { + solanaAddresses[cacheKey] = sender; + emit SolanaAddressCached(sender, sourceAddress); + } _record(r.chainId, sender, payload); } - - /// Cached decoding when present; the all-zero ID is never distinguishable from absent, so it - /// always takes the full decode. - function _solanaSender( - string calldata value - ) private view returns (bytes32 id) { - id = solanaAddresses[keccak256(bytes(value))]; - if (id == 0) id = OracleAddress.decode(value, OracleAddress.Kind.Solana); - } } diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol index 87549a1f..e74a0d54 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/StellarTransport.t.sol @@ -164,36 +164,63 @@ contract StellarTransportTest is Test { axelar.execute(bytes32(uint256(1)), "stellar", sender, m); } - function testSolanaSenderCacheIsPermissionlessAndCheapensExecute() public { + function solanaOracle() internal returns (AxelarOracle) { AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); - AxelarOracle oracle = new AxelarOracle(address(gateway), address(gateway), routes); + return new AxelarOracle(address(gateway), address(gateway), routes); + } + + /// Approve and execute one fresh Solana message with cold oracle and gateway storage. + /// Returns call-frame gas under the fixture gateway; excludes intrinsic gas. + function executeCold( + AxelarOracle oracle, + uint256 commandId, + string memory sender, + bytes memory payload + ) internal returns (uint256 used) { bytes[] memory p = new bytes[](1); - p[0] = hex"d1252dff012345"; + p[0] = payload; bytes memory m = this.encode(APP, p); + gateway.approve(bytes32(commandId), "solana", sender, address(oracle), m); + vm.cool(address(oracle)); + vm.cool(address(gateway)); + uint256 g = gasleft(); + oracle.execute(bytes32(commandId), "solana", sender, m); + used = g - gasleft(); + assertTrue(oracle.isProven(9, SENDER, APP, keccak256(payload))); + } + + function testSolanaSenderMemoizedByFirstApprovedExecute() public { + AxelarOracle oracle = solanaOracle(); string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Solana); + bytes32 key = keccak256(bytes(sender)); - gateway.approve(bytes32(0), "solana", sender, address(oracle), m); - uint256 g = gasleft(); - oracle.execute(bytes32(0), "solana", sender, m); - uint256 uncached = g - gasleft(); + // A rejected approval rolls back the memo write. + bytes[] memory p = new bytes[](1); + p[0] = hex"d1252dff012345"; + bytes memory m = this.encode(APP, p); + vm.expectRevert(AxelarOracle.NotApproved.selector); + oracle.execute(bytes32(uint256(9)), "solana", sender, m); + assertEq(oracle.solanaAddresses(key), bytes32(0)); + + uint256 first = executeCold(oracle, 0, sender, hex"d1252dff012345"); + assertEq(oracle.solanaAddresses(key), SENDER); + uint256 second = executeCold(oracle, 1, sender, hex"830c1e1c987654"); + assertLt(second * 5, first); + } + + function testSolanaSenderPrecacheIsPermissionless() public { + string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Solana); + uint256 uncached = executeCold(solanaOracle(), 0, sender, hex"d1252dff012345"); + AxelarOracle oracle = solanaOracle(); // Non-canonical spellings are rejected, so they can never be cached. vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); oracle.cacheSolanaAddress(string.concat("1", sender)); vm.prank(address(0xBEEF)); assertEq(oracle.cacheSolanaAddress(sender), SENDER); - assertEq(oracle.solanaAddresses(keccak256(bytes(sender))), SENDER); - - // A fresh proof, so both measured calls write a new tuple. - p[0] = hex"830c1e1c987654"; - m = this.encode(APP, p); - gateway.approve(bytes32(uint256(1)), "solana", sender, address(oracle), m); - g = gasleft(); - oracle.execute(bytes32(uint256(1)), "solana", sender, m); - uint256 cached = g - gasleft(); - assertTrue(oracle.isProven(9, SENDER, APP, keccak256(p[0]))); - assertLt(cached * 5, uncached); + uint256 precached = executeCold(oracle, 1, sender, hex"d1252dff012345"); + assertLt(precached * 5, uncached); } function testLayerZeroExportReceiveReplayAndFees() public { From 33561e3c5a00f15846a04b3469cf60ff2e839ab9 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 11:06:45 +0400 Subject: [PATCH 05/14] refactor(oracles): use OpenZeppelin Base58 for Solana addresses; drop sender cache --- .../oracles/axelar/AxelarOracle.sol | 46 ++------- .../oracles/common/OracleAddress.sol | 38 +++----- test/oracle/transport/StellarTransport.t.sol | 94 +++++++------------ 3 files changed, 53 insertions(+), 125 deletions(-) diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index 1098c3b7..cdbc4d5a 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -31,11 +31,7 @@ interface IAxelarNativeGasService { /// Transparent, immutable Axelar GMP oracle. Based on OIF PR #137; supports Stellar sender identities. contract AxelarOracle is BoundedOracle { - enum DeliveryMode { - Relayed, - SelfRelay - } - + enum DeliveryMode { Relayed, SelfRelay } struct Chain { string name; uint256 chainId; @@ -49,11 +45,8 @@ contract AxelarOracle is BoundedOracle { IAxelarMessageGateway public immutable gateway; IAxelarNativeGasService public immutable gasService; mapping(bytes32 => Route) private routes; - /// Permissionless memo of canonical Solana base58 decodings: keccak256(address string) => raw ID. - mapping(bytes32 => bytes32) public solanaAddresses; error NotApproved(); error InvalidFee(); - event SolanaAddressCached(bytes32 indexed id, string value); constructor( address gateway_, @@ -96,32 +89,19 @@ contract AxelarOracle is BoundedOracle { Route memory r = route(destinationChain); string memory recipient = OracleAddress.encode(recipientOracle, r.kind); bytes memory message = _export(source, payloads); - if (r.kind == OracleAddress.Kind.Solana) message = SolanaEnvelope.encode(message, destinationConfig); - else if (destinationConfig != 0) revert InvalidConfiguration(); + if (r.kind == OracleAddress.Kind.Solana) { + message = SolanaEnvelope.encode(message, destinationConfig); + } else if (destinationConfig != 0) revert InvalidConfiguration(); if (deliveryMode == DeliveryMode.Relayed) { if (msg.value == 0) revert InvalidFee(); gasService.payNativeGasForContractCall{ value: msg.value }( address(this), destinationChain, recipient, message, msg.sender ); - } else if (msg.value != 0) { - revert InvalidFee(); - } + } else if (msg.value != 0) revert InvalidFee(); gateway.callContract(destinationChain, recipient, message); } - /// Decode a canonical Solana base58 address and memoize it before any message arrives, so even - /// the first `execute` from that sender skips the decode. Anyone may pay for this: the entry is - /// exactly what `OracleAddress.decode` returns, so caching never changes results. - function cacheSolanaAddress( - string calldata value - ) external returns (bytes32 id) { - id = OracleAddress.decode(value, OracleAddress.Kind.Solana); - solanaAddresses[keccak256(bytes(value))] = id; - emit SolanaAddressCached(id, value); - } - /// Anyone may execute, but only the gateway can approve the exact destination-bound message. - /// A Solana sender missing from the memo is decoded once and memoized after validation. function execute( bytes32 commandId, string calldata sourceChain, @@ -129,24 +109,10 @@ contract AxelarOracle is BoundedOracle { bytes calldata payload ) external { Route memory r = route(sourceChain); - bytes32 sender; - bytes32 cacheKey; - if (r.kind == OracleAddress.Kind.Solana) { - cacheKey = keccak256(bytes(sourceAddress)); - sender = solanaAddresses[cacheKey]; - if (sender != 0) cacheKey = 0; - else sender = OracleAddress.decode(sourceAddress, r.kind); - } else { - sender = OracleAddress.decode(sourceAddress, r.kind); - } + bytes32 sender = OracleAddress.decode(sourceAddress, r.kind); if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { revert NotApproved(); } - // The all-zero ID is indistinguishable from absent, so it is never memoized. - if (cacheKey != 0 && sender != 0) { - solanaAddresses[cacheKey] = sender; - emit SolanaAddressCached(sender, sourceAddress); - } _record(r.chainId, sender, payload); } } diff --git a/src/integrations/oracles/common/OracleAddress.sol b/src/integrations/oracles/common/OracleAddress.sol index 05f8d160..2b987fb7 100644 --- a/src/integrations/oracles/common/OracleAddress.sol +++ b/src/integrations/oracles/common/OracleAddress.sol @@ -1,7 +1,10 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -/// Axelar native strings <-> OIF raw identifiers. Stellar CRC16-XModem is stored little-endian. +import { Base58 } from "@openzeppelin/contracts/utils/Base58.sol"; + +/// Axelar native strings <-> OIF raw identifiers. Solana uses OpenZeppelin Base58; Stellar +/// CRC16-XModem is stored little-endian. library OracleAddress { enum Kind { Evm, @@ -11,27 +14,12 @@ library OracleAddress { error InvalidOracleAddress(); bytes internal constant BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; bytes internal constant HEX = "0123456789abcdef"; - bytes internal constant BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; function encode( bytes32 id, Kind kind ) internal pure returns (string memory) { - if (kind == Kind.Solana) { - uint256 n = uint256(id); - bytes memory digits = new bytes(44); - uint256 length; - while (n != 0) { - digits[length++] = BASE58[n % 58]; - n /= 58; - } - uint256 zeros; - while (zeros < 32 && id[zeros] == 0) ++zeros; - bytes memory out58 = new bytes(zeros + length); - for (uint256 i; i < zeros; ++i) out58[i] = "1"; - for (uint256 i; i < length; ++i) out58[zeros + i] = digits[length - 1 - i]; - return string(out58); - } + if (kind == Kind.Solana) return Base58.encode(abi.encodePacked(id)); if (kind == Kind.Evm) { if (uint256(id) >> 160 != 0) revert InvalidOracleAddress(); bytes memory evm = new bytes(42); @@ -70,15 +58,13 @@ library OracleAddress { bytes calldata input = bytes(value); if (kind == Kind.Solana) { if (input.length < 32 || input.length > 44) revert InvalidOracleAddress(); - uint256 n; - for (uint256 i; i < input.length; ++i) { - uint256 digit; - while (digit < 58 && BASE58[digit] != input[i]) ++digit; - if (digit == 58 || n > (type(uint256).max - digit) / 58) revert InvalidOracleAddress(); - n = n * 58 + digit; - } - id = bytes32(n); - if (keccak256(bytes(encode(id, kind))) != keccak256(input)) revert InvalidOracleAddress(); + // Invalid characters revert with OpenZeppelin's `InvalidBase58Char`. + bytes memory decoded = Base58.decode(value); + if (decoded.length != 32) revert InvalidOracleAddress(); + id = bytes32(decoded); + // Base58 is a bijection, so this never fails today; it pins one spelling per ID + // independently of the library's decoder. + if (keccak256(bytes(Base58.encode(decoded))) != keccak256(input)) revert InvalidOracleAddress(); return id; } if (kind == Kind.Evm) { diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol index e74a0d54..8c9c64cd 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/StellarTransport.t.sol @@ -93,6 +93,41 @@ contract StellarTransportTest is Test { assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); } + // Vectors generated with @solana/web3.js PublicKey.toBase58(). + function testSolanaAddressVectors() public { + bytes32[6] memory ids = [ + bytes32(0), + bytes32(uint256(1)), + bytes32(0x00ababababababababababababababababababababababababababababababab), + bytes32(type(uint256).max), + bytes32(hex"0306466fe5211732ffecadba72c39be7bc8ce5bbc5f7126b2c439b3a40000000"), + bytes32(hex"037d46d67c93fbbe12f9428f838d40ff0570744927f48a64fcca704480000000") + ]; + string[6] memory strings = [ + "11111111111111111111111111111111", + "11111111111111111111111111111112", + "13cpvoZKJ28f1CDBboEmfEXMVVMcSQzBhTEMtecGWQ6v", + "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", + "ComputeBudget111111111111111111111111111111", + "Ed25519SigVerify111111111111111111111111111" + ]; + for (uint256 i; i < ids.length; ++i) { + assertEq(OracleAddress.encode(ids[i], OracleAddress.Kind.Solana), strings[i]); + assertEq(this.decodeAddress(strings[i], OracleAddress.Kind.Solana), ids[i]); + } + // 31 decoded bytes, 33 decoded bytes, a character outside the alphabet, and 45 characters. + string[4] memory bad = [ + "4uQeVj5tqViQh7yWWGStvkEG1Zmhx6uasJtWCJziofL", + "111111111111111111111111111111111", + "0EKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", + "1JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG" + ]; + for (uint256 i; i < bad.length; ++i) { + vm.expectRevert(); + this.decodeAddress(bad[i], OracleAddress.Kind.Solana); + } + } + function testSolanaEnvelopeAndExplicitSelfRelay() public { AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); @@ -164,65 +199,6 @@ contract StellarTransportTest is Test { axelar.execute(bytes32(uint256(1)), "stellar", sender, m); } - function solanaOracle() internal returns (AxelarOracle) { - AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); - routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); - return new AxelarOracle(address(gateway), address(gateway), routes); - } - - /// Approve and execute one fresh Solana message with cold oracle and gateway storage. - /// Returns call-frame gas under the fixture gateway; excludes intrinsic gas. - function executeCold( - AxelarOracle oracle, - uint256 commandId, - string memory sender, - bytes memory payload - ) internal returns (uint256 used) { - bytes[] memory p = new bytes[](1); - p[0] = payload; - bytes memory m = this.encode(APP, p); - gateway.approve(bytes32(commandId), "solana", sender, address(oracle), m); - vm.cool(address(oracle)); - vm.cool(address(gateway)); - uint256 g = gasleft(); - oracle.execute(bytes32(commandId), "solana", sender, m); - used = g - gasleft(); - assertTrue(oracle.isProven(9, SENDER, APP, keccak256(payload))); - } - - function testSolanaSenderMemoizedByFirstApprovedExecute() public { - AxelarOracle oracle = solanaOracle(); - string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Solana); - bytes32 key = keccak256(bytes(sender)); - - // A rejected approval rolls back the memo write. - bytes[] memory p = new bytes[](1); - p[0] = hex"d1252dff012345"; - bytes memory m = this.encode(APP, p); - vm.expectRevert(AxelarOracle.NotApproved.selector); - oracle.execute(bytes32(uint256(9)), "solana", sender, m); - assertEq(oracle.solanaAddresses(key), bytes32(0)); - - uint256 first = executeCold(oracle, 0, sender, hex"d1252dff012345"); - assertEq(oracle.solanaAddresses(key), SENDER); - uint256 second = executeCold(oracle, 1, sender, hex"830c1e1c987654"); - assertLt(second * 5, first); - } - - function testSolanaSenderPrecacheIsPermissionless() public { - string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Solana); - uint256 uncached = executeCold(solanaOracle(), 0, sender, hex"d1252dff012345"); - - AxelarOracle oracle = solanaOracle(); - // Non-canonical spellings are rejected, so they can never be cached. - vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); - oracle.cacheSolanaAddress(string.concat("1", sender)); - vm.prank(address(0xBEEF)); - assertEq(oracle.cacheSolanaAddress(sender), SENDER); - uint256 precached = executeCold(oracle, 1, sender, hex"d1252dff012345"); - assertLt(precached * 5, uncached); - } - function testLayerZeroExportReceiveReplayAndFees() public { source.setOracle(address(lz)); uint256 beforeBalance = address(this).balance; From dc07c680b46d2c641bd81d4a2d75b79c33e658c7 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 11:07:19 +0400 Subject: [PATCH 06/14] feat(axelar): owner-mapped chains following ChainMap conventions --- .../oracles/axelar/AxelarOracle.sol | 83 ++++++++++++------- test/oracle/transport/StellarTransport.t.sol | 53 ++++++++++-- test/oracle/transport/TransportFixtures.sol | 8 +- 3 files changed, 108 insertions(+), 36 deletions(-) diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index cdbc4d5a..aef0a81d 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -1,6 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; +import { Ownable } from "openzeppelin/access/Ownable.sol"; + import { BoundedOracle } from "../common/BoundedOracle.sol"; import { OracleAddress } from "../common/OracleAddress.sol"; import { SolanaEnvelope } from "./SolanaEnvelope.sol"; @@ -29,53 +31,78 @@ interface IAxelarNativeGasService { ) external payable; } -/// Transparent, immutable Axelar GMP oracle. Based on OIF PR #137; supports Stellar sender identities. -contract AxelarOracle is BoundedOracle { +/// Transparent Axelar GMP oracle with owner-set immutable chain maps (ChainMap conventions keyed by lowercase +/// Axelar name). Based on OIF PR #137; supports Stellar and Solana sender identities. +contract AxelarOracle is BoundedOracle, Ownable { enum DeliveryMode { Relayed, SelfRelay } - struct Chain { - string name; - uint256 chainId; - OracleAddress.Kind kind; - } struct Route { uint256 chainId; OracleAddress.Kind kind; } + + /// Axelar ChainNameRaw::MAX_LEN. + uint256 public constant MAX_CHAIN_NAME = 20; IAxelarMessageGateway public immutable gateway; IAxelarNativeGasService public immutable gasService; mapping(bytes32 => Route) private routes; + mapping(uint256 chainId => bytes32 nameKey) public reverseChainIdMap; + error NotApproved(); error InvalidFee(); + error AlreadySet(); + error ZeroValue(); + + event ChainMapConfigured(string name, uint256 chainId, OracleAddress.Kind kind); constructor( + address owner_, address gateway_, - address gasService_, - Chain[] memory chains - ) { - if (gateway_.code.length == 0 || gasService_.code.length == 0 || chains.length == 0 || chains.length > 16) { - revert InvalidConfiguration(); - } + address gasService_ + ) Ownable(owner_) { + if (gateway_.code.length == 0 || gasService_.code.length == 0) revert InvalidConfiguration(); gateway = IAxelarMessageGateway(gateway_); gasService = IAxelarNativeGasService(gasService_); - for (uint256 i; i < chains.length; ++i) { - Chain memory c = chains[i]; - bytes32 key = keccak256(bytes(c.name)); - if (bytes(c.name).length == 0 || bytes(c.name).length > 64 || c.chainId == 0 || routes[key].chainId != 0) { - revert InvalidConfiguration(); - } - for (uint256 j; j < i; ++j) { - if (chains[j].chainId == c.chainId) revert InvalidConfiguration(); - } - routes[key] = Route(c.chainId, c.kind); + } + + /// Set an immutable map from a lowercase Axelar name to an OIF chain. Each name and chain ID is set once. + function setChainMap( + string calldata name, + uint256 chainId, + OracleAddress.Kind kind + ) external onlyOwner { + if (chainId == 0) revert ZeroValue(); + bytes calldata b = bytes(name); + if (b.length == 0 || b.length > MAX_CHAIN_NAME) revert InvalidConfiguration(); + for (uint256 i; i < b.length; ++i) { + bytes1 c = b[i]; + if (!((c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c == "-")) revert InvalidConfiguration(); } + bytes32 key = keccak256(b); + if (routes[key].chainId != 0 || reverseChainIdMap[chainId] != 0) revert AlreadySet(); + routes[key] = Route(chainId, kind); + reverseChainIdMap[chainId] = key; + emit ChainMapConfigured(name, chainId, kind); } function route( string calldata name ) public view returns (Route memory r) { - r = routes[keccak256(bytes(name))]; + (, r) = _route(name); + } + + /// Lowercased canonical name and its map; Axelar names are unique after ASCII lowercasing. + function _route( + string calldata name + ) internal view returns (string memory canonical, Route memory r) { + bytes memory b = bytes(name); + if (b.length == 0 || b.length > MAX_CHAIN_NAME) revert UnknownChain(); + for (uint256 i; i < b.length; ++i) { + if (b[i] >= 0x41 && b[i] <= 0x5a) b[i] = bytes1(uint8(b[i]) + 32); + } + r = routes[keccak256(b)]; if (r.chainId == 0) revert UnknownChain(); + canonical = string(b); } function submit( @@ -86,7 +113,7 @@ contract AxelarOracle is BoundedOracle { bytes32 destinationConfig, DeliveryMode deliveryMode ) external payable { - Route memory r = route(destinationChain); + (string memory chain, Route memory r) = _route(destinationChain); string memory recipient = OracleAddress.encode(recipientOracle, r.kind); bytes memory message = _export(source, payloads); if (r.kind == OracleAddress.Kind.Solana) { @@ -95,10 +122,10 @@ contract AxelarOracle is BoundedOracle { if (deliveryMode == DeliveryMode.Relayed) { if (msg.value == 0) revert InvalidFee(); gasService.payNativeGasForContractCall{ value: msg.value }( - address(this), destinationChain, recipient, message, msg.sender + address(this), chain, recipient, message, msg.sender ); } else if (msg.value != 0) revert InvalidFee(); - gateway.callContract(destinationChain, recipient, message); + gateway.callContract(chain, recipient, message); } /// Anyone may execute, but only the gateway can approve the exact destination-bound message. @@ -108,7 +135,7 @@ contract AxelarOracle is BoundedOracle { string calldata sourceAddress, bytes calldata payload ) external { - Route memory r = route(sourceChain); + (, Route memory r) = _route(sourceChain); bytes32 sender = OracleAddress.decode(sourceAddress, r.kind); if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { revert NotApproved(); diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/StellarTransport.t.sol index 8c9c64cd..3ebd2b9f 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/StellarTransport.t.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.26; import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; +import { Ownable } from "openzeppelin/access/Ownable.sol"; import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; @@ -38,9 +39,8 @@ contract StellarTransportTest is Test { gateway = new GatewayFixture(); endpoint = new EndpointFixture(); source = new BoundAttester(); - AxelarOracle.Chain[] memory a = new AxelarOracle.Chain[](1); - a[0] = AxelarOracle.Chain("stellar", CHAIN, OracleAddress.Kind.Stellar); - axelar = new AxelarOracle(address(gateway), address(gateway), a); + axelar = new AxelarOracle(address(this), address(gateway), address(gateway)); + axelar.setChainMap("stellar", CHAIN, OracleAddress.Kind.Stellar); LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); address[] memory dvns = new address[](1); dvns[0] = address(0x1234); @@ -129,9 +129,8 @@ contract StellarTransportTest is Test { } function testSolanaEnvelopeAndExplicitSelfRelay() public { - AxelarOracle.Chain[] memory routes = new AxelarOracle.Chain[](1); - routes[0] = AxelarOracle.Chain("solana", 9, OracleAddress.Kind.Solana); - AxelarOracle oracle = new AxelarOracle(address(gateway), address(gateway), routes); + AxelarOracle oracle = new AxelarOracle(address(this), address(gateway), address(gateway)); + oracle.setChainMap("solana", 9, OracleAddress.Kind.Solana); source.setOracle(address(oracle)); bytes[] memory p = new bytes[](1); p[0] = new bytes(320); @@ -199,6 +198,48 @@ contract StellarTransportTest is Test { axelar.execute(bytes32(uint256(1)), "stellar", sender, m); } + function testAxelarChainMapOwnerSetOnce() public { + vm.prank(address(0xBEEF)); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); + axelar.setChainMap("evm", 1, OracleAddress.Kind.Evm); + vm.expectRevert(AxelarOracle.ZeroValue.selector); + axelar.setChainMap("evm", 0, OracleAddress.Kind.Evm); + vm.expectRevert(AxelarOracle.AlreadySet.selector); + axelar.setChainMap("stellar", 2, OracleAddress.Kind.Evm); + vm.expectRevert(AxelarOracle.AlreadySet.selector); + axelar.setChainMap("evm", CHAIN, OracleAddress.Kind.Evm); + string[4] memory bad = ["Evm", "", "abcdefghijklmnopqrstu", "e_vm"]; + for (uint256 i; i < bad.length; ++i) { + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + axelar.setChainMap(bad[i], 2, OracleAddress.Kind.Evm); + } + vm.expectEmit(address(axelar)); + emit AxelarOracle.ChainMapConfigured("evm", 1, OracleAddress.Kind.Evm); + axelar.setChainMap("evm", 1, OracleAddress.Kind.Evm); + assertEq(axelar.reverseChainIdMap(1), keccak256("evm")); + for (uint256 i; i < 17; ++i) { + axelar.setChainMap(string.concat("c", vm.toString(i)), 1000 + i, OracleAddress.Kind.Evm); + } + assertEq(axelar.route("C16").chainId, 1016); + vm.expectRevert(BoundedOracle.UnknownChain.selector); + axelar.route("stellar "); + axelar.renounceOwnership(); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(this))); + axelar.setChainMap("late", 5, OracleAddress.Kind.Evm); + } + + function testAxelarLowercaseLookupForwardsCanonicalName() public { + source.setOracle(address(axelar)); + axelar.submit{ value: 10 }("STELLAR", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + assertEq(gateway.lastChain(), "stellar"); + assertEq(gateway.lastGasChain(), "stellar"); + bytes memory m = this.encode(APP, payloads()); + string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); + gateway.approve(bytes32(uint256(7)), "Stellar", sender, address(axelar), m); + axelar.execute(bytes32(uint256(7)), "Stellar", sender, m); + assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); + } + function testLayerZeroExportReceiveReplayAndFees() public { source.setOracle(address(lz)); uint256 beforeBalance = address(this).balance; diff --git a/test/oracle/transport/TransportFixtures.sol b/test/oracle/transport/TransportFixtures.sol index 5f0f38e0..e31f00d0 100644 --- a/test/oracle/transport/TransportFixtures.sol +++ b/test/oracle/transport/TransportFixtures.sol @@ -15,6 +15,8 @@ contract GatewayFixture { mapping(bytes32 => bool) public approvals; bytes public lastMessage; string public lastDestination; + string public lastChain; + string public lastGasChain; address public lastSender; address public lastRefund; uint256 public paid; @@ -42,23 +44,25 @@ contract GatewayFixture { } function callContract( - string calldata, + string calldata chain, string calldata destination, bytes calldata payload ) external { lastMessage = payload; + lastChain = chain; lastDestination = destination; lastSender = msg.sender; } function payNativeGasForContractCall( address, - string calldata, + string calldata chain, string calldata, bytes calldata, address refund ) external payable { paid += msg.value; + lastGasChain = chain; lastRefund = refund; } } From 2a9fac46d9eb3d9035016c379196f2ed6a0da771 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 16:10:10 +0400 Subject: [PATCH 07/14] test(oracles): split transport tests per oracle --- ...llarTransport.t.sol => AxelarOracle.t.sol} | 174 +----------------- test/oracle/transport/BoundAttester.sol | 18 ++ ...nsportFixtures.sol => EndpointFixture.sol} | 58 ------ test/oracle/transport/GatewayFixture.sol | 59 ++++++ test/oracle/transport/LayerZeroOracle.t.sol | 104 +++++++++++ test/oracle/transport/OracleAddress.t.sol | 96 ++++++++++ 6 files changed, 285 insertions(+), 224 deletions(-) rename test/oracle/transport/{StellarTransport.t.sol => AxelarOracle.t.sol} (52%) create mode 100644 test/oracle/transport/BoundAttester.sol rename test/oracle/transport/{TransportFixtures.sol => EndpointFixture.sol} (61%) create mode 100644 test/oracle/transport/GatewayFixture.sol create mode 100644 test/oracle/transport/LayerZeroOracle.t.sol create mode 100644 test/oracle/transport/OracleAddress.t.sol diff --git a/test/oracle/transport/StellarTransport.t.sol b/test/oracle/transport/AxelarOracle.t.sol similarity index 52% rename from test/oracle/transport/StellarTransport.t.sol rename to test/oracle/transport/AxelarOracle.t.sol index 3ebd2b9f..b38e80be 100644 --- a/test/oracle/transport/StellarTransport.t.sol +++ b/test/oracle/transport/AxelarOracle.t.sol @@ -2,34 +2,16 @@ pragma solidity ^0.8.26; import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; -import { Ownable } from "openzeppelin/access/Ownable.sol"; import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; -import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; -import { EndpointFixture, GatewayFixture } from "./TransportFixtures.sol"; +import { BoundAttester } from "./BoundAttester.sol"; +import { GatewayFixture } from "./GatewayFixture.sol"; import { Test } from "forge-std/Test.sol"; +import { Ownable } from "openzeppelin/access/Ownable.sol"; -contract BoundAttester { - address public oracle; - - function setOracle( - address o - ) external { - oracle = o; - } - - function hasAttested( - bytes[] calldata - ) external view returns (bool) { - return msg.sender == oracle; - } -} - -contract StellarTransportTest is Test { +contract AxelarOracleTest is Test { GatewayFixture gateway; - EndpointFixture endpoint; AxelarOracle axelar; - LayerZeroOracle lz; BoundAttester source; bytes32 constant SENDER = keccak256("stellar oracle"); bytes32 constant APP = keccak256("stellar settler"); @@ -37,16 +19,11 @@ contract StellarTransportTest is Test { function setUp() public { gateway = new GatewayFixture(); - endpoint = new EndpointFixture(); source = new BoundAttester(); axelar = new AxelarOracle(address(this), address(gateway), address(gateway)); axelar.setChainMap("stellar", CHAIN, OracleAddress.Kind.Stellar); - LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); - address[] memory dvns = new address[](1); - dvns[0] = address(0x1234); - c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), 1, 1, dvns, dvns); - lz = new LayerZeroOracle(address(endpoint), c); } + receive() external payable { } function payloads() internal pure returns (bytes[] memory p) { @@ -62,72 +39,6 @@ contract StellarTransportTest is Test { return MessageEncodingLib.encodeMessage(application, p); } - function decodeAddress( - string calldata value, - OracleAddress.Kind kind - ) external pure returns (bytes32) { - return OracleAddress.decode(value, kind); - } - - function decode( - bytes calldata b - ) external pure returns (bytes32, bytes32[] memory) { - return MessageEncodingLib.getHashesOfEncodedPayloads(b); - } - - function options() internal pure returns (bytes memory) { - return abi.encodePacked(hex"000301001101", uint128(200_000)); - } - - function testFuzzStellarAddressRoundtrip( - bytes32 id - ) public { - assertEq( - this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Stellar), OracleAddress.Kind.Stellar), id - ); - } - - function testFuzzSolanaAddressRoundtrip( - bytes32 id - ) public { - assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); - } - - // Vectors generated with @solana/web3.js PublicKey.toBase58(). - function testSolanaAddressVectors() public { - bytes32[6] memory ids = [ - bytes32(0), - bytes32(uint256(1)), - bytes32(0x00ababababababababababababababababababababababababababababababab), - bytes32(type(uint256).max), - bytes32(hex"0306466fe5211732ffecadba72c39be7bc8ce5bbc5f7126b2c439b3a40000000"), - bytes32(hex"037d46d67c93fbbe12f9428f838d40ff0570744927f48a64fcca704480000000") - ]; - string[6] memory strings = [ - "11111111111111111111111111111111", - "11111111111111111111111111111112", - "13cpvoZKJ28f1CDBboEmfEXMVVMcSQzBhTEMtecGWQ6v", - "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", - "ComputeBudget111111111111111111111111111111", - "Ed25519SigVerify111111111111111111111111111" - ]; - for (uint256 i; i < ids.length; ++i) { - assertEq(OracleAddress.encode(ids[i], OracleAddress.Kind.Solana), strings[i]); - assertEq(this.decodeAddress(strings[i], OracleAddress.Kind.Solana), ids[i]); - } - // 31 decoded bytes, 33 decoded bytes, a character outside the alphabet, and 45 characters. - string[4] memory bad = [ - "4uQeVj5tqViQh7yWWGStvkEG1Zmhx6uasJtWCJziofL", - "111111111111111111111111111111111", - "0EKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", - "1JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG" - ]; - for (uint256 i; i < bad.length; ++i) { - vm.expectRevert(); - this.decodeAddress(bad[i], OracleAddress.Kind.Solana); - } - } - function testSolanaEnvelopeAndExplicitSelfRelay() public { AxelarOracle oracle = new AxelarOracle(address(this), address(gateway), address(gateway)); oracle.setChainMap("solana", 9, OracleAddress.Kind.Solana); @@ -160,20 +71,6 @@ contract StellarTransportTest is Test { p[0] = new bytes(321); vm.expectRevert(); oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); - vm.expectRevert(); - this.decodeAddress("111111111111111111111111111111111", OracleAddress.Kind.Solana); - vm.expectRevert(); - this.decodeAddress("01111111111111111111111111111111", OracleAddress.Kind.Solana); - } - - function testPublishedStrKeyAndBadChecksum() public { - string memory zero = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4"; - assertEq(OracleAddress.encode(bytes32(0), OracleAddress.Kind.Stellar), zero); - assertEq(this.decodeAddress(zero, OracleAddress.Kind.Stellar), bytes32(0)); - vm.expectRevert(); - this.decodeAddress("CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC5", OracleAddress.Kind.Stellar); - vm.expectRevert(); - this.decodeAddress("GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", OracleAddress.Kind.Stellar); } function testAxelarExportAndAuthenticatedNamespace() public { @@ -230,7 +127,9 @@ contract StellarTransportTest is Test { function testAxelarLowercaseLookupForwardsCanonicalName() public { source.setOracle(address(axelar)); - axelar.submit{ value: 10 }("STELLAR", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + axelar.submit{ value: 10 }( + "STELLAR", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); assertEq(gateway.lastChain(), "stellar"); assertEq(gateway.lastGasChain(), "stellar"); bytes memory m = this.encode(APP, payloads()); @@ -240,23 +139,6 @@ contract StellarTransportTest is Test { assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); } - function testLayerZeroExportReceiveReplayAndFees() public { - source.setOracle(address(lz)); - uint256 beforeBalance = address(this).balance; - lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); - assertEq(address(this).balance, beforeBalance - 10); - assertEq(endpoint.lastRecipient(), SENDER); - bytes memory m = this.encode(APP, payloads()); - Origin memory o = Origin(30600, SENDER, 1); - vm.expectRevert(); - lz.lzReceive(o, bytes32(0), m, address(this), ""); - endpoint.approve(address(lz), o, bytes32(0), m); - endpoint.deliver(address(lz), o, bytes32(0), m); - assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); - vm.expectRevert(); - endpoint.deliver(address(lz), o, bytes32(0), m); - } - function testBoundsMalformedRollbackAndExportNamespace() public { bytes memory m = bytes.concat(this.encode(APP, payloads()), hex"00"); string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); @@ -266,8 +148,6 @@ contract StellarTransportTest is Test { axelar.execute(bytes32(0), "stellar", sender, m); assertTrue(gateway.approvals(key)); vm.expectRevert(); - this.decode(m); - vm.expectRevert(); axelar.submit{ value: 10 }( "stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed ); @@ -278,43 +158,5 @@ contract StellarTransportTest is Test { axelar.submit{ value: 10 }( "stellar", SENDER, address(source), big, bytes32(0), AxelarOracle.DeliveryMode.Relayed ); - vm.expectRevert(); - lz.quote(30600, SENDER, address(source), payloads(), hex""); - vm.expectRevert(); - lz.quote(999, SENDER, address(source), payloads(), options()); - } - - function testLayerZeroRejectsNilConfirmations() public { - address[] memory dvns = new address[](1); - dvns[0] = address(0x1234); - LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); - c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), type(uint64).max, 1, dvns, dvns); - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); - new LayerZeroOracle(address(endpoint), c); - c[0].sendConfirmations = 1; - c[0].receiveConfirmations = type(uint64).max; - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); - new LayerZeroOracle(address(endpoint), c); - } - - function testMaximumBatchAndTupleChecks() public { - bytes[] memory p = new bytes[](4); - for (uint256 i; i < 4; ++i) { - p[i] = new bytes(684); - p[i][0] = bytes1(uint8(i)); - } - bytes memory m = this.encode(APP, p); - assertEq(m.length, 2778); - Origin memory o = Origin(30600, SENDER, 1); - endpoint.approve(address(lz), o, bytes32(0), m); - endpoint.deliver(address(lz), o, bytes32(0), m); - bytes memory proofs; - for (uint256 i; i < 4; ++i) { - proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); - } - lz.efficientRequireProven(proofs); - lz.efficientRequireProven(""); - vm.expectRevert(); - lz.efficientRequireProven(bytes.concat(proofs, hex"00")); } } diff --git a/test/oracle/transport/BoundAttester.sol b/test/oracle/transport/BoundAttester.sol new file mode 100644 index 00000000..dc401372 --- /dev/null +++ b/test/oracle/transport/BoundAttester.sol @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +contract BoundAttester { + address public oracle; + + function setOracle( + address o + ) external { + oracle = o; + } + + function hasAttested( + bytes[] calldata + ) external view returns (bool) { + return msg.sender == oracle; + } +} diff --git a/test/oracle/transport/TransportFixtures.sol b/test/oracle/transport/EndpointFixture.sol similarity index 61% rename from test/oracle/transport/TransportFixtures.sol rename to test/oracle/transport/EndpointFixture.sol index e31f00d0..caa39e3f 100644 --- a/test/oracle/transport/TransportFixtures.sol +++ b/test/oracle/transport/EndpointFixture.sol @@ -1,6 +1,5 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; import { LayerZeroOracle, MessagingFee, @@ -10,63 +9,6 @@ import { SetConfigParam } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; -/// Test-only verification boundary. Approvals bind every provider-authenticated field and are consumed atomically. -contract GatewayFixture { - mapping(bytes32 => bool) public approvals; - bytes public lastMessage; - string public lastDestination; - string public lastChain; - string public lastGasChain; - address public lastSender; - address public lastRefund; - uint256 public paid; - - function approve( - bytes32 command, - string memory chain, - string memory sender, - address receiver, - bytes memory payload - ) external { - approvals[keccak256(abi.encode(command, chain, sender, receiver, keccak256(payload)))] = true; - } - - function validateContractCall( - bytes32 command, - string calldata chain, - string calldata sender, - bytes32 hash - ) external returns (bool) { - bytes32 k = keccak256(abi.encode(command, chain, sender, msg.sender, hash)); - bool valid = approvals[k]; - delete approvals[k]; - return valid; - } - - function callContract( - string calldata chain, - string calldata destination, - bytes calldata payload - ) external { - lastMessage = payload; - lastChain = chain; - lastDestination = destination; - lastSender = msg.sender; - } - - function payNativeGasForContractCall( - address, - string calldata chain, - string calldata, - bytes calldata, - address refund - ) external payable { - paid += msg.value; - lastGasChain = chain; - lastRefund = refund; - } -} - contract EndpointFixture { mapping(bytes32 => bool) public approvals; mapping(bytes32 => bytes) public configs; diff --git a/test/oracle/transport/GatewayFixture.sol b/test/oracle/transport/GatewayFixture.sol new file mode 100644 index 00000000..279ee5fe --- /dev/null +++ b/test/oracle/transport/GatewayFixture.sol @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +/// Test-only verification boundary. Approvals bind every provider-authenticated field and are consumed atomically. +contract GatewayFixture { + mapping(bytes32 => bool) public approvals; + bytes public lastMessage; + string public lastDestination; + string public lastChain; + string public lastGasChain; + address public lastSender; + address public lastRefund; + uint256 public paid; + + function approve( + bytes32 command, + string memory chain, + string memory sender, + address receiver, + bytes memory payload + ) external { + approvals[keccak256(abi.encode(command, chain, sender, receiver, keccak256(payload)))] = true; + } + + function validateContractCall( + bytes32 command, + string calldata chain, + string calldata sender, + bytes32 hash + ) external returns (bool) { + bytes32 k = keccak256(abi.encode(command, chain, sender, msg.sender, hash)); + bool valid = approvals[k]; + delete approvals[k]; + return valid; + } + + function callContract( + string calldata chain, + string calldata destination, + bytes calldata payload + ) external { + lastMessage = payload; + lastChain = chain; + lastDestination = destination; + lastSender = msg.sender; + } + + function payNativeGasForContractCall( + address, + string calldata chain, + string calldata, + bytes calldata, + address refund + ) external payable { + paid += msg.value; + lastGasChain = chain; + lastRefund = refund; + } +} diff --git a/test/oracle/transport/LayerZeroOracle.t.sol b/test/oracle/transport/LayerZeroOracle.t.sol new file mode 100644 index 00000000..2ec0038b --- /dev/null +++ b/test/oracle/transport/LayerZeroOracle.t.sol @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; +import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; +import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { BoundAttester } from "./BoundAttester.sol"; +import { EndpointFixture } from "./EndpointFixture.sol"; +import { Test } from "forge-std/Test.sol"; + +contract LayerZeroOracleTest is Test { + EndpointFixture endpoint; + LayerZeroOracle lz; + BoundAttester source; + bytes32 constant SENDER = keccak256("stellar oracle"); + bytes32 constant APP = keccak256("stellar settler"); + uint256 constant CHAIN = 0x53544c; + + function setUp() public { + endpoint = new EndpointFixture(); + source = new BoundAttester(); + LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); + address[] memory dvns = new address[](1); + dvns[0] = address(0x1234); + c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), 1, 1, dvns, dvns); + lz = new LayerZeroOracle(address(endpoint), c); + } + + receive() external payable { } + + function payloads() internal pure returns (bytes[] memory p) { + p = new bytes[](2); + p[0] = hex"d1252dff012345"; + p[1] = hex"830c1e1c987654"; + } + + function encode( + bytes32 application, + bytes[] calldata p + ) external pure returns (bytes memory) { + return MessageEncodingLib.encodeMessage(application, p); + } + + function options() internal pure returns (bytes memory) { + return abi.encodePacked(hex"000301001101", uint128(200_000)); + } + + function testLayerZeroExportReceiveReplayAndFees() public { + source.setOracle(address(lz)); + uint256 beforeBalance = address(this).balance; + lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); + assertEq(address(this).balance, beforeBalance - 10); + assertEq(endpoint.lastRecipient(), SENDER); + bytes memory m = this.encode(APP, payloads()); + Origin memory o = Origin(30600, SENDER, 1); + vm.expectRevert(); + lz.lzReceive(o, bytes32(0), m, address(this), ""); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); + vm.expectRevert(); + endpoint.deliver(address(lz), o, bytes32(0), m); + } + + function testQuoteRejectsMissingOptionsAndUnknownChain() public { + vm.expectRevert(); + lz.quote(30600, SENDER, address(source), payloads(), hex""); + vm.expectRevert(); + lz.quote(999, SENDER, address(source), payloads(), options()); + } + + function testLayerZeroRejectsNilConfirmations() public { + address[] memory dvns = new address[](1); + dvns[0] = address(0x1234); + LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); + c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), type(uint64).max, 1, dvns, dvns); + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + new LayerZeroOracle(address(endpoint), c); + c[0].sendConfirmations = 1; + c[0].receiveConfirmations = type(uint64).max; + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + new LayerZeroOracle(address(endpoint), c); + } + + function testMaximumBatchAndTupleChecks() public { + bytes[] memory p = new bytes[](4); + for (uint256 i; i < 4; ++i) { + p[i] = new bytes(684); + p[i][0] = bytes1(uint8(i)); + } + bytes memory m = this.encode(APP, p); + assertEq(m.length, 2778); + Origin memory o = Origin(30600, SENDER, 1); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + bytes memory proofs; + for (uint256 i; i < 4; ++i) { + proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); + } + lz.efficientRequireProven(proofs); + lz.efficientRequireProven(""); + vm.expectRevert(); + lz.efficientRequireProven(bytes.concat(proofs, hex"00")); + } +} diff --git a/test/oracle/transport/OracleAddress.t.sol b/test/oracle/transport/OracleAddress.t.sol new file mode 100644 index 00000000..ea6ef95f --- /dev/null +++ b/test/oracle/transport/OracleAddress.t.sol @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; +import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { Test } from "forge-std/Test.sol"; + +contract OracleAddressTest is Test { + bytes32 constant APP = keccak256("stellar settler"); + + function encode( + bytes32 application, + bytes[] calldata p + ) external pure returns (bytes memory) { + return MessageEncodingLib.encodeMessage(application, p); + } + + function decodeAddress( + string calldata value, + OracleAddress.Kind kind + ) external pure returns (bytes32) { + return OracleAddress.decode(value, kind); + } + + function decode( + bytes calldata b + ) external pure returns (bytes32, bytes32[] memory) { + return MessageEncodingLib.getHashesOfEncodedPayloads(b); + } + + function testFuzzStellarAddressRoundtrip( + bytes32 id + ) public { + assertEq( + this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Stellar), OracleAddress.Kind.Stellar), id + ); + } + + function testFuzzSolanaAddressRoundtrip( + bytes32 id + ) public { + assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); + } + + // Vectors generated with @solana/web3.js PublicKey.toBase58(). + function testSolanaAddressVectors() public { + bytes32[6] memory ids = [ + bytes32(0), + bytes32(uint256(1)), + bytes32(0x00ababababababababababababababababababababababababababababababab), + bytes32(type(uint256).max), + bytes32(hex"0306466fe5211732ffecadba72c39be7bc8ce5bbc5f7126b2c439b3a40000000"), + bytes32(hex"037d46d67c93fbbe12f9428f838d40ff0570744927f48a64fcca704480000000") + ]; + string[6] memory strings = [ + "11111111111111111111111111111111", + "11111111111111111111111111111112", + "13cpvoZKJ28f1CDBboEmfEXMVVMcSQzBhTEMtecGWQ6v", + "JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", + "ComputeBudget111111111111111111111111111111", + "Ed25519SigVerify111111111111111111111111111" + ]; + for (uint256 i; i < ids.length; ++i) { + assertEq(OracleAddress.encode(ids[i], OracleAddress.Kind.Solana), strings[i]); + assertEq(this.decodeAddress(strings[i], OracleAddress.Kind.Solana), ids[i]); + } + // 31 decoded bytes, 33 decoded bytes, a character outside the alphabet, and 45 characters. + string[4] memory bad = [ + "4uQeVj5tqViQh7yWWGStvkEG1Zmhx6uasJtWCJziofL", + "111111111111111111111111111111111", + "0EKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG", + "1JEKNVnkbo3jma5nREBBJCDoXFVeKkD56V3xKrvRmWxFG" + ]; + for (uint256 i; i < bad.length; ++i) { + vm.expectRevert(); + this.decodeAddress(bad[i], OracleAddress.Kind.Solana); + } + } + + function testPublishedStrKeyAndBadChecksum() public { + string memory zero = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4"; + assertEq(OracleAddress.encode(bytes32(0), OracleAddress.Kind.Stellar), zero); + assertEq(this.decodeAddress(zero, OracleAddress.Kind.Stellar), bytes32(0)); + vm.expectRevert(); + this.decodeAddress("CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC5", OracleAddress.Kind.Stellar); + vm.expectRevert(); + this.decodeAddress("GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", OracleAddress.Kind.Stellar); + } + + function testTrailingMessageBytesRejected() public { + bytes[] memory p = new bytes[](1); + p[0] = hex"d1252dff012345"; + bytes memory m = bytes.concat(this.encode(APP, p), hex"00"); + vm.expectRevert(); + this.decode(m); + } +} From 42b3632f8c880ebc1ef26679435bc31752930b10 Mon Sep 17 00:00:00 2001 From: Alexander Date: Fri, 2 Oct 2026 16:10:18 +0400 Subject: [PATCH 08/14] refactor: move LayerZero oracle to its own PR --- .../oracles/layerzero/LayerZeroOracle.sol | 205 ------------------ test/oracle/transport/EndpointFixture.sol | 93 -------- test/oracle/transport/LayerZeroOracle.t.sol | 104 --------- 3 files changed, 402 deletions(-) delete mode 100644 src/integrations/oracles/layerzero/LayerZeroOracle.sol delete mode 100644 test/oracle/transport/EndpointFixture.sol delete mode 100644 test/oracle/transport/LayerZeroOracle.t.sol diff --git a/src/integrations/oracles/layerzero/LayerZeroOracle.sol b/src/integrations/oracles/layerzero/LayerZeroOracle.sol deleted file mode 100644 index 07f1c130..00000000 --- a/src/integrations/oracles/layerzero/LayerZeroOracle.sol +++ /dev/null @@ -1,205 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; - -import { BoundedOracle } from "../common/BoundedOracle.sol"; - -struct Origin { - uint32 srcEid; - bytes32 sender; - uint64 nonce; -} - -struct MessagingFee { - uint256 nativeFee; - uint256 lzTokenFee; -} - -struct MessagingReceipt { - bytes32 guid; - uint64 nonce; - MessagingFee fee; -} - -struct MessagingParams { - uint32 dstEid; - bytes32 receiver; - bytes message; - bytes options; - bool payInLzToken; -} - -struct SetConfigParam { - uint32 eid; - uint32 configType; - bytes config; -} - -interface IOracleEndpointV2 { - function quote( - MessagingParams calldata params, - address sender - ) external view returns (MessagingFee memory); - function send( - MessagingParams calldata params, - address refundAddress - ) external payable returns (MessagingReceipt memory); - function setSendLibrary( - address oapp, - uint32 eid, - address lib - ) external; - function setReceiveLibrary( - address oapp, - uint32 eid, - address lib, - uint256 gracePeriod - ) external; - function setConfig( - address oapp, - address lib, - SetConfigParam[] calldata params - ) external; -} - -/// Transparent OApp: authenticated Origin.sender is preserved, never replaced by a configured peer. -contract LayerZeroOracle is BoundedOracle { - struct UlnConfig { - uint64 confirmations; - uint8 requiredDVNCount; - uint8 optionalDVNCount; - uint8 optionalDVNThreshold; - address[] requiredDVNs; - address[] optionalDVNs; - } - - struct ExecutorConfig { - uint32 maxMessageSize; - address executor; - } - - struct Chain { - uint32 eid; - uint256 chainId; - address sendLibrary; - address receiveLibrary; - address executor; - uint64 sendConfirmations; - uint64 receiveConfirmations; - address[] sendDvns; - address[] receiveDvns; - } - IOracleEndpointV2 public immutable endpoint; - mapping(uint32 => uint256) public chainIds; - error OnlyEndpoint(); - error UnexpectedValue(); - - constructor( - address endpoint_, - Chain[] memory chains - ) { - if (endpoint_.code.length == 0 || chains.length == 0 || chains.length > 16) revert InvalidConfiguration(); - endpoint = IOracleEndpointV2(endpoint_); - for (uint256 i; i < chains.length; ++i) { - Chain memory c = chains[i]; - if ( - c.eid == 0 || c.chainId == 0 || chainIds[c.eid] != 0 || c.executor == address(0) - || c.sendLibrary == address(0) || c.receiveLibrary == address(0) - ) revert InvalidConfiguration(); - for (uint256 j; j < i; ++j) { - if (chains[j].chainId == c.chainId) revert InvalidConfiguration(); - } - chainIds[c.eid] = c.chainId; - endpoint.setSendLibrary(address(this), c.eid, c.sendLibrary); - endpoint.setReceiveLibrary(address(this), c.eid, c.receiveLibrary, 0); - SetConfigParam[] memory sendConfig = new SetConfigParam[](2); - sendConfig[0] = SetConfigParam(c.eid, 1, abi.encode(ExecutorConfig(uint32(MAX_MESSAGE), c.executor))); - sendConfig[1] = SetConfigParam(c.eid, 2, _uln(c.sendConfirmations, c.sendDvns)); - endpoint.setConfig(address(this), c.sendLibrary, sendConfig); - SetConfigParam[] memory receiveConfig = new SetConfigParam[](1); - receiveConfig[0] = SetConfigParam(c.eid, 2, _uln(c.receiveConfirmations, c.receiveDvns)); - endpoint.setConfig(address(this), c.receiveLibrary, receiveConfig); - } - } - - function _uln( - uint64 confirmations, - address[] memory dvns - ) private pure returns (bytes memory) { - // UlnBase reads type(uint64).max (NIL_CONFIRMATIONS) in an OApp config as literal zero confirmations. - if (confirmations == 0 || confirmations == type(uint64).max || dvns.length == 0 || dvns.length > 127) { - revert InvalidConfiguration(); - } - address previous; - for (uint256 i; i < dvns.length; ++i) { - if (dvns[i] <= previous) revert InvalidConfiguration(); - previous = dvns[i]; - } - // NIL_DVN_COUNT explicitly disables optional DVNs rather than inheriting a mutable default. - return abi.encode(UlnConfig(confirmations, uint8(dvns.length), 255, 0, dvns, new address[](0))); - } - - function quote( - uint32 dstEid, - bytes32 recipientOracle, - address source, - bytes[] calldata payloads, - bytes calldata options - ) external view returns (MessagingFee memory) { - _checkDestination(dstEid, options); - return endpoint.quote( - MessagingParams(dstEid, recipientOracle, _encode(source, payloads), options, false), address(this) - ); - } - - function submit( - uint32 dstEid, - bytes32 recipientOracle, - address source, - bytes[] calldata payloads, - bytes calldata options - ) external payable returns (MessagingReceipt memory) { - _checkDestination(dstEid, options); - return endpoint.send{ value: msg.value }( - MessagingParams(dstEid, recipientOracle, _export(source, payloads), options, false), msg.sender - ); - } - - function _checkDestination( - uint32 eid, - bytes calldata options - ) private view { - if (chainIds[eid] == 0) revert UnknownChain(); - _checkOptions(options); - } - - function allowInitializePath( - Origin calldata origin - ) external view returns (bool) { - return chainIds[origin.srcEid] != 0; - } - - function nextNonce( - uint32, - bytes32 - ) external pure returns (uint64) { - return 0; - } - - function oAppVersion() external pure returns (uint64, uint64) { - return (1, 1); - } - - function lzReceive( - Origin calldata origin, - bytes32, - bytes calldata message, - address, - bytes calldata - ) external payable { - if (msg.sender != address(endpoint)) revert OnlyEndpoint(); - if (msg.value != 0) revert UnexpectedValue(); - uint256 chain = chainIds[origin.srcEid]; - if (chain == 0) revert UnknownChain(); - _record(chain, origin.sender, message); - } -} diff --git a/test/oracle/transport/EndpointFixture.sol b/test/oracle/transport/EndpointFixture.sol deleted file mode 100644 index caa39e3f..00000000 --- a/test/oracle/transport/EndpointFixture.sol +++ /dev/null @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; -import { - LayerZeroOracle, - MessagingFee, - MessagingParams, - MessagingReceipt, - Origin, - SetConfigParam -} from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; - -contract EndpointFixture { - mapping(bytes32 => bool) public approvals; - mapping(bytes32 => bytes) public configs; - bytes public lastMessage; - bytes32 public lastRecipient; - address public lastSender; - uint64 public nonce; - - function setSendLibrary( - address oapp, - uint32 eid, - address lib - ) external { - require(msg.sender == oapp); - configs[keccak256(abi.encode(oapp, eid, "send"))] = abi.encode(lib); - } - - function setReceiveLibrary( - address oapp, - uint32 eid, - address lib, - uint256 grace - ) external { - require(msg.sender == oapp && grace == 0); - configs[keccak256(abi.encode(oapp, eid, "receive"))] = abi.encode(lib); - } - - function setConfig( - address oapp, - address lib, - SetConfigParam[] calldata params - ) external { - require(msg.sender == oapp); - for (uint256 i; i < params.length; ++i) { - configs[keccak256(abi.encode(oapp, lib, params[i].eid, params[i].configType))] = params[i].config; - } - } - - function quote( - MessagingParams calldata, - address - ) external pure returns (MessagingFee memory) { - return MessagingFee(10, 0); - } - - function send( - MessagingParams calldata p, - address refund - ) external payable returns (MessagingReceipt memory) { - require(msg.value >= 10 && !p.payInLzToken); - lastMessage = p.message; - lastRecipient = p.receiver; - lastSender = msg.sender; - if (msg.value > 10) { - (bool ok,) = refund.call{ value: msg.value - 10 }(""); - require(ok); - } - return MessagingReceipt(keccak256(abi.encode(msg.sender, ++nonce, p)), nonce, MessagingFee(10, 0)); - } - - function approve( - address receiver, - Origin memory origin, - bytes32 guid, - bytes memory message - ) external { - require(LayerZeroOracle(receiver).allowInitializePath(origin)); - approvals[keccak256(abi.encode(receiver, origin, guid, message))] = true; - } - - function deliver( - address receiver, - Origin memory origin, - bytes32 guid, - bytes memory message - ) external { - bytes32 key = keccak256(abi.encode(receiver, origin, guid, message)); - require(approvals[key], "unverified"); - delete approvals[key]; - LayerZeroOracle(receiver).lzReceive(origin, guid, message, msg.sender, ""); - } -} diff --git a/test/oracle/transport/LayerZeroOracle.t.sol b/test/oracle/transport/LayerZeroOracle.t.sol deleted file mode 100644 index 2ec0038b..00000000 --- a/test/oracle/transport/LayerZeroOracle.t.sol +++ /dev/null @@ -1,104 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; -import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; -import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; -import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; -import { BoundAttester } from "./BoundAttester.sol"; -import { EndpointFixture } from "./EndpointFixture.sol"; -import { Test } from "forge-std/Test.sol"; - -contract LayerZeroOracleTest is Test { - EndpointFixture endpoint; - LayerZeroOracle lz; - BoundAttester source; - bytes32 constant SENDER = keccak256("stellar oracle"); - bytes32 constant APP = keccak256("stellar settler"); - uint256 constant CHAIN = 0x53544c; - - function setUp() public { - endpoint = new EndpointFixture(); - source = new BoundAttester(); - LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); - address[] memory dvns = new address[](1); - dvns[0] = address(0x1234); - c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), 1, 1, dvns, dvns); - lz = new LayerZeroOracle(address(endpoint), c); - } - - receive() external payable { } - - function payloads() internal pure returns (bytes[] memory p) { - p = new bytes[](2); - p[0] = hex"d1252dff012345"; - p[1] = hex"830c1e1c987654"; - } - - function encode( - bytes32 application, - bytes[] calldata p - ) external pure returns (bytes memory) { - return MessageEncodingLib.encodeMessage(application, p); - } - - function options() internal pure returns (bytes memory) { - return abi.encodePacked(hex"000301001101", uint128(200_000)); - } - - function testLayerZeroExportReceiveReplayAndFees() public { - source.setOracle(address(lz)); - uint256 beforeBalance = address(this).balance; - lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); - assertEq(address(this).balance, beforeBalance - 10); - assertEq(endpoint.lastRecipient(), SENDER); - bytes memory m = this.encode(APP, payloads()); - Origin memory o = Origin(30600, SENDER, 1); - vm.expectRevert(); - lz.lzReceive(o, bytes32(0), m, address(this), ""); - endpoint.approve(address(lz), o, bytes32(0), m); - endpoint.deliver(address(lz), o, bytes32(0), m); - assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); - vm.expectRevert(); - endpoint.deliver(address(lz), o, bytes32(0), m); - } - - function testQuoteRejectsMissingOptionsAndUnknownChain() public { - vm.expectRevert(); - lz.quote(30600, SENDER, address(source), payloads(), hex""); - vm.expectRevert(); - lz.quote(999, SENDER, address(source), payloads(), options()); - } - - function testLayerZeroRejectsNilConfirmations() public { - address[] memory dvns = new address[](1); - dvns[0] = address(0x1234); - LayerZeroOracle.Chain[] memory c = new LayerZeroOracle.Chain[](1); - c[0] = LayerZeroOracle.Chain(30600, CHAIN, address(1), address(2), address(3), type(uint64).max, 1, dvns, dvns); - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); - new LayerZeroOracle(address(endpoint), c); - c[0].sendConfirmations = 1; - c[0].receiveConfirmations = type(uint64).max; - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); - new LayerZeroOracle(address(endpoint), c); - } - - function testMaximumBatchAndTupleChecks() public { - bytes[] memory p = new bytes[](4); - for (uint256 i; i < 4; ++i) { - p[i] = new bytes(684); - p[i][0] = bytes1(uint8(i)); - } - bytes memory m = this.encode(APP, p); - assertEq(m.length, 2778); - Origin memory o = Origin(30600, SENDER, 1); - endpoint.approve(address(lz), o, bytes32(0), m); - endpoint.deliver(address(lz), o, bytes32(0), m); - bytes memory proofs; - for (uint256 i; i < 4; ++i) { - proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); - } - lz.efficientRequireProven(proofs); - lz.efficientRequireProven(""); - vm.expectRevert(); - lz.efficientRequireProven(bytes.concat(proofs, hex"00")); - } -} From e226659bd866ff99b85834704948ab4775c01bd3 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 5 Oct 2026 09:31:26 +0400 Subject: [PATCH 09/14] refactor(oracles): share owner set-once route map; drop LayerZero-only option check --- .../oracles/axelar/AxelarOracle.sol | 25 +++++-------- .../oracles/common/BoundedOracle.sol | 10 ----- .../oracles/common/MappedOracle.sol | 37 +++++++++++++++++++ test/oracle/transport/AxelarOracle.t.sol | 7 ++-- 4 files changed, 50 insertions(+), 29 deletions(-) create mode 100644 src/integrations/oracles/common/MappedOracle.sol diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index aef0a81d..284efc36 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -1,9 +1,7 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { Ownable } from "openzeppelin/access/Ownable.sol"; - -import { BoundedOracle } from "../common/BoundedOracle.sol"; +import { MappedOracle } from "../common/MappedOracle.sol"; import { OracleAddress } from "../common/OracleAddress.sol"; import { SolanaEnvelope } from "./SolanaEnvelope.sol"; @@ -32,8 +30,8 @@ interface IAxelarNativeGasService { } /// Transparent Axelar GMP oracle with owner-set immutable chain maps (ChainMap conventions keyed by lowercase -/// Axelar name). Based on OIF PR #137; supports Stellar and Solana sender identities. -contract AxelarOracle is BoundedOracle, Ownable { +/// Axelar name); supports Stellar and Solana sender identities. +contract AxelarOracle is MappedOracle { enum DeliveryMode { Relayed, SelfRelay } struct Route { @@ -45,13 +43,10 @@ contract AxelarOracle is BoundedOracle, Ownable { uint256 public constant MAX_CHAIN_NAME = 20; IAxelarMessageGateway public immutable gateway; IAxelarNativeGasService public immutable gasService; - mapping(bytes32 => Route) private routes; - mapping(uint256 chainId => bytes32 nameKey) public reverseChainIdMap; + mapping(bytes32 nameKey => OracleAddress.Kind) private kinds; error NotApproved(); error InvalidFee(); - error AlreadySet(); - error ZeroValue(); event ChainMapConfigured(string name, uint256 chainId, OracleAddress.Kind kind); @@ -59,7 +54,7 @@ contract AxelarOracle is BoundedOracle, Ownable { address owner_, address gateway_, address gasService_ - ) Ownable(owner_) { + ) MappedOracle(owner_) { if (gateway_.code.length == 0 || gasService_.code.length == 0) revert InvalidConfiguration(); gateway = IAxelarMessageGateway(gateway_); gasService = IAxelarNativeGasService(gasService_); @@ -71,7 +66,6 @@ contract AxelarOracle is BoundedOracle, Ownable { uint256 chainId, OracleAddress.Kind kind ) external onlyOwner { - if (chainId == 0) revert ZeroValue(); bytes calldata b = bytes(name); if (b.length == 0 || b.length > MAX_CHAIN_NAME) revert InvalidConfiguration(); for (uint256 i; i < b.length; ++i) { @@ -79,9 +73,8 @@ contract AxelarOracle is BoundedOracle, Ownable { if (!((c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c == "-")) revert InvalidConfiguration(); } bytes32 key = keccak256(b); - if (routes[key].chainId != 0 || reverseChainIdMap[chainId] != 0) revert AlreadySet(); - routes[key] = Route(chainId, kind); - reverseChainIdMap[chainId] = key; + _setRoute(key, chainId); + kinds[key] = kind; emit ChainMapConfigured(name, chainId, kind); } @@ -100,8 +93,8 @@ contract AxelarOracle is BoundedOracle, Ownable { for (uint256 i; i < b.length; ++i) { if (b[i] >= 0x41 && b[i] <= 0x5a) b[i] = bytes1(uint8(b[i]) + 32); } - r = routes[keccak256(b)]; - if (r.chainId == 0) revert UnknownChain(); + bytes32 key = keccak256(b); + r = Route(_chainId(key), kinds[key]); canonical = string(b); } diff --git a/src/integrations/oracles/common/BoundedOracle.sol b/src/integrations/oracles/common/BoundedOracle.sol index 27e87fc4..1e34b3c0 100644 --- a/src/integrations/oracles/common/BoundedOracle.sol +++ b/src/integrations/oracles/common/BoundedOracle.sol @@ -11,7 +11,6 @@ abstract contract BoundedOracle is BaseInputOracle { error UnknownChain(); error MessageLimit(); error NotAttested(); - error InvalidOptions(); uint256 public constant MAX_PAYLOADS = 4; uint256 public constant MAX_PAYLOAD = 684; uint256 public constant MAX_MESSAGE = 2778; @@ -57,13 +56,4 @@ abstract contract BoundedOracle is BaseInputOracle { } } } - - /// A single Type-3 lzReceive option, positive gas, zero receiver value. No compose/drop/ordered options. - function _checkOptions( - bytes calldata options - ) internal pure { - if (options.length != 22 || bytes6(options[:6]) != hex"000301001101" || uint128(bytes16(options[6:22])) == 0) { - revert InvalidOptions(); - } - } } diff --git a/src/integrations/oracles/common/MappedOracle.sol b/src/integrations/oracles/common/MappedOracle.sol new file mode 100644 index 00000000..ee7722a8 --- /dev/null +++ b/src/integrations/oracles/common/MappedOracle.sol @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { Ownable } from "openzeppelin/access/Ownable.sol"; + +import { BoundedOracle } from "./BoundedOracle.sol"; + +/// Bounded transport oracle with owner-added, set-once, bijective route-key -> OIF chain maps. +abstract contract MappedOracle is BoundedOracle, Ownable { + error AlreadySet(); + error ZeroValue(); + + mapping(bytes32 routeKey => uint256 chainId) internal _chainIds; + mapping(uint256 chainId => bytes32 routeKey) public reverseChainIdMap; + + constructor( + address owner_ + ) Ownable(owner_) { } + + /// Map a nonzero route key to a nonzero OIF chain. Each key and chain ID is set once. + function _setRoute( + bytes32 key, + uint256 chainId + ) internal { + if (chainId == 0) revert ZeroValue(); + if (_chainIds[key] != 0 || reverseChainIdMap[chainId] != 0) revert AlreadySet(); + _chainIds[key] = chainId; + reverseChainIdMap[chainId] = key; + } + + function _chainId( + bytes32 key + ) internal view returns (uint256 chainId) { + chainId = _chainIds[key]; + if (chainId == 0) revert UnknownChain(); + } +} diff --git a/test/oracle/transport/AxelarOracle.t.sol b/test/oracle/transport/AxelarOracle.t.sol index b38e80be..23ee742d 100644 --- a/test/oracle/transport/AxelarOracle.t.sol +++ b/test/oracle/transport/AxelarOracle.t.sol @@ -2,6 +2,7 @@ pragma solidity ^0.8.26; import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; +import { MappedOracle } from "../../../src/integrations/oracles/common/MappedOracle.sol"; import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; import { BoundAttester } from "./BoundAttester.sol"; @@ -99,11 +100,11 @@ contract AxelarOracleTest is Test { vm.prank(address(0xBEEF)); vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); axelar.setChainMap("evm", 1, OracleAddress.Kind.Evm); - vm.expectRevert(AxelarOracle.ZeroValue.selector); + vm.expectRevert(MappedOracle.ZeroValue.selector); axelar.setChainMap("evm", 0, OracleAddress.Kind.Evm); - vm.expectRevert(AxelarOracle.AlreadySet.selector); + vm.expectRevert(MappedOracle.AlreadySet.selector); axelar.setChainMap("stellar", 2, OracleAddress.Kind.Evm); - vm.expectRevert(AxelarOracle.AlreadySet.selector); + vm.expectRevert(MappedOracle.AlreadySet.selector); axelar.setChainMap("evm", CHAIN, OracleAddress.Kind.Evm); string[4] memory bad = ["Evm", "", "abcdefghijklmnopqrstu", "e_vm"]; for (uint256 i; i < bad.length; ++i) { From 33e561c0c3a38ec1c77f55edc4c9b8eac8ea48a5 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 5 Oct 2026 09:32:40 +0400 Subject: [PATCH 10/14] feat(layerzero): owner-added set-once routes with per-route security pinning --- .../oracles/layerzero/LayerZeroOracle.sol | 232 ++++++++++++++++++ test/oracle/transport/EndpointFixture.sol | 93 +++++++ test/oracle/transport/LayerZeroOracle.t.sol | 138 +++++++++++ 3 files changed, 463 insertions(+) create mode 100644 src/integrations/oracles/layerzero/LayerZeroOracle.sol create mode 100644 test/oracle/transport/EndpointFixture.sol create mode 100644 test/oracle/transport/LayerZeroOracle.t.sol diff --git a/src/integrations/oracles/layerzero/LayerZeroOracle.sol b/src/integrations/oracles/layerzero/LayerZeroOracle.sol new file mode 100644 index 00000000..9486a3f3 --- /dev/null +++ b/src/integrations/oracles/layerzero/LayerZeroOracle.sol @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { MappedOracle } from "../common/MappedOracle.sol"; + +struct Origin { + uint32 srcEid; + bytes32 sender; + uint64 nonce; +} + +struct MessagingFee { + uint256 nativeFee; + uint256 lzTokenFee; +} + +struct MessagingReceipt { + bytes32 guid; + uint64 nonce; + MessagingFee fee; +} + +struct MessagingParams { + uint32 dstEid; + bytes32 receiver; + bytes message; + bytes options; + bool payInLzToken; +} + +struct SetConfigParam { + uint32 eid; + uint32 configType; + bytes config; +} + +interface IOracleEndpointV2 { + function quote( + MessagingParams calldata params, + address sender + ) external view returns (MessagingFee memory); + function send( + MessagingParams calldata params, + address refundAddress + ) external payable returns (MessagingReceipt memory); + function setSendLibrary( + address oapp, + uint32 eid, + address lib + ) external; + function setReceiveLibrary( + address oapp, + uint32 eid, + address lib, + uint256 gracePeriod + ) external; + function setConfig( + address oapp, + address lib, + SetConfigParam[] calldata params + ) external; +} + +/// Transparent OApp: authenticated Origin.sender is preserved, never replaced by a configured peer. The owner adds +/// set-once routes; each route pins its own libraries, executor and DVN configuration when it is added. +contract LayerZeroOracle is MappedOracle { + struct UlnConfig { + uint64 confirmations; + uint8 requiredDVNCount; + uint8 optionalDVNCount; + uint8 optionalDVNThreshold; + address[] requiredDVNs; + address[] optionalDVNs; + } + + struct ExecutorConfig { + uint32 maxMessageSize; + address executor; + } + + struct Security { + address sendLibrary; + address receiveLibrary; + address executor; + uint64 sendConfirmations; + uint64 receiveConfirmations; + address[] sendDvns; + address[] receiveDvns; + } + + IOracleEndpointV2 public immutable endpoint; + + error OnlyEndpoint(); + error UnexpectedValue(); + error InvalidOptions(); + + event ChainMapConfigured(uint32 eid, uint256 chainId); + + constructor( + address owner_, + address endpoint_ + ) MappedOracle(owner_) { + if (endpoint_.code.length == 0) revert InvalidConfiguration(); + endpoint = IOracleEndpointV2(endpoint_); + } + + /// Set an immutable map from a LayerZero endpoint ID to an OIF chain and pin the route's security configuration. + /// Each endpoint ID and chain ID is set once; paths open only after this call. + function setChainMap( + uint32 eid, + uint256 chainId, + Security calldata s + ) external onlyOwner { + if (eid == 0) revert ZeroValue(); + if (s.executor == address(0) || s.sendLibrary == address(0) || s.receiveLibrary == address(0)) { + revert InvalidConfiguration(); + } + _setRoute(_key(eid), chainId); + endpoint.setSendLibrary(address(this), eid, s.sendLibrary); + endpoint.setReceiveLibrary(address(this), eid, s.receiveLibrary, 0); + SetConfigParam[] memory sendConfig = new SetConfigParam[](2); + sendConfig[0] = SetConfigParam(eid, 1, abi.encode(ExecutorConfig(uint32(MAX_MESSAGE), s.executor))); + sendConfig[1] = SetConfigParam(eid, 2, _uln(s.sendConfirmations, s.sendDvns)); + endpoint.setConfig(address(this), s.sendLibrary, sendConfig); + SetConfigParam[] memory receiveConfig = new SetConfigParam[](1); + receiveConfig[0] = SetConfigParam(eid, 2, _uln(s.receiveConfirmations, s.receiveDvns)); + endpoint.setConfig(address(this), s.receiveLibrary, receiveConfig); + emit ChainMapConfigured(eid, chainId); + } + + function route( + uint32 eid + ) external view returns (uint256) { + return _chainId(_key(eid)); + } + + function _key( + uint32 eid + ) private pure returns (bytes32) { + return bytes32(uint256(eid)); + } + + function _uln( + uint64 confirmations, + address[] memory dvns + ) private pure returns (bytes memory) { + // UlnBase reads type(uint64).max (NIL_CONFIRMATIONS) in an OApp config as literal zero confirmations. + if (confirmations == 0 || confirmations == type(uint64).max || dvns.length == 0 || dvns.length > 127) { + revert InvalidConfiguration(); + } + address previous; + for (uint256 i; i < dvns.length; ++i) { + if (dvns[i] <= previous) revert InvalidConfiguration(); + previous = dvns[i]; + } + // NIL_DVN_COUNT explicitly disables optional DVNs rather than inheriting a mutable default. + return abi.encode(UlnConfig(confirmations, uint8(dvns.length), 255, 0, dvns, new address[](0))); + } + + function quote( + uint32 dstEid, + bytes32 recipientOracle, + address source, + bytes[] calldata payloads, + bytes calldata options + ) external view returns (MessagingFee memory) { + _checkDestination(dstEid, options); + return endpoint.quote( + MessagingParams(dstEid, recipientOracle, _encode(source, payloads), options, false), address(this) + ); + } + + function submit( + uint32 dstEid, + bytes32 recipientOracle, + address source, + bytes[] calldata payloads, + bytes calldata options + ) external payable returns (MessagingReceipt memory) { + _checkDestination(dstEid, options); + return endpoint.send{ value: msg.value }( + MessagingParams(dstEid, recipientOracle, _export(source, payloads), options, false), msg.sender + ); + } + + function _checkDestination( + uint32 eid, + bytes calldata options + ) private view { + _chainId(_key(eid)); + _checkOptions(options); + } + + /// A single Type-3 lzReceive option, positive gas, zero receiver value. No compose/drop/ordered options. + function _checkOptions( + bytes calldata options + ) private pure { + if (options.length != 22 || bytes6(options[:6]) != hex"000301001101" || uint128(bytes16(options[6:22])) == 0) { + revert InvalidOptions(); + } + } + + function allowInitializePath( + Origin calldata origin + ) external view returns (bool) { + return _chainIds[_key(origin.srcEid)] != 0; + } + + function nextNonce( + uint32, + bytes32 + ) external pure returns (uint64) { + return 0; + } + + function oAppVersion() external pure returns (uint64, uint64) { + return (1, 1); + } + + function lzReceive( + Origin calldata origin, + bytes32, + bytes calldata message, + address, + bytes calldata + ) external payable { + if (msg.sender != address(endpoint)) revert OnlyEndpoint(); + if (msg.value != 0) revert UnexpectedValue(); + uint256 chain = _chainId(_key(origin.srcEid)); + _record(chain, origin.sender, message); + } +} diff --git a/test/oracle/transport/EndpointFixture.sol b/test/oracle/transport/EndpointFixture.sol new file mode 100644 index 00000000..caa39e3f --- /dev/null +++ b/test/oracle/transport/EndpointFixture.sol @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { + LayerZeroOracle, + MessagingFee, + MessagingParams, + MessagingReceipt, + Origin, + SetConfigParam +} from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; + +contract EndpointFixture { + mapping(bytes32 => bool) public approvals; + mapping(bytes32 => bytes) public configs; + bytes public lastMessage; + bytes32 public lastRecipient; + address public lastSender; + uint64 public nonce; + + function setSendLibrary( + address oapp, + uint32 eid, + address lib + ) external { + require(msg.sender == oapp); + configs[keccak256(abi.encode(oapp, eid, "send"))] = abi.encode(lib); + } + + function setReceiveLibrary( + address oapp, + uint32 eid, + address lib, + uint256 grace + ) external { + require(msg.sender == oapp && grace == 0); + configs[keccak256(abi.encode(oapp, eid, "receive"))] = abi.encode(lib); + } + + function setConfig( + address oapp, + address lib, + SetConfigParam[] calldata params + ) external { + require(msg.sender == oapp); + for (uint256 i; i < params.length; ++i) { + configs[keccak256(abi.encode(oapp, lib, params[i].eid, params[i].configType))] = params[i].config; + } + } + + function quote( + MessagingParams calldata, + address + ) external pure returns (MessagingFee memory) { + return MessagingFee(10, 0); + } + + function send( + MessagingParams calldata p, + address refund + ) external payable returns (MessagingReceipt memory) { + require(msg.value >= 10 && !p.payInLzToken); + lastMessage = p.message; + lastRecipient = p.receiver; + lastSender = msg.sender; + if (msg.value > 10) { + (bool ok,) = refund.call{ value: msg.value - 10 }(""); + require(ok); + } + return MessagingReceipt(keccak256(abi.encode(msg.sender, ++nonce, p)), nonce, MessagingFee(10, 0)); + } + + function approve( + address receiver, + Origin memory origin, + bytes32 guid, + bytes memory message + ) external { + require(LayerZeroOracle(receiver).allowInitializePath(origin)); + approvals[keccak256(abi.encode(receiver, origin, guid, message))] = true; + } + + function deliver( + address receiver, + Origin memory origin, + bytes32 guid, + bytes memory message + ) external { + bytes32 key = keccak256(abi.encode(receiver, origin, guid, message)); + require(approvals[key], "unverified"); + delete approvals[key]; + LayerZeroOracle(receiver).lzReceive(origin, guid, message, msg.sender, ""); + } +} diff --git a/test/oracle/transport/LayerZeroOracle.t.sol b/test/oracle/transport/LayerZeroOracle.t.sol new file mode 100644 index 00000000..44135494 --- /dev/null +++ b/test/oracle/transport/LayerZeroOracle.t.sol @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; +import { MappedOracle } from "../../../src/integrations/oracles/common/MappedOracle.sol"; +import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; +import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { BoundAttester } from "./BoundAttester.sol"; +import { EndpointFixture } from "./EndpointFixture.sol"; +import { Test } from "forge-std/Test.sol"; +import { Ownable } from "openzeppelin/access/Ownable.sol"; + +contract LayerZeroOracleTest is Test { + EndpointFixture endpoint; + LayerZeroOracle lz; + BoundAttester source; + bytes32 constant SENDER = keccak256("stellar oracle"); + bytes32 constant APP = keccak256("stellar settler"); + uint256 constant CHAIN = 0x53544c; + + function setUp() public { + endpoint = new EndpointFixture(); + source = new BoundAttester(); + lz = new LayerZeroOracle(address(this), address(endpoint)); + lz.setChainMap(30600, CHAIN, security(1, 1)); + } + + function security( + uint64 send, + uint64 recv + ) internal pure returns (LayerZeroOracle.Security memory s) { + address[] memory dvns = new address[](1); + dvns[0] = address(0x1234); + s = LayerZeroOracle.Security(address(1), address(2), address(3), send, recv, dvns, dvns); + } + + receive() external payable { } + + function payloads() internal pure returns (bytes[] memory p) { + p = new bytes[](2); + p[0] = hex"d1252dff012345"; + p[1] = hex"830c1e1c987654"; + } + + function encode( + bytes32 application, + bytes[] calldata p + ) external pure returns (bytes memory) { + return MessageEncodingLib.encodeMessage(application, p); + } + + function options() internal pure returns (bytes memory) { + return abi.encodePacked(hex"000301001101", uint128(200_000)); + } + + function testLayerZeroExportReceiveReplayAndFees() public { + source.setOracle(address(lz)); + uint256 beforeBalance = address(this).balance; + lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); + assertEq(address(this).balance, beforeBalance - 10); + assertEq(endpoint.lastRecipient(), SENDER); + bytes memory m = this.encode(APP, payloads()); + Origin memory o = Origin(30600, SENDER, 1); + vm.expectRevert(); + lz.lzReceive(o, bytes32(0), m, address(this), ""); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); + vm.expectRevert(); + endpoint.deliver(address(lz), o, bytes32(0), m); + } + + function testQuoteRejectsMissingOptionsAndUnknownChain() public { + vm.expectRevert(); + lz.quote(30600, SENDER, address(source), payloads(), hex""); + vm.expectRevert(); + lz.quote(999, SENDER, address(source), payloads(), options()); + } + + function testLayerZeroRejectsNilConfirmations() public { + LayerZeroOracle o = new LayerZeroOracle(address(this), address(endpoint)); + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, security(type(uint64).max, 1)); + vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, security(1, type(uint64).max)); + } + + function testLayerZeroChainMapOwnerSetOnce() public { + vm.prank(address(0xBEEF)); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); + lz.setChainMap(30601, 1, security(1, 1)); + vm.expectRevert(MappedOracle.ZeroValue.selector); + lz.setChainMap(0, 1, security(1, 1)); + vm.expectRevert(MappedOracle.ZeroValue.selector); + lz.setChainMap(30601, 0, security(1, 1)); + vm.expectRevert(MappedOracle.AlreadySet.selector); + lz.setChainMap(30600, 1, security(1, 1)); + vm.expectRevert(MappedOracle.AlreadySet.selector); + lz.setChainMap(30601, CHAIN, security(1, 1)); + + assertFalse(lz.allowInitializePath(Origin(30601, SENDER, 1))); + vm.expectEmit(address(lz)); + emit LayerZeroOracle.ChainMapConfigured(30601, 1); + lz.setChainMap(30601, 1, security(1, 1)); + assertTrue(lz.allowInitializePath(Origin(30601, SENDER, 1))); + assertEq(endpoint.configs(keccak256(abi.encode(address(lz), uint32(30601), "send"))), abi.encode(address(1))); + assertEq(lz.reverseChainIdMap(1), bytes32(uint256(30601))); + + for (uint32 i; i < 17; ++i) { + lz.setChainMap(30700 + i, 2000 + i, security(1, 1)); + } + assertEq(lz.route(30716), 2016); + + lz.renounceOwnership(); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(this))); + lz.setChainMap(30800, 3000, security(1, 1)); + } + + function testMaximumBatchAndTupleChecks() public { + bytes[] memory p = new bytes[](4); + for (uint256 i; i < 4; ++i) { + p[i] = new bytes(684); + p[i][0] = bytes1(uint8(i)); + } + bytes memory m = this.encode(APP, p); + assertEq(m.length, 2778); + Origin memory o = Origin(30600, SENDER, 1); + endpoint.approve(address(lz), o, bytes32(0), m); + endpoint.deliver(address(lz), o, bytes32(0), m); + bytes memory proofs; + for (uint256 i; i < 4; ++i) { + proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); + } + lz.efficientRequireProven(proofs); + lz.efficientRequireProven(""); + vm.expectRevert(); + lz.efficientRequireProven(bytes.concat(proofs, hex"00")); + } +} From 81de0325fbbc3b89553ed460f69f0a5ab89cf8b9 Mon Sep 17 00:00:00 2001 From: Alexander Date: Mon, 12 Oct 2026 13:28:56 +0400 Subject: [PATCH 11/14] feat(axelar): add AxelarOracle deployment script --- script/AxelarOracle.s.sol | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 script/AxelarOracle.s.sol diff --git a/script/AxelarOracle.s.sol b/script/AxelarOracle.s.sol new file mode 100644 index 00000000..ddf34bb0 --- /dev/null +++ b/script/AxelarOracle.s.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { Script } from "forge-std/Script.sol"; +import { console } from "forge-std/console.sol"; + +import { AxelarOracle } from "../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { OracleAddress } from "../src/integrations/oracles/common/OracleAddress.sol"; + +/// @notice Deploys an AxelarOracle on Base and maps Axelar's `stellar` chain to LI.FI's Stellar chain ID. +/// The map is permanent and is set only when `owner` is the broadcasting account. +/// +/// Usage: +/// forge script script/AxelarOracle.s.sol:DeployAxelarOracle --sig 'run(address)' \ +/// --rpc-url https://mainnet.base.org --ledger --sender --broadcast +contract DeployAxelarOracle is Script { + address constant GATEWAY = 0xe432150cce91c13a887f7D836923d5597adD8E31; + address constant GAS_SERVICE = 0x2d5d7d31F671F86C782533cc367F14109a082712; + uint256 constant STELLAR_CHAIN_ID = 1201081091099710; + + function run( + address owner + ) external returns (AxelarOracle oracle) { + require(block.chainid == 8453, "not Base"); + + vm.startBroadcast(); + (, address sender,) = vm.readCallers(); + oracle = new AxelarOracle(owner, GATEWAY, GAS_SERVICE); + if (sender == owner) oracle.setChainMap("stellar", STELLAR_CHAIN_ID, OracleAddress.Kind.Stellar); + vm.stopBroadcast(); + + console.log("AxelarOracle", address(oracle)); + if (sender != owner) console.log("Owner must still call setChainMap(\"stellar\", 1201081091099710, 1)"); + } +} From 8052144703591c7ff1f1ec3c3781455371d18f9b Mon Sep 17 00:00:00 2001 From: Alexander Date: Tue, 13 Oct 2026 16:23:06 +0400 Subject: [PATCH 12/14] Separate Axelar deployment from chain-map configuration --- README.md | 74 +++++++++++++++++++++++++++++++++++++ script/AxelarChainMap.s.sol | 26 +++++++++++++ script/AxelarOracle.s.sol | 36 +++++++----------- 3 files changed, 113 insertions(+), 23 deletions(-) create mode 100644 script/AxelarChainMap.s.sol diff --git a/README.md b/README.md index b7b6ad7a..5db01801 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,80 @@ forge coverage --no-match-coverage "(script|test|wormhole/external/wormhole|worm forge script deploy --sig "run(string[])" "[]" --account --slow --multi --isolate --always-use-create-2-factory --verify --broadcast [-vvvv] ``` +### Axelar deployment + +`script/AxelarOracle.s.sol:DeployAxelarOracle` deploys with CREATE2 (`salt = 0`), matching the +other oracle deployment scripts. Pass the mapping owner, local gateway, and local gas service +explicitly. The deployer can differ from the owner. Deployment does **not** configure any chain maps +and is not restricted to Base or Arbitrum. + +Use verified provider addresses for the target network from +[Axelar's mainnet contract reference](https://docs.axelar.dev/dev/reference/mainnet-contract-addresses/). +On Base (8453) and Arbitrum (42161), both providers currently use the addresses in this example: + +```shell +OWNER=0x712E90032d8f44bE276A903E1769d64dD1C7F45a +GATEWAY=0xe432150cce91c13a887f7D836923d5597adD8E31 +GAS_SERVICE=0x2d5d7d31F671F86C782533cc367F14109a082712 +RPC=https://arb1.arbitrum.io/rpc + +# Verify the target network and provider code before signing. +cast chain-id --rpc-url "$RPC" +cast code "$GATEWAY" --rpc-url "$RPC" +cast code "$GAS_SERVICE" --rpc-url "$RPC" + +# Dry run; no transactions are sent. +forge script script/AxelarOracle.s.sol:DeployAxelarOracle \ + --sig 'deploy(address,address,address)' "$OWNER" "$GATEWAY" "$GAS_SERVICE" \ + --rpc-url "$RPC" --account deployer + +# Deployment only; the deployer signs, not necessarily OWNER. +forge script script/AxelarOracle.s.sol:DeployAxelarOracle \ + --sig 'deploy(address,address,address)' "$OWNER" "$GATEWAY" "$GAS_SERVICE" \ + --rpc-url "$RPC" --account deployer --broadcast +``` + +Set `ORACLE` to the returned deployed address. Verify `owner()(address)`, `gateway()(address)`, +and `gasService()(address)` with `cast call`. CREATE2 prediction depends on the factory, salt, +bytecode, and all constructor arguments, not the sender's nonce. Fund the deployer above Forge's +estimated transaction cost, with headroom for fee changes; a dry run does not prove sufficient funds. + +#### Separate chain-map configuration + +`script/AxelarChainMap.s.sol:ConfigureAxelarChainMap` configures one route per invocation. +The signing account must control the oracle's owner. Axelar names must be lowercase; names and +canonical OIF chain IDs are set-once. Repeated configuration reverts rather than overwriting a route. +Address kinds are `Evm = 0`, `Stellar = 1`, and `Solana = 2`. + +```shell +# Example: configure the Base route on an Arbitrum oracle. Dry-run first. +forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ + --sig 'setChainMap(address,string,uint256,uint8)' "$ORACLE" base 8453 0 \ + --rpc-url "$RPC" --account owner + +# Only after checking the route and signing account: +forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ + --sig 'setChainMap(address,string,uint256,uint8)' "$ORACLE" base 8453 0 \ + --rpc-url "$RPC" --account owner --broadcast + +cast call "$ORACLE" 'route(string)((uint256,uint8))' base --rpc-url "$RPC" +# Expected: (8453, 0). +``` + +The sibling [`intents-oracle-owner`](../../intents-oracle-owner/README.md) repository keeps its +ceremony owner keys in GitHub Actions, separately from deployment. Use the target chain's +`expectedOwner` from its reviewed configuration when that owner is intended; the example above uses +its current Base/Arbitrum owner. Its reconciler currently supports only numeric +`setChainMap(uint256,uint256)`, **not** Axelar's `setChainMap(string,uint256,uint8)`. +Assigning that owner does not enable automated Axelar configuration: the reconciler needs Axelar +support before its ceremony key can configure routes. The local configuration script is for owners +with an available signer; it does not access GitHub-held keys. + +Route checks confirm configuration, not live GMP delivery. Orders must use the actual remote oracle +addresses. EVM `submit` calls use zero `destinationConfig`; relayed delivery requires a positive, +off-chain-estimated native gas payment. Self-relay uses zero value and still requires gateway +approval before `execute`. + ## License Notice This project is licensed under the **[GNU Lesser General Public License v3.0 only (LGPL-3.0-only)](/LICENSE)**. diff --git a/script/AxelarChainMap.s.sol b/script/AxelarChainMap.s.sol new file mode 100644 index 00000000..4b6eb50a --- /dev/null +++ b/script/AxelarChainMap.s.sol @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { Script } from "forge-std/Script.sol"; + +import { AxelarOracle } from "../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { OracleAddress } from "../src/integrations/oracles/common/OracleAddress.sol"; + +/// @notice Configures one permanent Axelar route; broadcast with the oracle's owner. +/// Kind: Evm = 0, Stellar = 1, Solana = 2. Names must be lowercase Axelar chain names. +/// +/// Usage (omit --broadcast for a dry run): +/// forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ +/// --sig 'setChainMap(address,string,uint256,uint8)' \ +/// --rpc-url --account owner --broadcast +contract ConfigureAxelarChainMap is Script { + function setChainMap( + address oracle, + string calldata name, + uint256 chainId, + OracleAddress.Kind kind + ) external { + vm.broadcast(); + AxelarOracle(oracle).setChainMap(name, chainId, kind); + } +} diff --git a/script/AxelarOracle.s.sol b/script/AxelarOracle.s.sol index ddf34bb0..2e6228f3 100644 --- a/script/AxelarOracle.s.sol +++ b/script/AxelarOracle.s.sol @@ -2,34 +2,24 @@ pragma solidity ^0.8.26; import { Script } from "forge-std/Script.sol"; -import { console } from "forge-std/console.sol"; import { AxelarOracle } from "../src/integrations/oracles/axelar/AxelarOracle.sol"; -import { OracleAddress } from "../src/integrations/oracles/common/OracleAddress.sol"; -/// @notice Deploys an AxelarOracle on Base and maps Axelar's `stellar` chain to LI.FI's Stellar chain ID. -/// The map is permanent and is set only when `owner` is the broadcasting account. +/// @notice Deploys an AxelarOracle without configuring chain maps. +/// Uses CREATE2 with salt zero, matching the other oracle deployment scripts. +/// The owner need not be the broadcasting account. /// -/// Usage: -/// forge script script/AxelarOracle.s.sol:DeployAxelarOracle --sig 'run(address)' \ -/// --rpc-url https://mainnet.base.org --ledger --sender --broadcast +/// Usage (omit --broadcast for a dry run): +/// forge script script/AxelarOracle.s.sol:DeployAxelarOracle \ +/// --sig 'deploy(address,address,address)' \ +/// --rpc-url --account deployer --broadcast contract DeployAxelarOracle is Script { - address constant GATEWAY = 0xe432150cce91c13a887f7D836923d5597adD8E31; - address constant GAS_SERVICE = 0x2d5d7d31F671F86C782533cc367F14109a082712; - uint256 constant STELLAR_CHAIN_ID = 1201081091099710; - - function run( - address owner + function deploy( + address owner, + address gateway, + address gasService ) external returns (AxelarOracle oracle) { - require(block.chainid == 8453, "not Base"); - - vm.startBroadcast(); - (, address sender,) = vm.readCallers(); - oracle = new AxelarOracle(owner, GATEWAY, GAS_SERVICE); - if (sender == owner) oracle.setChainMap("stellar", STELLAR_CHAIN_ID, OracleAddress.Kind.Stellar); - vm.stopBroadcast(); - - console.log("AxelarOracle", address(oracle)); - if (sender != owner) console.log("Owner must still call setChainMap(\"stellar\", 1201081091099710, 1)"); + vm.broadcast(); + oracle = new AxelarOracle{ salt: bytes32(0) }(owner, gateway, gasService); } } From b8a41781498acbfb57534c8dfa14867bb56c7e0f Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 14 Oct 2026 18:53:34 +0400 Subject: [PATCH 13/14] refactor(axelar): build AxelarOracle on shared ChainMap Drop MappedOracle/BoundedOracle. The oracle now inherits ChainMap with the key being the ASCII-lowercased Axelar name packed left-aligned into a uint256, so reverseChainIdMap yields the name. - submit takes the destination OIF chain ID and the recipient's Axelar address string; a nonzero destinationConfig selects the Solana envelope. - execute infers the sender format (0x hex, Stellar StrKey, Solana base58) and records proofs like HyperlaneOracle. - Names are 1-32 bytes without NUL, no character set imposed; packing lives in the AxelarChainName library (word-at-a-time lowercasing). - No Stellar message limits on EVM; destinations enforce their own. - ChainMap.setChainMap is public virtual so the oracle can validate keys. - OracleAddress moves to axelar/ and is decode-only. - Chain-map script takes (oracle, name, chainId); README updated. - Axelar tests move to test/oracle/axelar, with exhaustive key tests. --- README.md | 27 +- script/AxelarChainMap.s.sol | 10 +- snapshots/inputSettler.json | 35 +-- snapshots/oracle.json | 20 +- snapshots/outputSettler.json | 7 +- .../oracles/axelar/AxelarChainName.sol | 54 ++++ .../oracles/axelar/AxelarOracle.sol | 130 +++++----- .../oracles/axelar/OracleAddress.sol | 98 +++++++ .../oracles/common/BoundedOracle.sol | 59 ----- .../oracles/common/MappedOracle.sol | 37 --- .../oracles/common/OracleAddress.sol | 121 --------- src/oracles/ChainMap.sol | 2 +- test/oracle/axelar/AddressStrings.sol | 67 +++++ test/oracle/axelar/AxelarChainName.t.sol | 208 +++++++++++++++ test/oracle/axelar/AxelarOracle.t.sol | 240 ++++++++++++++++++ .../{transport => axelar}/BoundAttester.sol | 0 .../{transport => axelar}/GatewayFixture.sol | 0 .../{transport => axelar}/OracleAddress.t.sol | 60 +++-- test/oracle/transport/AxelarOracle.t.sol | 163 ------------ 19 files changed, 808 insertions(+), 530 deletions(-) create mode 100644 src/integrations/oracles/axelar/AxelarChainName.sol create mode 100644 src/integrations/oracles/axelar/OracleAddress.sol delete mode 100644 src/integrations/oracles/common/BoundedOracle.sol delete mode 100644 src/integrations/oracles/common/MappedOracle.sol delete mode 100644 src/integrations/oracles/common/OracleAddress.sol create mode 100644 test/oracle/axelar/AddressStrings.sol create mode 100644 test/oracle/axelar/AxelarChainName.t.sol create mode 100644 test/oracle/axelar/AxelarOracle.t.sol rename test/oracle/{transport => axelar}/BoundAttester.sol (100%) rename test/oracle/{transport => axelar}/GatewayFixture.sol (100%) rename test/oracle/{transport => axelar}/OracleAddress.t.sol (63%) delete mode 100644 test/oracle/transport/AxelarOracle.t.sol diff --git a/README.md b/README.md index 5db01801..dc3be0eb 100644 --- a/README.md +++ b/README.md @@ -96,36 +96,37 @@ estimated transaction cost, with headroom for fee changes; a dry run does not pr `script/AxelarChainMap.s.sol:ConfigureAxelarChainMap` configures one route per invocation. The signing account must control the oracle's owner. Axelar names must be lowercase; names and canonical OIF chain IDs are set-once. Repeated configuration reverts rather than overwriting a route. -Address kinds are `Evm = 0`, `Stellar = 1`, and `Solana = 2`. ```shell # Example: configure the Base route on an Arbitrum oracle. Dry-run first. forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ - --sig 'setChainMap(address,string,uint256,uint8)' "$ORACLE" base 8453 0 \ + --sig 'setChainMap(address,string,uint256)' "$ORACLE" base 8453 \ --rpc-url "$RPC" --account owner # Only after checking the route and signing account: forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ - --sig 'setChainMap(address,string,uint256,uint8)' "$ORACLE" base 8453 0 \ + --sig 'setChainMap(address,string,uint256)' "$ORACLE" base 8453 \ --rpc-url "$RPC" --account owner --broadcast -cast call "$ORACLE" 'route(string)((uint256,uint8))' base --rpc-url "$RPC" -# Expected: (8453, 0). +cast call "$ORACLE" 'reverseChainIdMap(uint256)(bytes32)' 8453 --rpc-url "$RPC" +# Expected: $(cast --format-bytes32-string base), the lowercase name packed left-aligned. ``` The sibling [`intents-oracle-owner`](../../intents-oracle-owner/README.md) repository keeps its ceremony owner keys in GitHub Actions, separately from deployment. Use the target chain's `expectedOwner` from its reviewed configuration when that owner is intended; the example above uses -its current Base/Arbitrum owner. Its reconciler currently supports only numeric -`setChainMap(uint256,uint256)`, **not** Axelar's `setChainMap(string,uint256,uint8)`. -Assigning that owner does not enable automated Axelar configuration: the reconciler needs Axelar -support before its ceremony key can configure routes. The local configuration script is for owners +its current Base/Arbitrum owner. Axelar uses the numeric `setChainMap(uint256,uint256)` that its +reconciler already supports. The key is `uint256(bytes32(bytes(lowercaseName)))`; the oracle +rejects keys that are not packed lowercase names. The local configuration script is for owners with an available signer; it does not access GitHub-held keys. -Route checks confirm configuration, not live GMP delivery. Orders must use the actual remote oracle -addresses. EVM `submit` calls use zero `destinationConfig`; relayed delivery requires a positive, -off-chain-estimated native gas payment. Self-relay uses zero value and still requires gateway -approval before `execute`. +Route checks confirm configuration, not live GMP delivery. `submit` takes the destination's OIF +chain ID and the destination oracle's Axelar address string (EVM `0x…`, Stellar `C…` StrKey, Solana +base58), passed through unchecked. Use a nonzero `destinationConfig` only for Solana destinations; +it selects the Borsh envelope. Clients split batches to meet the destination's limits: Stellar +allows 1–4 payloads of ≤684 bytes, and Solana allows one payload of ≤320 bytes. Relayed delivery +requires a positive, off-chain-estimated native gas payment. Self-relay uses zero value and still +requires gateway approval before `execute`. ## License Notice diff --git a/script/AxelarChainMap.s.sol b/script/AxelarChainMap.s.sol index 4b6eb50a..09ff8183 100644 --- a/script/AxelarChainMap.s.sol +++ b/script/AxelarChainMap.s.sol @@ -4,23 +4,21 @@ pragma solidity ^0.8.26; import { Script } from "forge-std/Script.sol"; import { AxelarOracle } from "../src/integrations/oracles/axelar/AxelarOracle.sol"; -import { OracleAddress } from "../src/integrations/oracles/common/OracleAddress.sol"; /// @notice Configures one permanent Axelar route; broadcast with the oracle's owner. -/// Kind: Evm = 0, Stellar = 1, Solana = 2. Names must be lowercase Axelar chain names. +/// Names must be lowercase Axelar chain names; the oracle rejects anything else. /// /// Usage (omit --broadcast for a dry run): /// forge script script/AxelarChainMap.s.sol:ConfigureAxelarChainMap \ -/// --sig 'setChainMap(address,string,uint256,uint8)' \ +/// --sig 'setChainMap(address,string,uint256)' \ /// --rpc-url --account owner --broadcast contract ConfigureAxelarChainMap is Script { function setChainMap( address oracle, string calldata name, - uint256 chainId, - OracleAddress.Kind kind + uint256 chainId ) external { vm.broadcast(); - AxelarOracle(oracle).setChainMap(name, chainId, kind); + AxelarOracle(oracle).setChainMap(uint256(bytes32(bytes(name))), chainId); } } diff --git a/snapshots/inputSettler.json b/snapshots/inputSettler.json index d3902756..e6f1d105 100644 --- a/snapshots/inputSettler.json +++ b/snapshots/inputSettler.json @@ -1,28 +1,13 @@ { - "BasePurchaseOrder": "138441", - "CompactFinaliseFor": "126996", - "CompactFinaliseSelf": "119560", - "CompactFinaliseTo": "119560", - "EscrowFinalise": "46544", - "IntegrationCoinFill": "89886", - "IntegrationCompactFinaliseSelf": "150381", - "IntegrationWormholeReceiveMessage": "73594", - "IntegrationWormholeSubmit": "42516", - "broadcast": "14904", - "compactFinaliseSelfWithFee": "189123", - "depositAndRegisterFor": "129887", - "escrowFinaliseSelfWithFee": "106637", - "escrowFinaliseWithSignature": "53732", - "escrowOpen": "57180", - "escrowOpenFor3009Single": "87859", - "escrowOpenFor3009SingleArray": "94003", - "escrowOpenFor3009Two": "145099", - "escrowOpenForMsgSender": "57339", - "escrowOpenForPermit2": "95283", - "escrowRefundOnNonFill": "21029", + "CompactFinaliseFor": "162638", + "CompactFinaliseSelf": "153798", + "CompactFinaliseTo": "153798", + "IntegrationCoinFill": "89862", + "IntegrationCompactFinaliseSelf": "152843", + "IntegrationWormholeReceiveMessage": "73558", + "IntegrationWormholeSubmit": "42492", + "broadcast": "43912", + "depositAndRegisterFor": "163659", "maxTimestamp1": "461", - "minTimestamp1": "483", - "tronEscrowFinaliseSelfWithFee": "111068", - "validate2Fills": "9617", - "validate2FillsMultipleSolvers": "9617" + "minTimestamp1": "483" } \ No newline at end of file diff --git a/snapshots/oracle.json b/snapshots/oracle.json index 55a7d577..c6954eca 100644 --- a/snapshots/oracle.json +++ b/snapshots/oracle.json @@ -1,18 +1,6 @@ { - "bitcoinFinaliseDispute": "63284", - "bitcoinOPVerify": "87733", - "bitcoinOutputClaim": "99799", - "bitcoinOutputDispute": "71733", - "bitcoinVerify": "135429", - "bitcoinVerifyWithEmbed": "138039", - "citreaFinaliseDispute": "63284", - "citreaOPVerify": "87733", - "citreaOutputClaim": "99799", - "citreaOutputDispute": "71733", - "citreaVerify": "130685", - "citreaVerifyWithEmbed": "133295", - "hyperlaneOracleHandle": "25916", - "hyperlaneOracleSubmit": "37608", - "hyperlaneOracleSubmitCustomHook": "37604", - "wormholeOracleSubmit": "14020" + "hyperlaneOracleHandle": "50296", + "hyperlaneOracleSubmit": "67472", + "hyperlaneOracleSubmitCustomHook": "67848", + "wormholeOracleSubmit": "42648" } \ No newline at end of file diff --git a/snapshots/outputSettler.json b/snapshots/outputSettler.json index 34ff8588..7ca668c7 100644 --- a/snapshots/outputSettler.json +++ b/snapshots/outputSettler.json @@ -1,10 +1,5 @@ { - "emitNotFilled": "8431", - "outputSettlerCoinFill": "83316", - "outputSettlerCoinFillDutchAuction": "84576", - "outputSettlerCoinFillExclusive": "84709", - "outputSettlerCoinFillExclusiveDutchAuction": "85453", - "outputSettlerCoinFillNative": "89389", + "emitNotFilled": "32683", "outputSettlerCoinFillOrderOutputsNative": "128930", "outputSettlerCoinfillOrderOutputs": "119862" } \ No newline at end of file diff --git a/src/integrations/oracles/axelar/AxelarChainName.sol b/src/integrations/oracles/axelar/AxelarChainName.sol new file mode 100644 index 00000000..ab3f6ff0 --- /dev/null +++ b/src/integrations/oracles/axelar/AxelarChainName.sol @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { LibString } from "solady/utils/LibString.sol"; + +/// @title AxelarChainName +/// @notice Axelar chain name ↔ packed `uint256` chain-map key. +/// @dev The key is the ASCII-lowercased name packed left-aligned and zero-padded: `uint256(bytes32(bytes(name)))`. +/// Names are 1–32 bytes without NUL; no character set is imposed. Axelar compares names ASCII-case-insensitively, +/// so lowercasing gives each chain exactly one key. +library AxelarChainName { + /// @notice The name is empty, longer than 32 bytes, or contains a NUL byte. + error InvalidChainName(); + + /// @notice ASCII-lowercases `chainName` and packs it left-aligned, word-at-a-time. + /// @dev Only 0x41–0x5a change (by setting bit 0x20); bytes ≥ 0x80 are left as is. + /// @param chainName Axelar chain name, in any ASCII case. + /// @return packed Packed lowercase name. + function key( + string memory chainName + ) internal pure returns (uint256 packed) { + uint256 n = bytes(chainName).length; + if (n == 0 || n > 32) revert InvalidChainName(); + bool nul; + assembly ("memory-safe") { + let ones := 0x0101010101010101010101010101010101010101010101010101010101010101 + let highs := shl(7, ones) + // Mask of the bytes past the name. n = 32 shifts by 256, which yields 0 (no tail). + let tail := shr(shl(3, n), not(0)) + let w := and(mload(add(chainName, 0x20)), not(tail)) + // NUL test on a copy `v` whose tail bytes are 0x01, so the zero padding does not count; `w` and the key + // keep a zero tail. The has-zero-byte test is exact for a yes/no answer. + let v := or(w, and(tail, ones)) + nul := iszero(iszero(and(and(sub(v, ones), not(v)), highs))) + // With high bits cleared each byte is ≤ 0x7f, so adding ≤ 0x3f per byte never carries across bytes. + // Bit 7 of (b + 0x3f) is set iff b ≥ 0x41; of (b + 0x25) iff b ≥ 0x5b. + let low := and(w, not(highs)) + let ge41 := and(add(low, mul(0x3f, ones)), highs) + let ge5b := and(add(low, mul(0x25, ones)), highs) + // Uppercase ASCII: ≥ 0x41, < 0x5b, and the original high bit clear; move bit 7 to bit 5. + packed := or(w, shr(2, and(and(ge41, not(ge5b)), not(w)))) + } + if (nul) revert InvalidChainName(); + } + + /// @notice Unpacks a key into its name: the bytes up to the first zero byte. + /// @param packed Packed name. + /// @return Chain name. + function name( + uint256 packed + ) internal pure returns (string memory) { + return LibString.fromSmallString(bytes32(packed)); + } +} diff --git a/src/integrations/oracles/axelar/AxelarOracle.sol b/src/integrations/oracles/axelar/AxelarOracle.sol index 284efc36..0a12748b 100644 --- a/src/integrations/oracles/axelar/AxelarOracle.sol +++ b/src/integrations/oracles/axelar/AxelarOracle.sol @@ -1,8 +1,13 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { MappedOracle } from "../common/MappedOracle.sol"; -import { OracleAddress } from "../common/OracleAddress.sol"; +import { IAttester } from "../../../interfaces/IAttester.sol"; +import { LibAddress } from "../../../libs/LibAddress.sol"; +import { MessageEncodingLib } from "../../../libs/MessageEncodingLib.sol"; +import { BaseInputOracle } from "../../../oracles/BaseInputOracle.sol"; +import { ChainMap } from "../../../oracles/ChainMap.sol"; +import { AxelarChainName } from "./AxelarChainName.sol"; +import { OracleAddress } from "./OracleAddress.sol"; import { SolanaEnvelope } from "./SolanaEnvelope.sol"; interface IAxelarMessageGateway { @@ -29,110 +34,107 @@ interface IAxelarNativeGasService { ) external payable; } -/// Transparent Axelar GMP oracle with owner-set immutable chain maps (ChainMap conventions keyed by lowercase -/// Axelar name); supports Stellar and Solana sender identities. -contract AxelarOracle is MappedOracle { - enum DeliveryMode { Relayed, SelfRelay } +/// @title AxelarOracle +/// @notice Transparent Axelar GMP oracle with owner-set, immutable chain maps. +/// @dev The owner maps an Axelar chain to an OIF chain through `ChainMap.setChainMap(key, chainId)`, where `key` is +/// the ASCII-lowercased Axelar name packed left-aligned and zero-padded: `uint256(bytes32(bytes(name)))`. Names are +/// 1–32 bytes without NUL; no other character set is imposed, so `reverseChainIdMap(chainId)` returns the packed +/// name, which `submit` unpacks into the outbound chain name. Axelar currently caps names at 20 bytes. +/// Inbound sender formats (EVM hex, Stellar StrKey, Solana base58) are inferred from the +/// sender string. No Stellar message limits are enforced here; Stellar and Solana destinations enforce their own, +/// so clients split batches to fit. +contract AxelarOracle is BaseInputOracle, ChainMap { + using LibAddress for address; - struct Route { - uint256 chainId; - OracleAddress.Kind kind; + enum DeliveryMode { + Relayed, + SelfRelay } - /// Axelar ChainNameRaw::MAX_LEN. - uint256 public constant MAX_CHAIN_NAME = 20; IAxelarMessageGateway public immutable gateway; IAxelarNativeGasService public immutable gasService; - mapping(bytes32 nameKey => OracleAddress.Kind) private kinds; + error InvalidConfiguration(); + error NotAllPayloadsValid(); error NotApproved(); error InvalidFee(); - event ChainMapConfigured(string name, uint256 chainId, OracleAddress.Kind kind); - constructor( address owner_, address gateway_, address gasService_ - ) MappedOracle(owner_) { + ) ChainMap(owner_) { if (gateway_.code.length == 0 || gasService_.code.length == 0) revert InvalidConfiguration(); gateway = IAxelarMessageGateway(gateway_); gasService = IAxelarNativeGasService(gasService_); } - /// Set an immutable map from a lowercase Axelar name to an OIF chain. Each name and chain ID is set once. + /// @notice Sets an immutable map from a packed lowercase Axelar name to an OIF chain ID. + /// @dev `protocolChainIdentifier` must be `uint256(bytes32(bytes(name)))` for a 1–32-byte name with no NUL and no + /// ASCII uppercase; anything else (zero, right-aligned, bytes after a NUL, uppercase) reverts + /// `AxelarChainName.InvalidChainName`. function setChainMap( - string calldata name, - uint256 chainId, - OracleAddress.Kind kind - ) external onlyOwner { - bytes calldata b = bytes(name); - if (b.length == 0 || b.length > MAX_CHAIN_NAME) revert InvalidConfiguration(); - for (uint256 i; i < b.length; ++i) { - bytes1 c = b[i]; - if (!((c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c == "-")) revert InvalidConfiguration(); - } - bytes32 key = keccak256(b); - _setRoute(key, chainId); - kinds[key] = kind; - emit ChainMapConfigured(name, chainId, kind); - } - - function route( - string calldata name - ) public view returns (Route memory r) { - (, r) = _route(name); - } - - /// Lowercased canonical name and its map; Axelar names are unique after ASCII lowercasing. - function _route( - string calldata name - ) internal view returns (string memory canonical, Route memory r) { - bytes memory b = bytes(name); - if (b.length == 0 || b.length > MAX_CHAIN_NAME) revert UnknownChain(); - for (uint256 i; i < b.length; ++i) { - if (b[i] >= 0x41 && b[i] <= 0x5a) b[i] = bytes1(uint8(b[i]) + 32); + uint256 protocolChainIdentifier, + uint256 chainId + ) public override onlyOwner { + if (AxelarChainName.key(AxelarChainName.name(protocolChainIdentifier)) != protocolChainIdentifier) { + revert AxelarChainName.InvalidChainName(); } - bytes32 key = keccak256(b); - r = Route(_chainId(key), kinds[key]); - canonical = string(b); + super.setChainMap(protocolChainIdentifier, chainId); } + /// @notice Sends attested payloads to the Axelar chain mapped to `destinationChainId`. + /// @dev `recipientOracle` is passed to Axelar unchecked. A wrong recipient or config loses only that delivery: + /// export does not consume anything, so anyone can submit again. + /// @param destinationChainId OIF chain ID of the destination; must be mapped. + /// @param recipientOracle Destination oracle as an Axelar address string (`0x…`, `C…` StrKey, or base58). + /// @param source Attester whose payloads are sent. + /// @param payloads Payloads `source` has attested. + /// @param destinationConfig Nonzero selects the Solana Borsh envelope with this config; zero sends the raw message. + /// @param deliveryMode `Relayed` pays `msg.value` to the gas service; `SelfRelay` requires no value. function submit( - string calldata destinationChain, - bytes32 recipientOracle, + uint256 destinationChainId, + string calldata recipientOracle, address source, bytes[] calldata payloads, bytes32 destinationConfig, DeliveryMode deliveryMode ) external payable { - (string memory chain, Route memory r) = _route(destinationChain); - string memory recipient = OracleAddress.encode(recipientOracle, r.kind); - bytes memory message = _export(source, payloads); - if (r.kind == OracleAddress.Kind.Solana) { - message = SolanaEnvelope.encode(message, destinationConfig); - } else if (destinationConfig != 0) revert InvalidConfiguration(); + uint256 key = reverseChainIdMap[destinationChainId]; + if (key == 0) revert ZeroValue(); + string memory chain = AxelarChainName.name(key); + if (!IAttester(source).hasAttested(payloads)) revert NotAllPayloadsValid(); + bytes memory message = MessageEncodingLib.encodeMessage(source.toIdentifier(), payloads); + if (destinationConfig != 0) message = SolanaEnvelope.encode(message, destinationConfig); if (deliveryMode == DeliveryMode.Relayed) { if (msg.value == 0) revert InvalidFee(); gasService.payNativeGasForContractCall{ value: msg.value }( - address(this), chain, recipient, message, msg.sender + address(this), chain, recipientOracle, message, msg.sender ); - } else if (msg.value != 0) revert InvalidFee(); - gateway.callContract(chain, recipient, message); + } else if (msg.value != 0) { + revert InvalidFee(); + } + gateway.callContract(chain, recipientOracle, message); } - /// Anyone may execute, but only the gateway can approve the exact destination-bound message. + /// @notice Records the payload hashes of a gateway-approved message. + /// @dev Anyone may execute, but only the gateway can approve the exact destination-bound message. The original + /// `sourceChain` and `sourceAddress` strings are validated, since Axelar binds the approved spelling. function execute( bytes32 commandId, string calldata sourceChain, string calldata sourceAddress, bytes calldata payload ) external { - (, Route memory r) = _route(sourceChain); - bytes32 sender = OracleAddress.decode(sourceAddress, r.kind); + uint256 chainId = _getMappedChainId(AxelarChainName.key(sourceChain)); + bytes32 sender = OracleAddress.decode(sourceAddress); if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, keccak256(payload))) { revert NotApproved(); } - _record(r.chainId, sender, payload); + (bytes32 application, bytes32[] memory hashes) = MessageEncodingLib.getHashesOfEncodedPayloads(payload); + for (uint256 i; i < hashes.length; ++i) { + _attestations[chainId][sender][application][hashes[i]] = true; + emit OutputProven(chainId, sender, application, hashes[i]); + } } } diff --git a/src/integrations/oracles/axelar/OracleAddress.sol b/src/integrations/oracles/axelar/OracleAddress.sol new file mode 100644 index 00000000..ffa385c5 --- /dev/null +++ b/src/integrations/oracles/axelar/OracleAddress.sol @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { Base58 } from "@openzeppelin/contracts/utils/Base58.sol"; + +/// @title OracleAddress +/// @notice Axelar address string → OIF identifier. +/// @dev The format is inferred from the string's shape. EVM: `0x`-prefixed 20-byte hex, left-padded into the +/// identifier. Stellar: 56-character contract StrKey (`C...`, version byte 0x10) whose CRC16-XModem checksum is +/// stored little-endian. Solana: 32–44-character base58 public key, decoded with OpenZeppelin Base58. The shapes +/// cannot overlap: `0` is not in the base58 alphabet, and 56 is outside Solana's 32–44 length range. +library OracleAddress { + /// @notice The string is not a valid address of the format its shape selects. + error InvalidOracleAddress(); + + /// @dev RFC 4648 base32 alphabet used by Stellar StrKeys. + bytes internal constant BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + /// @notice Decodes an Axelar address string into an OIF identifier. + /// @dev Rejects malformed input instead of normalising it. Dispatch: a `0x` prefix selects EVM, which must be + /// 42 characters of hex in either case (the EIP-55 checksum is not checked); otherwise a length of 56 selects a + /// Stellar contract StrKey with a valid checksum; otherwise the string must be a Solana key that decodes to + /// exactly 32 bytes in its canonical spelling. + /// @param value Axelar address string. + /// @return id Raw 32-byte identifier. EVM addresses are left-padded with zeros. + function decode( + string calldata value + ) internal pure returns (bytes32 id) { + bytes calldata input = bytes(value); + if (input.length >= 2 && input[0] == "0" && input[1] == "x") { + if (input.length != 42) revert InvalidOracleAddress(); + uint256 n; + for (uint256 i = 2; i < 42; ++i) { + n = (n << 4) | _hex(uint8(input[i])); + } + return bytes32(n); + } + if (input.length == 56) { + bytes memory raw = new bytes(35); + uint256 acc; + uint256 bits; + uint256 j; + for (uint256 i; i < 56; ++i) { + uint8 c = uint8(input[i]); + uint256 v; + if (c >= 65 && c <= 90) v = c - 65; + else if (c >= 50 && c <= 55) v = c - 24; + else revert InvalidOracleAddress(); + acc = (acc << 5) | v; + bits += 5; + if (bits >= 8) { + bits -= 8; + raw[j++] = bytes1(uint8(acc >> bits)); + } + } + if (raw[0] != 0x10 || _crc(raw) != (uint16(uint8(raw[33])) | uint16(uint8(raw[34])) << 8)) { + revert InvalidOracleAddress(); + } + assembly ("memory-safe") { id := mload(add(raw, 33)) } + return id; + } + if (input.length < 32 || input.length > 44) revert InvalidOracleAddress(); + // Invalid characters revert with OpenZeppelin's `InvalidBase58Char`. + bytes memory decoded = Base58.decode(value); + if (decoded.length != 32) revert InvalidOracleAddress(); + id = bytes32(decoded); + // Base58 is a bijection, so this never fails today; it pins one spelling per ID + // independently of the library's decoder. + if (keccak256(bytes(Base58.encode(decoded))) != keccak256(input)) revert InvalidOracleAddress(); + } + + /// @dev Value of one ASCII hex digit, accepting either case. + /// @param c ASCII character. + /// @return Digit value in [0, 15]. + function _hex( + uint8 c + ) private pure returns (uint256) { + if (c >= 48 && c <= 57) return c - 48; + if (c >= 65 && c <= 70) return c - 55; + if (c >= 97 && c <= 102) return c - 87; + revert InvalidOracleAddress(); + } + + /// @dev CRC16-XModem (polynomial 0x1021, initial value 0) over the first 33 bytes, which are the + /// StrKey version byte and payload. + /// @param data StrKey bytes, at least 33 long. + /// @return crc Checksum. + function _crc( + bytes memory data + ) private pure returns (uint16 crc) { + for (uint256 i; i < 33; ++i) { + crc ^= uint16(uint8(data[i])) << 8; + for (uint256 k; k < 8; ++k) { + crc = crc & 0x8000 != 0 ? (crc << 1) ^ 0x1021 : crc << 1; + } + } + } +} diff --git a/src/integrations/oracles/common/BoundedOracle.sol b/src/integrations/oracles/common/BoundedOracle.sol deleted file mode 100644 index 1e34b3c0..00000000 --- a/src/integrations/oracles/common/BoundedOracle.sol +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; - -import { IAttester } from "../../../interfaces/IAttester.sol"; -import { MessageEncodingLib } from "../../../libs/MessageEncodingLib.sol"; -import { BaseInputOracle } from "../../../oracles/BaseInputOracle.sol"; - -/// Shared Stellar-compatible admission limits; transport authentication belongs to each adapter. -abstract contract BoundedOracle is BaseInputOracle { - error InvalidConfiguration(); - error UnknownChain(); - error MessageLimit(); - error NotAttested(); - uint256 public constant MAX_PAYLOADS = 4; - uint256 public constant MAX_PAYLOAD = 684; - uint256 public constant MAX_MESSAGE = 2778; - - function _encode( - address source, - bytes[] calldata payloads - ) internal pure returns (bytes memory) { - if (source == address(0) || payloads.length == 0 || payloads.length > MAX_PAYLOADS) revert MessageLimit(); - for (uint256 i; i < payloads.length; ++i) { - if (payloads[i].length > MAX_PAYLOAD) revert MessageLimit(); - } - return MessageEncodingLib.encodeMessage(bytes32(uint256(uint160(source))), payloads); - } - - function _export( - address source, - bytes[] calldata payloads - ) internal view returns (bytes memory message) { - message = _encode(source, payloads); - if (!IAttester(source).hasAttested(payloads)) revert NotAttested(); - } - - function _record( - uint256 chain, - bytes32 sender, - bytes calldata message - ) internal { - if (message.length < 34 || message.length > MAX_MESSAGE) revert MessageLimit(); - uint256 count = uint16(bytes2(message[32:34])); - if (count == 0 || count > MAX_PAYLOADS) revert MessageLimit(); - uint256 cursor = 34; - for (uint256 i; i < count; ++i) { - uint256 size = uint16(bytes2(message[cursor:cursor + 2])); - if (size > MAX_PAYLOAD) revert MessageLimit(); - cursor += 2 + size; - } - (bytes32 application, bytes32[] memory hashes) = MessageEncodingLib.getHashesOfEncodedPayloads(message); - for (uint256 i; i < hashes.length; ++i) { - if (!_attestations[chain][sender][application][hashes[i]]) { - _attestations[chain][sender][application][hashes[i]] = true; - emit OutputProven(chain, sender, application, hashes[i]); - } - } - } -} diff --git a/src/integrations/oracles/common/MappedOracle.sol b/src/integrations/oracles/common/MappedOracle.sol deleted file mode 100644 index ee7722a8..00000000 --- a/src/integrations/oracles/common/MappedOracle.sol +++ /dev/null @@ -1,37 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; - -import { Ownable } from "openzeppelin/access/Ownable.sol"; - -import { BoundedOracle } from "./BoundedOracle.sol"; - -/// Bounded transport oracle with owner-added, set-once, bijective route-key -> OIF chain maps. -abstract contract MappedOracle is BoundedOracle, Ownable { - error AlreadySet(); - error ZeroValue(); - - mapping(bytes32 routeKey => uint256 chainId) internal _chainIds; - mapping(uint256 chainId => bytes32 routeKey) public reverseChainIdMap; - - constructor( - address owner_ - ) Ownable(owner_) { } - - /// Map a nonzero route key to a nonzero OIF chain. Each key and chain ID is set once. - function _setRoute( - bytes32 key, - uint256 chainId - ) internal { - if (chainId == 0) revert ZeroValue(); - if (_chainIds[key] != 0 || reverseChainIdMap[chainId] != 0) revert AlreadySet(); - _chainIds[key] = chainId; - reverseChainIdMap[chainId] = key; - } - - function _chainId( - bytes32 key - ) internal view returns (uint256 chainId) { - chainId = _chainIds[key]; - if (chainId == 0) revert UnknownChain(); - } -} diff --git a/src/integrations/oracles/common/OracleAddress.sol b/src/integrations/oracles/common/OracleAddress.sol deleted file mode 100644 index 2b987fb7..00000000 --- a/src/integrations/oracles/common/OracleAddress.sol +++ /dev/null @@ -1,121 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; - -import { Base58 } from "@openzeppelin/contracts/utils/Base58.sol"; - -/// Axelar native strings <-> OIF raw identifiers. Solana uses OpenZeppelin Base58; Stellar -/// CRC16-XModem is stored little-endian. -library OracleAddress { - enum Kind { - Evm, - Stellar, - Solana - } - error InvalidOracleAddress(); - bytes internal constant BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - bytes internal constant HEX = "0123456789abcdef"; - - function encode( - bytes32 id, - Kind kind - ) internal pure returns (string memory) { - if (kind == Kind.Solana) return Base58.encode(abi.encodePacked(id)); - if (kind == Kind.Evm) { - if (uint256(id) >> 160 != 0) revert InvalidOracleAddress(); - bytes memory evm = new bytes(42); - evm[0] = "0"; - evm[1] = "x"; - for (uint256 i; i < 20; ++i) { - uint8 b = uint8(id[i + 12]); - evm[2 + i * 2] = HEX[b >> 4]; - evm[3 + i * 2] = HEX[b & 15]; - } - return string(evm); - } - bytes memory raw = abi.encodePacked(bytes1(0x10), id, bytes2(0)); - uint16 crc = _crc(raw); - raw[33] = bytes1(uint8(crc)); - raw[34] = bytes1(uint8(crc >> 8)); - bytes memory out = new bytes(56); - uint256 acc; - uint256 bits; - uint256 j; - for (uint256 i; i < 35; ++i) { - acc = (acc << 8) | uint8(raw[i]); - bits += 8; - while (bits >= 5) { - bits -= 5; - out[j++] = BASE32[(acc >> bits) & 31]; - } - } - return string(out); - } - - function decode( - string calldata value, - Kind kind - ) internal pure returns (bytes32 id) { - bytes calldata input = bytes(value); - if (kind == Kind.Solana) { - if (input.length < 32 || input.length > 44) revert InvalidOracleAddress(); - // Invalid characters revert with OpenZeppelin's `InvalidBase58Char`. - bytes memory decoded = Base58.decode(value); - if (decoded.length != 32) revert InvalidOracleAddress(); - id = bytes32(decoded); - // Base58 is a bijection, so this never fails today; it pins one spelling per ID - // independently of the library's decoder. - if (keccak256(bytes(Base58.encode(decoded))) != keccak256(input)) revert InvalidOracleAddress(); - return id; - } - if (kind == Kind.Evm) { - if (input.length != 42 || input[0] != "0" || input[1] != "x") revert InvalidOracleAddress(); - uint256 n; - for (uint256 i = 2; i < 42; ++i) { - n = (n << 4) | _hex(uint8(input[i])); - } - return bytes32(n); - } - if (input.length != 56) revert InvalidOracleAddress(); - bytes memory raw = new bytes(35); - uint256 acc; - uint256 bits; - uint256 j; - for (uint256 i; i < 56; ++i) { - uint8 c = uint8(input[i]); - uint256 v; - if (c >= 65 && c <= 90) v = c - 65; - else if (c >= 50 && c <= 55) v = c - 24; - else revert InvalidOracleAddress(); - acc = (acc << 5) | v; - bits += 5; - if (bits >= 8) { - bits -= 8; - raw[j++] = bytes1(uint8(acc >> bits)); - } - } - if (raw[0] != 0x10 || _crc(raw) != (uint16(uint8(raw[33])) | uint16(uint8(raw[34])) << 8)) { - revert InvalidOracleAddress(); - } - assembly ("memory-safe") { id := mload(add(raw, 33)) } - } - - function _hex( - uint8 c - ) private pure returns (uint256) { - if (c >= 48 && c <= 57) return c - 48; - if (c >= 65 && c <= 70) return c - 55; - if (c >= 97 && c <= 102) return c - 87; - revert InvalidOracleAddress(); - } - - function _crc( - bytes memory data - ) private pure returns (uint16 crc) { - for (uint256 i; i < 33; ++i) { - crc ^= uint16(uint8(data[i])) << 8; - for (uint256 k; k < 8; ++k) { - crc = crc & 0x8000 != 0 ? (crc << 1) ^ 0x1021 : crc << 1; - } - } - } -} diff --git a/src/oracles/ChainMap.sol b/src/oracles/ChainMap.sol index 1ac1f1cf..fa6785cf 100644 --- a/src/oracles/ChainMap.sol +++ b/src/oracles/ChainMap.sol @@ -45,7 +45,7 @@ abstract contract ChainMap is Ownable { function setChainMap( uint256 protocolChainIdentifier, uint256 chainId - ) external onlyOwner { + ) public virtual onlyOwner { if (protocolChainIdentifier == 0) revert ZeroValue(); if (chainId == 0) revert ZeroValue(); diff --git a/test/oracle/axelar/AddressStrings.sol b/test/oracle/axelar/AddressStrings.sol new file mode 100644 index 00000000..3043283f --- /dev/null +++ b/test/oracle/axelar/AddressStrings.sol @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { Base58 } from "@openzeppelin/contracts/utils/Base58.sol"; + +/// Test-only encoders from OIF identifiers to Axelar address strings. +library AddressStrings { + bytes internal constant HEX = "0123456789abcdef"; + bytes internal constant BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + + /// Lowercase `0x` + 40 hex digits; the upper 12 bytes of `id` must be zero. + function evm( + bytes32 id + ) internal pure returns (string memory) { + require(uint256(id) >> 160 == 0, "not an EVM address"); + bytes memory out = new bytes(42); + out[0] = "0"; + out[1] = "x"; + for (uint256 i; i < 20; ++i) { + uint8 b = uint8(id[i + 12]); + out[2 + i * 2] = HEX[b >> 4]; + out[3 + i * 2] = HEX[b & 15]; + } + return string(out); + } + + /// Stellar contract StrKey: version byte 0x10, id, little-endian CRC16-XModem, base32. + function stellar( + bytes32 id + ) internal pure returns (string memory) { + bytes memory raw = abi.encodePacked(bytes1(0x10), id, bytes2(0)); + uint16 crc = _crc(raw); + raw[33] = bytes1(uint8(crc)); + raw[34] = bytes1(uint8(crc >> 8)); + bytes memory out = new bytes(56); + uint256 acc; + uint256 bits; + uint256 j; + for (uint256 i; i < 35; ++i) { + acc = (acc << 8) | uint8(raw[i]); + bits += 8; + while (bits >= 5) { + bits -= 5; + out[j++] = BASE32[(acc >> bits) & 31]; + } + } + return string(out); + } + + /// Solana base58 public key. + function solana( + bytes32 id + ) internal pure returns (string memory) { + return Base58.encode(abi.encodePacked(id)); + } + + function _crc( + bytes memory data + ) private pure returns (uint16 crc) { + for (uint256 i; i < 33; ++i) { + crc ^= uint16(uint8(data[i])) << 8; + for (uint256 k; k < 8; ++k) { + crc = crc & 0x8000 != 0 ? (crc << 1) ^ 0x1021 : crc << 1; + } + } + } +} diff --git a/test/oracle/axelar/AxelarChainName.t.sol b/test/oracle/axelar/AxelarChainName.t.sol new file mode 100644 index 00000000..f69b8f90 --- /dev/null +++ b/test/oracle/axelar/AxelarChainName.t.sol @@ -0,0 +1,208 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; + +import { AxelarChainName } from "../../../src/integrations/oracles/axelar/AxelarChainName.sol"; +import { Test } from "forge-std/Test.sol"; + +contract ChainNameHarness { + function key( + string memory chainName + ) external pure returns (uint256) { + return AxelarChainName.key(chainName); + } + + function name( + uint256 packed + ) external pure returns (string memory) { + return AxelarChainName.name(packed); + } +} + +/// `AxelarChainName.key` (word-at-a-time) against a byte-by-byte reference: ASCII A–Z lowercased, every other +/// nonzero byte kept, 1–32 bytes, NUL rejected. +contract AxelarChainNameTest is Test { + ChainNameHarness h; + + function setUp() public { + h = new ChainNameHarness(); + } + + function reference_( + bytes memory b + ) internal pure returns (bool ok, uint256 key) { + if (b.length == 0 || b.length > 32) return (false, 0); + for (uint256 i; i < b.length; ++i) { + uint8 c = uint8(b[i]); + if (c == 0) return (false, 0); + if (c >= 0x41 && c <= 0x5a) c += 32; + key |= uint256(c) << (248 - 8 * i); + } + return (true, key); + } + + function check( + bytes memory b + ) internal view { + (bool ok, uint256 expected) = reference_(b); + (bool success, bytes memory ret) = address(h).staticcall(abi.encodeCall(ChainNameHarness.key, (string(b)))); + assertEq(success, ok, "revert mismatch"); + if (ok) assertEq(abi.decode(ret, (uint256)), expected, "key mismatch"); + else assertEq(ret, abi.encodeWithSelector(AxelarChainName.InvalidChainName.selector), "wrong error"); + } + + function filled( + uint256 n, + bytes1 c + ) internal pure returns (bytes memory b) { + b = new bytes(n); + for (uint256 i; i < n; ++i) { + b[i] = c; + } + } + + /// Every byte value at every position of names of length `from`–`to`, beside `filler` neighbours. + function sweep( + bytes1 filler, + uint256 from, + uint256 to + ) internal view { + for (uint256 n = from; n <= to; ++n) { + bytes memory b = filled(n, filler); + for (uint256 p; p < n; ++p) { + for (uint256 c; c < 256; ++c) { + b[p] = bytes1(uint8(c)); + uint256 fmp; + assembly ("memory-safe") { fmp := mload(0x40) } + check(b); + // Reclaim the call's scratch allocations; otherwise memory-expansion cost grows quadratically. + assembly ("memory-safe") { mstore(0x40, fmp) } + } + b[p] = filler; + } + } + } + + // Together: all 256 byte values at every position of every length 1–32, beside neighbours that stay + // unchanged (`a`) and that are lowercased (`Z`). Split only to stay under the per-test gas limit. + function testEveryByteLowerNeighbours1To22() public view { + sweep("a", 1, 22); + } + + function testEveryByteLowerNeighbours23To28() public view { + sweep("a", 23, 28); + } + + function testEveryByteLowerNeighbours29To32() public view { + sweep("a", 29, 32); + } + + function testEveryByteUpperNeighbours1To22() public view { + sweep("Z", 1, 22); + } + + function testEveryByteUpperNeighbours23To28() public view { + sweep("Z", 23, 28); + } + + function testEveryByteUpperNeighbours29To32() public view { + sweep("Z", 29, 32); + } + + /// A single byte of every value, as a whole name: exact lowercasing boundaries. + function testSingleByteMapping() public view { + for (uint256 c = 1; c < 256; ++c) { + uint256 expected = (c >= 0x41 && c <= 0x5a ? c + 32 : c) << 248; + assertEq(h.key(string(abi.encodePacked(uint8(c)))), expected); + } + assertEq(h.key("@"), uint256(0x40) << 248); + assertEq(h.key("A"), uint256(0x61) << 248); + assertEq(h.key("Z"), uint256(0x7a) << 248); + assertEq(h.key("["), uint256(0x5b) << 248); + assertEq(h.key(string(abi.encodePacked(uint8(0x80)))), uint256(0x80) << 248); + assertEq(h.key(string(abi.encodePacked(uint8(0xc1)))), uint256(0xc1) << 248); // 0x41 | 0x80: not uppercase + assertEq(h.key(string(abi.encodePacked(uint8(0xda)))), uint256(0xda) << 248); // 0x5a | 0x80: not uppercase + } + + function testWholeAlphabet() public view { + assertEq(h.key("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), uint256(bytes32(bytes("abcdefghijklmnopqrstuvwxyz")))); + assertEq(h.key("abcdefghijklmnopqrstuvwxyz"), uint256(bytes32(bytes("abcdefghijklmnopqrstuvwxyz")))); + assertEq(h.key("0123456789-_.:/ !~"), uint256(bytes32(bytes("0123456789-_.:/ !~")))); + assertEq(h.key("Ethereum"), uint256(bytes32(bytes("ethereum")))); + assertEq(h.key("STELLAR-2026-Q1-2"), uint256(bytes32(bytes("stellar-2026-q1-2")))); + } + + function testLengthBounds() public view { + check(""); + check(filled(32, "A")); + check(filled(33, "a")); + check(filled(64, "a")); + assertEq(h.key(string(filled(32, "A"))), uint256(bytes32(filled(32, "a")))); + } + + function testNulAnywhereReverts() public view { + for (uint256 n = 1; n <= 32; ++n) { + for (uint256 p; p < n; ++p) { + bytes memory b = filled(n, "a"); + b[p] = 0; + vm.assertFalse(_ok(b)); + } + } + } + + function _ok( + bytes memory b + ) internal view returns (bool success) { + (success,) = address(h).staticcall(abi.encodeCall(ChainNameHarness.key, (string(b)))); + } + + /// Random bytes at random lengths 0–40. + function testFuzzRandomBytes( + bytes32 lo, + bytes32 hi, + uint8 len + ) public view { + bytes memory raw = abi.encodePacked(lo, hi); + bytes memory b = new bytes(bound(len, 0, 40)); + for (uint256 i; i < b.length; ++i) { + b[i] = raw[i]; + } + check(b); + } + + /// Random names over printable ASCII (no NUL), the realistic input space, lengths 1–32. + function testFuzzPrintable( + bytes32 seed, + uint8 len + ) public view { + bytes memory b = new bytes(bound(len, 1, 32)); + for (uint256 i; i < b.length; ++i) { + b[i] = bytes1(uint8(0x20 + uint8(seed[i]) % 95)); + } + check(b); + assertTrue(_ok(b)); + } + + /// `name` inverts `key` up to lowercasing, and `key(name(k)) == k` (the setter's canonical check). + function testFuzzNameRoundTrip( + bytes32 seed, + uint8 len + ) public view { + bytes memory b = new bytes(bound(len, 1, 32)); + for (uint256 i; i < b.length; ++i) { + b[i] = bytes1(uint8(1 + uint8(seed[i]) % 255)); + } + uint256 k = h.key(string(b)); + string memory n = h.name(k); + assertEq(bytes(n).length, b.length); + assertEq(uint256(bytes32(bytes(n))), k); + assertEq(h.key(n), k); + } + + function testNameStopsAtFirstZeroByte() public view { + assertEq(h.name(0), ""); + assertEq(h.name(uint256(bytes32("base"))), "base"); + assertEq(h.name(uint256(bytes32("evm")) | 0xff), "evm"); + assertEq(h.name(uint256(bytes32("evm")) >> 8), ""); + assertEq(bytes(h.name(type(uint256).max)).length, 32); + } +} diff --git a/test/oracle/axelar/AxelarOracle.t.sol b/test/oracle/axelar/AxelarOracle.t.sol new file mode 100644 index 00000000..171fa769 --- /dev/null +++ b/test/oracle/axelar/AxelarOracle.t.sol @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.26; +import { AxelarChainName } from "../../../src/integrations/oracles/axelar/AxelarChainName.sol"; +import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; +import { OracleAddress } from "../../../src/integrations/oracles/axelar/OracleAddress.sol"; +import { SolanaEnvelope } from "../../../src/integrations/oracles/axelar/SolanaEnvelope.sol"; +import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { ChainMap } from "../../../src/oracles/ChainMap.sol"; +import { AddressStrings } from "./AddressStrings.sol"; +import { BoundAttester } from "./BoundAttester.sol"; +import { GatewayFixture } from "./GatewayFixture.sol"; +import { Test } from "forge-std/Test.sol"; +import { Ownable } from "openzeppelin/access/Ownable.sol"; + +contract AxelarOracleTest is Test { + GatewayFixture gateway; + AxelarOracle axelar; + BoundAttester source; + bytes32 constant SENDER = keccak256("stellar oracle"); + bytes32 constant APP = keccak256("stellar settler"); + uint256 constant CHAIN = 0x53544c; + + function setUp() public { + gateway = new GatewayFixture(); + source = new BoundAttester(); + axelar = new AxelarOracle(address(this), address(gateway), address(gateway)); + axelar.setChainMap(pack("stellar"), CHAIN); + } + + receive() external payable { } + + function pack( + string memory s + ) internal pure returns (uint256) { + return uint256(bytes32(bytes(s))); + } + + function payloads() internal pure returns (bytes[] memory p) { + p = new bytes[](2); + p[0] = hex"d1252dff012345"; + p[1] = hex"830c1e1c987654"; + } + + function encode( + bytes32 application, + bytes[] calldata p + ) external pure returns (bytes memory) { + return MessageEncodingLib.encodeMessage(application, p); + } + + function approvalKey( + bytes32 command, + string memory chain, + string memory sender, + bytes memory message + ) internal view returns (bytes32) { + return keccak256(abi.encode(command, chain, sender, address(axelar), keccak256(message))); + } + + // --- Setter --- // + + function testSetChainMapRejectsNonOwner() public { + vm.prank(address(0xBEEF)); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); + axelar.setChainMap(pack("evm"), 1); + } + + function testSetChainMapRejectsNonCanonicalKeys() public { + uint256[6] memory bad = [ + uint256(0), + pack("Evm"), + pack("evM"), + pack("evm") >> 8, + pack("evm") | 0xff, + pack("ev") | (uint256(0x6d) << 224) + ]; + for (uint256 i; i < bad.length; ++i) { + vm.expectRevert(AxelarChainName.InvalidChainName.selector); + axelar.setChainMap(bad[i], 2); + } + } + + function testSetChainMapAcceptsAnyCharsetAndFullWord() public { + axelar.setChainMap(pack("a"), 2); + axelar.setChainMap(pack("e_vm.2"), 3); + axelar.setChainMap(pack("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 4); + axelar.setChainMap(uint256(bytes32(hex"c3a9")), 5); // UTF-8 "é": bytes >= 0x80 are kept + assertEq(axelar.chainIdMap(pack("a")), 2); + assertEq(axelar.chainIdMap(pack("e_vm.2")), 3); + assertEq(axelar.chainIdMap(pack("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")), 4); + assertEq(axelar.reverseChainIdMap(4), type(uint256).max / 0xff * 0x61); + } + + function testSubmitForwardsFullWordName() public { + string memory name = "abcdefghijklmnopqrstuvwxyz-01234"; + axelar.setChainMap(pack(name), 32); + source.setOracle(address(axelar)); + axelar.submit(32, "r", address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.SelfRelay); + assertEq(gateway.lastChain(), name); + } + + function testSetChainMapSetOnce() public { + vm.expectRevert(ChainMap.ZeroValue.selector); + axelar.setChainMap(pack("evm"), 0); + vm.expectRevert(ChainMap.AlreadySet.selector); + axelar.setChainMap(pack("stellar"), 2); + vm.expectRevert(ChainMap.AlreadySet.selector); + axelar.setChainMap(pack("evm"), CHAIN); + + vm.expectEmit(address(axelar)); + emit ChainMap.ChainMapConfigured(pack("evm"), 1); + axelar.setChainMap(pack("evm"), 1); + assertEq(axelar.reverseChainIdMap(1), pack("evm")); + assertEq(axelar.chainIdMap(pack("evm")), 1); + + axelar.renounceOwnership(); + vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(this))); + axelar.setChainMap(pack("late"), 5); + } + + // --- Submit --- // + + function testSubmitRelayed() public { + source.setOracle(address(axelar)); + string memory recipient = AddressStrings.stellar(SENDER); + axelar.submit{ value: 10 }( + CHAIN, recipient, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); + assertEq(gateway.lastChain(), "stellar"); + assertEq(gateway.lastGasChain(), "stellar"); + assertEq(gateway.lastDestination(), recipient); + assertEq(gateway.lastMessage(), this.encode(bytes32(uint256(uint160(address(source)))), payloads())); + assertEq(gateway.lastSender(), address(axelar)); + assertEq(gateway.lastRefund(), address(this)); + assertEq(gateway.paid(), 10); + } + + function testSubmitRejects() public { + string memory recipient = AddressStrings.stellar(SENDER); + vm.expectRevert(AxelarOracle.NotAllPayloadsValid.selector); + axelar.submit{ value: 10 }( + CHAIN, recipient, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); + source.setOracle(address(axelar)); + vm.expectRevert(ChainMap.ZeroValue.selector); + axelar.submit{ value: 10 }( + 999, recipient, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed + ); + vm.expectRevert(AxelarOracle.InvalidFee.selector); + axelar.submit(CHAIN, recipient, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed); + vm.expectRevert(AxelarOracle.InvalidFee.selector); + axelar.submit{ value: 1 }( + CHAIN, recipient, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.SelfRelay + ); + } + + function testSolanaEnvelope() public { + axelar.setChainMap(pack("solana"), 9); + source.setOracle(address(axelar)); + string memory recipient = AddressStrings.solana(SENDER); + bytes[] memory p = new bytes[](1); + p[0] = new bytes(320); + bytes32 config = keccak256("config"); + bytes memory raw = this.encode(bytes32(uint256(uint160(address(source)))), p); + + axelar.submit(9, recipient, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + assertEq(gateway.lastChain(), "solana"); + assertEq(gateway.paid(), 0); + assertEq(gateway.lastMessage(), bytes.concat(hex"0064010000", raw, hex"01000000", config, hex"00")); + + axelar.submit(9, recipient, address(source), p, bytes32(0), AxelarOracle.DeliveryMode.SelfRelay); + assertEq(gateway.lastMessage(), raw); + + p[0] = new bytes(321); + vm.expectRevert(SolanaEnvelope.InvalidSolanaEnvelope.selector); + axelar.submit(9, recipient, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); + } + + // --- Execute --- // + + function testExecuteInfersSenderFormat() public { + bytes memory m = this.encode(APP, payloads()); + bytes32 h = keccak256(payloads()[0]); + address evmAddr = makeAddr("evm oracle"); + bytes32 solanaId = keccak256("solana oracle"); + string[3] memory senders = + [AddressStrings.stellar(SENDER), vm.toString(evmAddr), AddressStrings.solana(solanaId)]; + bytes32[3] memory ids = [SENDER, bytes32(uint256(uint160(evmAddr))), solanaId]; + for (uint256 i; i < 3; ++i) { + bytes32 command = bytes32(i); + gateway.approve(command, "stellar", senders[i], address(axelar), m); + axelar.execute(command, "stellar", senders[i], m); + assertTrue(axelar.isProven(CHAIN, ids[i], APP, h)); + } + assertFalse(axelar.isProven(CHAIN, bytes32(uint256(1)), APP, h)); + + vm.expectRevert(AxelarOracle.NotApproved.selector); + axelar.execute(bytes32(0), "stellar", senders[0], m); + } + + function testExecuteKeepsApprovedCase() public { + bytes memory m = this.encode(APP, payloads()); + string memory sender = AddressStrings.stellar(SENDER); + gateway.approve(bytes32(uint256(7)), "Stellar", sender, address(axelar), m); + axelar.execute(bytes32(uint256(7)), "Stellar", sender, m); + assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); + } + + function testExecuteFailuresLeaveApproval() public { + bytes memory m = this.encode(APP, payloads()); + string memory sender = AddressStrings.stellar(SENDER); + + gateway.approve(bytes32(0), "base", sender, address(axelar), m); + vm.expectRevert(ChainMap.ZeroValue.selector); + axelar.execute(bytes32(0), "base", sender, m); + assertTrue(gateway.approvals(approvalKey(bytes32(0), "base", sender, m))); + + gateway.approve(bytes32(0), "stellar\x00", sender, address(axelar), m); + vm.expectRevert(AxelarChainName.InvalidChainName.selector); + axelar.execute(bytes32(0), "stellar\x00", sender, m); + assertTrue(gateway.approvals(approvalKey(bytes32(0), "stellar\x00", sender, m))); + + string memory long = "abcdefghijklmnopqrstuvwxyz-012345"; + gateway.approve(bytes32(0), long, sender, address(axelar), m); + vm.expectRevert(AxelarChainName.InvalidChainName.selector); + axelar.execute(bytes32(0), long, sender, m); + assertTrue(gateway.approvals(approvalKey(bytes32(0), long, sender, m))); + + gateway.approve(bytes32(0), "stellar", "hello", address(axelar), m); + vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); + axelar.execute(bytes32(0), "stellar", "hello", m); + assertTrue(gateway.approvals(approvalKey(bytes32(0), "stellar", "hello", m))); + + bytes memory trailing = bytes.concat(m, hex"00"); + gateway.approve(bytes32(0), "stellar", sender, address(axelar), trailing); + vm.expectRevert(); + axelar.execute(bytes32(0), "stellar", sender, trailing); + assertTrue(gateway.approvals(approvalKey(bytes32(0), "stellar", sender, trailing))); + } +} diff --git a/test/oracle/transport/BoundAttester.sol b/test/oracle/axelar/BoundAttester.sol similarity index 100% rename from test/oracle/transport/BoundAttester.sol rename to test/oracle/axelar/BoundAttester.sol diff --git a/test/oracle/transport/GatewayFixture.sol b/test/oracle/axelar/GatewayFixture.sol similarity index 100% rename from test/oracle/transport/GatewayFixture.sol rename to test/oracle/axelar/GatewayFixture.sol diff --git a/test/oracle/transport/OracleAddress.t.sol b/test/oracle/axelar/OracleAddress.t.sol similarity index 63% rename from test/oracle/transport/OracleAddress.t.sol rename to test/oracle/axelar/OracleAddress.t.sol index ea6ef95f..7ddf0a4d 100644 --- a/test/oracle/transport/OracleAddress.t.sol +++ b/test/oracle/axelar/OracleAddress.t.sol @@ -1,7 +1,8 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; +import { OracleAddress } from "../../../src/integrations/oracles/axelar/OracleAddress.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; +import { AddressStrings } from "./AddressStrings.sol"; import { Test } from "forge-std/Test.sol"; contract OracleAddressTest is Test { @@ -15,10 +16,9 @@ contract OracleAddressTest is Test { } function decodeAddress( - string calldata value, - OracleAddress.Kind kind + string calldata value ) external pure returns (bytes32) { - return OracleAddress.decode(value, kind); + return OracleAddress.decode(value); } function decode( @@ -29,16 +29,22 @@ contract OracleAddressTest is Test { function testFuzzStellarAddressRoundtrip( bytes32 id - ) public { - assertEq( - this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Stellar), OracleAddress.Kind.Stellar), id - ); + ) public view { + assertEq(this.decodeAddress(AddressStrings.stellar(id)), id); } function testFuzzSolanaAddressRoundtrip( bytes32 id - ) public { - assertEq(this.decodeAddress(OracleAddress.encode(id, OracleAddress.Kind.Solana), OracleAddress.Kind.Solana), id); + ) public view { + assertEq(this.decodeAddress(AddressStrings.solana(id)), id); + } + + function testFuzzEvmAddress( + address a + ) public view { + bytes32 id = bytes32(uint256(uint160(a))); + assertEq(this.decodeAddress(vm.toString(a)), id); + assertEq(this.decodeAddress(AddressStrings.evm(id)), id); } // Vectors generated with @solana/web3.js PublicKey.toBase58(). @@ -60,8 +66,8 @@ contract OracleAddressTest is Test { "Ed25519SigVerify111111111111111111111111111" ]; for (uint256 i; i < ids.length; ++i) { - assertEq(OracleAddress.encode(ids[i], OracleAddress.Kind.Solana), strings[i]); - assertEq(this.decodeAddress(strings[i], OracleAddress.Kind.Solana), ids[i]); + assertEq(AddressStrings.solana(ids[i]), strings[i]); + assertEq(this.decodeAddress(strings[i]), ids[i]); } // 31 decoded bytes, 33 decoded bytes, a character outside the alphabet, and 45 characters. string[4] memory bad = [ @@ -72,18 +78,34 @@ contract OracleAddressTest is Test { ]; for (uint256 i; i < bad.length; ++i) { vm.expectRevert(); - this.decodeAddress(bad[i], OracleAddress.Kind.Solana); + this.decodeAddress(bad[i]); } } function testPublishedStrKeyAndBadChecksum() public { string memory zero = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4"; - assertEq(OracleAddress.encode(bytes32(0), OracleAddress.Kind.Stellar), zero); - assertEq(this.decodeAddress(zero, OracleAddress.Kind.Stellar), bytes32(0)); - vm.expectRevert(); - this.decodeAddress("CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC5", OracleAddress.Kind.Stellar); - vm.expectRevert(); - this.decodeAddress("GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", OracleAddress.Kind.Stellar); + assertEq(AddressStrings.stellar(bytes32(0)), zero); + assertEq(this.decodeAddress(zero), bytes32(0)); + vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); + this.decodeAddress("CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC5"); + vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); + this.decodeAddress("GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"); + } + + function testMalformedShapesRejected() public { + string[4] memory bad = [ + "", + "0x000000000000000000000000000000000000000", + "0x000000000000000000000000000000000000000g", + "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + ]; + assertEq(bytes(bad[1]).length, 41); + assertEq(bytes(bad[2]).length, 42); + assertEq(bytes(bad[3]).length, 56); + for (uint256 i; i < bad.length; ++i) { + vm.expectRevert(OracleAddress.InvalidOracleAddress.selector); + this.decodeAddress(bad[i]); + } } function testTrailingMessageBytesRejected() public { diff --git a/test/oracle/transport/AxelarOracle.t.sol b/test/oracle/transport/AxelarOracle.t.sol deleted file mode 100644 index 23ee742d..00000000 --- a/test/oracle/transport/AxelarOracle.t.sol +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.26; -import { AxelarOracle } from "../../../src/integrations/oracles/axelar/AxelarOracle.sol"; -import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; -import { MappedOracle } from "../../../src/integrations/oracles/common/MappedOracle.sol"; -import { OracleAddress } from "../../../src/integrations/oracles/common/OracleAddress.sol"; -import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; -import { BoundAttester } from "./BoundAttester.sol"; -import { GatewayFixture } from "./GatewayFixture.sol"; -import { Test } from "forge-std/Test.sol"; -import { Ownable } from "openzeppelin/access/Ownable.sol"; - -contract AxelarOracleTest is Test { - GatewayFixture gateway; - AxelarOracle axelar; - BoundAttester source; - bytes32 constant SENDER = keccak256("stellar oracle"); - bytes32 constant APP = keccak256("stellar settler"); - uint256 constant CHAIN = 0x53544c; - - function setUp() public { - gateway = new GatewayFixture(); - source = new BoundAttester(); - axelar = new AxelarOracle(address(this), address(gateway), address(gateway)); - axelar.setChainMap("stellar", CHAIN, OracleAddress.Kind.Stellar); - } - - receive() external payable { } - - function payloads() internal pure returns (bytes[] memory p) { - p = new bytes[](2); - p[0] = hex"d1252dff012345"; - p[1] = hex"830c1e1c987654"; - } - - function encode( - bytes32 application, - bytes[] calldata p - ) external pure returns (bytes memory) { - return MessageEncodingLib.encodeMessage(application, p); - } - - function testSolanaEnvelopeAndExplicitSelfRelay() public { - AxelarOracle oracle = new AxelarOracle(address(this), address(gateway), address(gateway)); - oracle.setChainMap("solana", 9, OracleAddress.Kind.Solana); - source.setOracle(address(oracle)); - bytes[] memory p = new bytes[](1); - p[0] = new bytes(320); - bytes32 config = keccak256("config"); - oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); - assertEq(gateway.paid(), 0); - assertEq(gateway.lastSender(), address(oracle)); - assertEq( - gateway.lastMessage(), - bytes.concat( - hex"0064010000", - this.encode(bytes32(uint256(uint160(address(source)))), p), - hex"01000000", - config, - hex"00" - ) - ); - assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Solana)); - vm.expectRevert(); - oracle.submit{ value: 1 }("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); - vm.expectRevert(); - oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); - oracle.submit{ value: 10 }("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.Relayed); - assertEq(gateway.paid(), 10); - vm.expectRevert(); - oracle.submit("solana", SENDER, address(source), p, bytes32(0), AxelarOracle.DeliveryMode.SelfRelay); - p[0] = new bytes(321); - vm.expectRevert(); - oracle.submit("solana", SENDER, address(source), p, config, AxelarOracle.DeliveryMode.SelfRelay); - } - - function testAxelarExportAndAuthenticatedNamespace() public { - source.setOracle(address(axelar)); - axelar.submit{ value: 10 }( - "stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed - ); - assertEq(gateway.lastSender(), address(axelar)); - assertEq(gateway.lastRefund(), address(this)); - assertEq(gateway.lastDestination(), OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar)); - bytes memory m = this.encode(APP, payloads()); - string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); - vm.expectRevert(); - axelar.execute(bytes32(0), "stellar", sender, m); - gateway.approve(bytes32(0), "stellar", sender, address(axelar), m); - axelar.execute(bytes32(0), "stellar", sender, m); - assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); - assertFalse(axelar.isProven(CHAIN, bytes32(uint256(1)), APP, keccak256(payloads()[0]))); - vm.expectRevert(); - axelar.execute(bytes32(0), "stellar", sender, m); - gateway.approve(bytes32(uint256(1)), "stellar", sender, address(axelar), m); - axelar.execute(bytes32(uint256(1)), "stellar", sender, m); - } - - function testAxelarChainMapOwnerSetOnce() public { - vm.prank(address(0xBEEF)); - vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); - axelar.setChainMap("evm", 1, OracleAddress.Kind.Evm); - vm.expectRevert(MappedOracle.ZeroValue.selector); - axelar.setChainMap("evm", 0, OracleAddress.Kind.Evm); - vm.expectRevert(MappedOracle.AlreadySet.selector); - axelar.setChainMap("stellar", 2, OracleAddress.Kind.Evm); - vm.expectRevert(MappedOracle.AlreadySet.selector); - axelar.setChainMap("evm", CHAIN, OracleAddress.Kind.Evm); - string[4] memory bad = ["Evm", "", "abcdefghijklmnopqrstu", "e_vm"]; - for (uint256 i; i < bad.length; ++i) { - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); - axelar.setChainMap(bad[i], 2, OracleAddress.Kind.Evm); - } - vm.expectEmit(address(axelar)); - emit AxelarOracle.ChainMapConfigured("evm", 1, OracleAddress.Kind.Evm); - axelar.setChainMap("evm", 1, OracleAddress.Kind.Evm); - assertEq(axelar.reverseChainIdMap(1), keccak256("evm")); - for (uint256 i; i < 17; ++i) { - axelar.setChainMap(string.concat("c", vm.toString(i)), 1000 + i, OracleAddress.Kind.Evm); - } - assertEq(axelar.route("C16").chainId, 1016); - vm.expectRevert(BoundedOracle.UnknownChain.selector); - axelar.route("stellar "); - axelar.renounceOwnership(); - vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(this))); - axelar.setChainMap("late", 5, OracleAddress.Kind.Evm); - } - - function testAxelarLowercaseLookupForwardsCanonicalName() public { - source.setOracle(address(axelar)); - axelar.submit{ value: 10 }( - "STELLAR", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed - ); - assertEq(gateway.lastChain(), "stellar"); - assertEq(gateway.lastGasChain(), "stellar"); - bytes memory m = this.encode(APP, payloads()); - string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); - gateway.approve(bytes32(uint256(7)), "Stellar", sender, address(axelar), m); - axelar.execute(bytes32(uint256(7)), "Stellar", sender, m); - assertTrue(axelar.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); - } - - function testBoundsMalformedRollbackAndExportNamespace() public { - bytes memory m = bytes.concat(this.encode(APP, payloads()), hex"00"); - string memory sender = OracleAddress.encode(SENDER, OracleAddress.Kind.Stellar); - gateway.approve(bytes32(0), "stellar", sender, address(axelar), m); - bytes32 key = keccak256(abi.encode(bytes32(0), "stellar", sender, address(axelar), keccak256(m))); - vm.expectRevert(); - axelar.execute(bytes32(0), "stellar", sender, m); - assertTrue(gateway.approvals(key)); - vm.expectRevert(); - axelar.submit{ value: 10 }( - "stellar", SENDER, address(source), payloads(), bytes32(0), AxelarOracle.DeliveryMode.Relayed - ); - source.setOracle(address(axelar)); - bytes[] memory big = new bytes[](1); - big[0] = new bytes(685); - vm.expectRevert(); - axelar.submit{ value: 10 }( - "stellar", SENDER, address(source), big, bytes32(0), AxelarOracle.DeliveryMode.Relayed - ); - } -} From bfcfd8809090564720d2f8709960dcd75647c3e2 Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 14 Oct 2026 19:01:47 +0400 Subject: [PATCH 14/14] refactor(layerzero): build LayerZeroOracle on shared ChainMap Drop MappedOracle/BoundedOracle (removed in b8a4178). The oracle now inherits BaseInputOracle and ChainMap with key = uint256(eid). - setChainMap(uint256 eid, uint256 chainId, Security) is the only way to add a route: it validates the EID fits uint32 and the Security config, maps through ChainMap.setChainMap (ZeroValue/AlreadySet/ChainMapConfigured) and pins libraries, executor and ULN config in the same call. The plain ChainMap.setChainMap(uint256,uint256) is overridden to revert SecurityRequired so no route can open on endpoint defaults. - Security gains maxMessageSize (nonzero), pinned in the executor config, replacing BoundedOracle's fixed 2,778-byte MAX_MESSAGE. - No Stellar count/size admission checks; destinations enforce their own. - submit/lzReceive inline export/record like HyperlaneOracle (NotAllPayloadsValid; OutputProven on every record). Unmapped destinations and origins revert ZeroValue; route(eid), UnknownChain and the uint32 ChainMapConfigured event are removed (use chainIdMap). - Tests cover the disabled 2-arg setter, uint32 bound, security validation, unmapped send/receive, and malformed-message rollback. --- .../oracles/layerzero/LayerZeroOracle.sol | 118 ++++++++----- test/oracle/layerzero/LayerZeroOracle.t.sol | 161 ++++++++++++++---- 2 files changed, 207 insertions(+), 72 deletions(-) diff --git a/src/integrations/oracles/layerzero/LayerZeroOracle.sol b/src/integrations/oracles/layerzero/LayerZeroOracle.sol index 9486a3f3..82b22d36 100644 --- a/src/integrations/oracles/layerzero/LayerZeroOracle.sol +++ b/src/integrations/oracles/layerzero/LayerZeroOracle.sol @@ -1,7 +1,11 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { MappedOracle } from "../common/MappedOracle.sol"; +import { IAttester } from "../../../interfaces/IAttester.sol"; +import { LibAddress } from "../../../libs/LibAddress.sol"; +import { MessageEncodingLib } from "../../../libs/MessageEncodingLib.sol"; +import { BaseInputOracle } from "../../../oracles/BaseInputOracle.sol"; +import { ChainMap } from "../../../oracles/ChainMap.sol"; struct Origin { uint32 srcEid; @@ -61,9 +65,18 @@ interface IOracleEndpointV2 { ) external; } -/// Transparent OApp: authenticated Origin.sender is preserved, never replaced by a configured peer. The owner adds -/// set-once routes; each route pins its own libraries, executor and DVN configuration when it is added. -contract LayerZeroOracle is MappedOracle { +/// @title LayerZeroOracle +/// @notice Transparent LayerZero V2 OApp: the authenticated `Origin.sender` is recorded as the proving oracle, never +/// replaced by a configured peer. +/// @dev The owner maps a LayerZero endpoint ID to an OIF chain through `setChainMap(eid, chainId, security)`, with +/// `ChainMap` key `uint256(eid)`. Each map is set once and pins that route's libraries, executor and DVN configuration +/// in the same call, so a path never runs on the endpoint's mutable defaults. The plain `ChainMap.setChainMap` is +/// disabled. Paths open (`allowInitializePath`) only for mapped endpoint IDs, and only mapped destinations can be sent +/// to. No Stellar message limits are enforced here beyond each route's executor `maxMessageSize`; destinations enforce +/// their own, so clients split batches to fit. +contract LayerZeroOracle is BaseInputOracle, ChainMap { + using LibAddress for address; + struct UlnConfig { uint64 confirmations; uint8 requiredDVNCount; @@ -78,10 +91,19 @@ contract LayerZeroOracle is MappedOracle { address executor; } + /// @param sendLibrary Send message library pinned for the route. + /// @param receiveLibrary Receive message library pinned for the route (no grace period). + /// @param executor Executor pinned for the route. + /// @param maxMessageSize Largest message the route sends; nonzero, so the library default is never inherited. + /// @param sendConfirmations Block confirmations required on send; not 0 or NIL (`type(uint64).max`). + /// @param receiveConfirmations Block confirmations required on receive; not 0 or NIL. + /// @param sendDvns Required send DVNs, strictly ascending, 1–127. Optional DVNs are disabled. + /// @param receiveDvns Required receive DVNs, strictly ascending, 1–127. Optional DVNs are disabled. struct Security { address sendLibrary; address receiveLibrary; address executor; + uint32 maxMessageSize; uint64 sendConfirmations; uint64 receiveConfirmations; address[] sendDvns; @@ -90,54 +112,58 @@ contract LayerZeroOracle is MappedOracle { IOracleEndpointV2 public immutable endpoint; + error InvalidConfiguration(); + error SecurityRequired(); + error NotAllPayloadsValid(); error OnlyEndpoint(); error UnexpectedValue(); error InvalidOptions(); - event ChainMapConfigured(uint32 eid, uint256 chainId); - constructor( address owner_, address endpoint_ - ) MappedOracle(owner_) { + ) ChainMap(owner_) { if (endpoint_.code.length == 0) revert InvalidConfiguration(); endpoint = IOracleEndpointV2(endpoint_); } - /// Set an immutable map from a LayerZero endpoint ID to an OIF chain and pin the route's security configuration. - /// Each endpoint ID and chain ID is set once; paths open only after this call. + /// @notice Disabled: a route must pin its security configuration when it is mapped. + /// @dev Use `setChainMap(eid, chainId, security)`. function setChainMap( - uint32 eid, + uint256, + uint256 + ) public pure override { + revert SecurityRequired(); + } + + /// @notice Sets an immutable map from a LayerZero endpoint ID to an OIF chain ID and pins the route's security + /// configuration on the endpoint. Paths to and from `eid` open only after this call. + /// @dev Each endpoint ID and chain ID is set once (`ChainMap.AlreadySet`); zero values revert `ChainMap.ZeroValue`. + /// @param eid LayerZero endpoint ID; must fit `uint32`. + /// @param chainId OIF chain ID. + /// @param s Route security configuration. + function setChainMap( + uint256 eid, uint256 chainId, Security calldata s ) external onlyOwner { - if (eid == 0) revert ZeroValue(); - if (s.executor == address(0) || s.sendLibrary == address(0) || s.receiveLibrary == address(0)) { - revert InvalidConfiguration(); - } - _setRoute(_key(eid), chainId); - endpoint.setSendLibrary(address(this), eid, s.sendLibrary); - endpoint.setReceiveLibrary(address(this), eid, s.receiveLibrary, 0); + if (eid > type(uint32).max) revert InvalidConfiguration(); + if ( + s.executor == address(0) || s.sendLibrary == address(0) || s.receiveLibrary == address(0) + || s.maxMessageSize == 0 + ) revert InvalidConfiguration(); + super.setChainMap(eid, chainId); + // forge-lint: disable-next-line(unsafe-typecast) + uint32 id = uint32(eid); // Checked above. + endpoint.setSendLibrary(address(this), id, s.sendLibrary); + endpoint.setReceiveLibrary(address(this), id, s.receiveLibrary, 0); SetConfigParam[] memory sendConfig = new SetConfigParam[](2); - sendConfig[0] = SetConfigParam(eid, 1, abi.encode(ExecutorConfig(uint32(MAX_MESSAGE), s.executor))); - sendConfig[1] = SetConfigParam(eid, 2, _uln(s.sendConfirmations, s.sendDvns)); + sendConfig[0] = SetConfigParam(id, 1, abi.encode(ExecutorConfig(s.maxMessageSize, s.executor))); + sendConfig[1] = SetConfigParam(id, 2, _uln(s.sendConfirmations, s.sendDvns)); endpoint.setConfig(address(this), s.sendLibrary, sendConfig); SetConfigParam[] memory receiveConfig = new SetConfigParam[](1); - receiveConfig[0] = SetConfigParam(eid, 2, _uln(s.receiveConfirmations, s.receiveDvns)); + receiveConfig[0] = SetConfigParam(id, 2, _uln(s.receiveConfirmations, s.receiveDvns)); endpoint.setConfig(address(this), s.receiveLibrary, receiveConfig); - emit ChainMapConfigured(eid, chainId); - } - - function route( - uint32 eid - ) external view returns (uint256) { - return _chainId(_key(eid)); - } - - function _key( - uint32 eid - ) private pure returns (bytes32) { - return bytes32(uint256(eid)); } function _uln( @@ -157,6 +183,7 @@ contract LayerZeroOracle is MappedOracle { return abi.encode(UlnConfig(confirmations, uint8(dvns.length), 255, 0, dvns, new address[](0))); } + /// @notice Quotes `submit` for the same arguments. Does not check that `source` attested the payloads. function quote( uint32 dstEid, bytes32 recipientOracle, @@ -165,11 +192,13 @@ contract LayerZeroOracle is MappedOracle { bytes calldata options ) external view returns (MessagingFee memory) { _checkDestination(dstEid, options); - return endpoint.quote( - MessagingParams(dstEid, recipientOracle, _encode(source, payloads), options, false), address(this) - ); + bytes memory message = MessageEncodingLib.encodeMessage(source.toIdentifier(), payloads); + return endpoint.quote(MessagingParams(dstEid, recipientOracle, message, options, false), address(this)); } + /// @notice Sends attested payloads to the oracle `recipientOracle` on the mapped endpoint `dstEid`. + /// @dev Unmapped destinations revert `ChainMap.ZeroValue`. Excess `msg.value` is refunded to the caller by the + /// endpoint. function submit( uint32 dstEid, bytes32 recipientOracle, @@ -178,8 +207,10 @@ contract LayerZeroOracle is MappedOracle { bytes calldata options ) external payable returns (MessagingReceipt memory) { _checkDestination(dstEid, options); + if (!IAttester(source).hasAttested(payloads)) revert NotAllPayloadsValid(); + bytes memory message = MessageEncodingLib.encodeMessage(source.toIdentifier(), payloads); return endpoint.send{ value: msg.value }( - MessagingParams(dstEid, recipientOracle, _export(source, payloads), options, false), msg.sender + MessagingParams(dstEid, recipientOracle, message, options, false), msg.sender ); } @@ -187,7 +218,7 @@ contract LayerZeroOracle is MappedOracle { uint32 eid, bytes calldata options ) private view { - _chainId(_key(eid)); + _getMappedChainId(eid); _checkOptions(options); } @@ -203,7 +234,7 @@ contract LayerZeroOracle is MappedOracle { function allowInitializePath( Origin calldata origin ) external view returns (bool) { - return _chainIds[_key(origin.srcEid)] != 0; + return chainIdMap[origin.srcEid] != 0; } function nextNonce( @@ -217,6 +248,7 @@ contract LayerZeroOracle is MappedOracle { return (1, 1); } + /// @notice Records the payload hashes of an endpoint-verified message under its authenticated origin. function lzReceive( Origin calldata origin, bytes32, @@ -226,7 +258,11 @@ contract LayerZeroOracle is MappedOracle { ) external payable { if (msg.sender != address(endpoint)) revert OnlyEndpoint(); if (msg.value != 0) revert UnexpectedValue(); - uint256 chain = _chainId(_key(origin.srcEid)); - _record(chain, origin.sender, message); + uint256 chainId = _getMappedChainId(origin.srcEid); + (bytes32 application, bytes32[] memory hashes) = MessageEncodingLib.getHashesOfEncodedPayloads(message); + for (uint256 i; i < hashes.length; ++i) { + _attestations[chainId][origin.sender][application][hashes[i]] = true; + emit OutputProven(chainId, origin.sender, application, hashes[i]); + } } } diff --git a/test/oracle/layerzero/LayerZeroOracle.t.sol b/test/oracle/layerzero/LayerZeroOracle.t.sol index 44135494..8e1f9baf 100644 --- a/test/oracle/layerzero/LayerZeroOracle.t.sol +++ b/test/oracle/layerzero/LayerZeroOracle.t.sol @@ -1,10 +1,11 @@ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; -import { BoundedOracle } from "../../../src/integrations/oracles/common/BoundedOracle.sol"; -import { MappedOracle } from "../../../src/integrations/oracles/common/MappedOracle.sol"; + import { LayerZeroOracle, Origin } from "../../../src/integrations/oracles/layerzero/LayerZeroOracle.sol"; import { MessageEncodingLib } from "../../../src/libs/MessageEncodingLib.sol"; -import { BoundAttester } from "./BoundAttester.sol"; +import { BaseInputOracle } from "../../../src/oracles/BaseInputOracle.sol"; +import { ChainMap } from "../../../src/oracles/ChainMap.sol"; +import { BoundAttester } from "../axelar/BoundAttester.sol"; import { EndpointFixture } from "./EndpointFixture.sol"; import { Test } from "forge-std/Test.sol"; import { Ownable } from "openzeppelin/access/Ownable.sol"; @@ -16,12 +17,13 @@ contract LayerZeroOracleTest is Test { bytes32 constant SENDER = keccak256("stellar oracle"); bytes32 constant APP = keccak256("stellar settler"); uint256 constant CHAIN = 0x53544c; + uint32 constant EID = 30600; function setUp() public { endpoint = new EndpointFixture(); source = new BoundAttester(); lz = new LayerZeroOracle(address(this), address(endpoint)); - lz.setChainMap(30600, CHAIN, security(1, 1)); + lz.setChainMap(EID, CHAIN, security(1, 1)); } function security( @@ -30,7 +32,7 @@ contract LayerZeroOracleTest is Test { ) internal pure returns (LayerZeroOracle.Security memory s) { address[] memory dvns = new address[](1); dvns[0] = address(0x1234); - s = LayerZeroOracle.Security(address(1), address(2), address(3), send, recv, dvns, dvns); + s = LayerZeroOracle.Security(address(1), address(2), address(3), 2778, send, recv, dvns, dvns); } receive() external payable { } @@ -52,82 +54,170 @@ contract LayerZeroOracleTest is Test { return abi.encodePacked(hex"000301001101", uint128(200_000)); } + function testConstructorRequiresEndpointCode() public { + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + new LayerZeroOracle(address(this), address(0xE11D)); + } + function testLayerZeroExportReceiveReplayAndFees() public { source.setOracle(address(lz)); uint256 beforeBalance = address(this).balance; - lz.submit{ value: 20 }(30600, SENDER, address(source), payloads(), options()); + lz.submit{ value: 20 }(EID, SENDER, address(source), payloads(), options()); assertEq(address(this).balance, beforeBalance - 10); assertEq(endpoint.lastRecipient(), SENDER); + assertEq(endpoint.lastSender(), address(lz)); + assertEq(endpoint.lastMessage(), this.encode(bytes32(uint256(uint160(address(source)))), payloads())); + bytes memory m = this.encode(APP, payloads()); - Origin memory o = Origin(30600, SENDER, 1); - vm.expectRevert(); + Origin memory o = Origin(EID, SENDER, 1); + vm.expectRevert(LayerZeroOracle.OnlyEndpoint.selector); lz.lzReceive(o, bytes32(0), m, address(this), ""); endpoint.approve(address(lz), o, bytes32(0), m); + for (uint256 i; i < 2; ++i) { + vm.expectEmit(address(lz)); + emit BaseInputOracle.OutputProven(CHAIN, SENDER, APP, keccak256(payloads()[i])); + } endpoint.deliver(address(lz), o, bytes32(0), m); + assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[0]))); assertTrue(lz.isProven(CHAIN, SENDER, APP, keccak256(payloads()[1]))); - vm.expectRevert(); + assertFalse(lz.isProven(CHAIN, keccak256("other"), APP, keccak256(payloads()[1]))); + vm.expectRevert("unverified"); endpoint.deliver(address(lz), o, bytes32(0), m); } - function testQuoteRejectsMissingOptionsAndUnknownChain() public { - vm.expectRevert(); - lz.quote(30600, SENDER, address(source), payloads(), hex""); - vm.expectRevert(); + function testSubmitRejectsUnattestedUnmappedAndBadOptions() public { + vm.expectRevert(LayerZeroOracle.NotAllPayloadsValid.selector); + lz.submit{ value: 10 }(EID, SENDER, address(source), payloads(), options()); + source.setOracle(address(lz)); + vm.expectRevert(ChainMap.ZeroValue.selector); + lz.submit{ value: 10 }(999, SENDER, address(source), payloads(), options()); + vm.expectRevert(LayerZeroOracle.InvalidOptions.selector); + lz.submit{ value: 10 }(EID, SENDER, address(source), payloads(), hex""); + } + + function testQuoteRejectsBadOptionsAndUnmappedChain() public { + assertEq(lz.quote(EID, SENDER, address(source), payloads(), options()).nativeFee, 10); + vm.expectRevert(LayerZeroOracle.InvalidOptions.selector); + lz.quote(EID, SENDER, address(source), payloads(), hex""); + vm.expectRevert(LayerZeroOracle.InvalidOptions.selector); + lz.quote(EID, SENDER, address(source), payloads(), abi.encodePacked(hex"000301001101", uint128(0))); + vm.expectRevert(ChainMap.ZeroValue.selector); lz.quote(999, SENDER, address(source), payloads(), options()); } - function testLayerZeroRejectsNilConfirmations() public { + function testReceiveRejectsValueAndUnmappedOrigin() public { + bytes memory m = this.encode(APP, payloads()); + vm.deal(address(endpoint), 1); + vm.prank(address(endpoint)); + vm.expectRevert(LayerZeroOracle.UnexpectedValue.selector); + lz.lzReceive{ value: 1 }(Origin(EID, SENDER, 1), bytes32(0), m, address(this), ""); + vm.prank(address(endpoint)); + vm.expectRevert(ChainMap.ZeroValue.selector); + lz.lzReceive(Origin(999, SENDER, 1), bytes32(0), m, address(this), ""); + assertFalse(lz.allowInitializePath(Origin(999, SENDER, 1))); + assertTrue(lz.allowInitializePath(Origin(EID, SENDER, 1))); + } + + function testLayerZeroRejectsInvalidSecurity() public { LayerZeroOracle o = new LayerZeroOracle(address(this), address(endpoint)); - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); o.setChainMap(30601, 7, security(type(uint64).max, 1)); - vm.expectRevert(BoundedOracle.InvalidConfiguration.selector); + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); o.setChainMap(30601, 7, security(1, type(uint64).max)); + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, security(0, 1)); + + LayerZeroOracle.Security memory s = security(1, 1); + s.maxMessageSize = 0; + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, s); + s = security(1, 1); + s.executor = address(0); + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, s); + + s = security(1, 1); + address[] memory unsorted = new address[](2); + unsorted[0] = address(0x2); + unsorted[1] = address(0x1); + s.receiveDvns = unsorted; + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, s); + s.receiveDvns = new address[](0); + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + o.setChainMap(30601, 7, s); + + // A failed setter leaves the route unmapped. + assertEq(o.chainIdMap(30601), 0); + assertFalse(o.allowInitializePath(Origin(30601, SENDER, 1))); + } + + function testPlainChainMapSetterDisabled() public { + vm.expectRevert(LayerZeroOracle.SecurityRequired.selector); + lz.setChainMap(30601, 1); + vm.prank(address(0xBEEF)); + vm.expectRevert(LayerZeroOracle.SecurityRequired.selector); + lz.setChainMap(30601, 1); + assertEq(lz.chainIdMap(30601), 0); + } + + function testEidMustFitUint32() public { + vm.expectRevert(LayerZeroOracle.InvalidConfiguration.selector); + lz.setChainMap(uint256(type(uint32).max) + 1, 1, security(1, 1)); + lz.setChainMap(type(uint32).max, 1, security(1, 1)); + assertEq(lz.chainIdMap(type(uint32).max), 1); } function testLayerZeroChainMapOwnerSetOnce() public { vm.prank(address(0xBEEF)); vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(0xBEEF))); lz.setChainMap(30601, 1, security(1, 1)); - vm.expectRevert(MappedOracle.ZeroValue.selector); + vm.expectRevert(ChainMap.ZeroValue.selector); lz.setChainMap(0, 1, security(1, 1)); - vm.expectRevert(MappedOracle.ZeroValue.selector); + vm.expectRevert(ChainMap.ZeroValue.selector); lz.setChainMap(30601, 0, security(1, 1)); - vm.expectRevert(MappedOracle.AlreadySet.selector); - lz.setChainMap(30600, 1, security(1, 1)); - vm.expectRevert(MappedOracle.AlreadySet.selector); + vm.expectRevert(ChainMap.AlreadySet.selector); + lz.setChainMap(EID, 1, security(1, 1)); + vm.expectRevert(ChainMap.AlreadySet.selector); lz.setChainMap(30601, CHAIN, security(1, 1)); assertFalse(lz.allowInitializePath(Origin(30601, SENDER, 1))); vm.expectEmit(address(lz)); - emit LayerZeroOracle.ChainMapConfigured(30601, 1); + emit ChainMap.ChainMapConfigured(30601, 1); lz.setChainMap(30601, 1, security(1, 1)); assertTrue(lz.allowInitializePath(Origin(30601, SENDER, 1))); assertEq(endpoint.configs(keccak256(abi.encode(address(lz), uint32(30601), "send"))), abi.encode(address(1))); - assertEq(lz.reverseChainIdMap(1), bytes32(uint256(30601))); + assertEq(endpoint.configs(keccak256(abi.encode(address(lz), uint32(30601), "receive"))), abi.encode(address(2))); + assertEq( + endpoint.configs(keccak256(abi.encode(address(lz), address(1), uint32(30601), uint32(1)))), + abi.encode(LayerZeroOracle.ExecutorConfig(2778, address(3))) + ); + assertEq(lz.chainIdMap(30601), 1); + assertEq(lz.reverseChainIdMap(1), 30601); for (uint32 i; i < 17; ++i) { lz.setChainMap(30700 + i, 2000 + i, security(1, 1)); } - assertEq(lz.route(30716), 2016); + assertEq(lz.chainIdMap(30716), 2016); lz.renounceOwnership(); vm.expectRevert(abi.encodeWithSelector(Ownable.OwnableUnauthorizedAccount.selector, address(this))); lz.setChainMap(30800, 3000, security(1, 1)); } - function testMaximumBatchAndTupleChecks() public { - bytes[] memory p = new bytes[](4); - for (uint256 i; i < 4; ++i) { - p[i] = new bytes(684); + /// Receipt records batches beyond Stellar's limits; destinations enforce their own. + function testLargeBatchAndTupleChecks() public { + bytes[] memory p = new bytes[](5); + for (uint256 i; i < 5; ++i) { + p[i] = new bytes(700); p[i][0] = bytes1(uint8(i)); } bytes memory m = this.encode(APP, p); - assertEq(m.length, 2778); - Origin memory o = Origin(30600, SENDER, 1); + Origin memory o = Origin(EID, SENDER, 1); endpoint.approve(address(lz), o, bytes32(0), m); endpoint.deliver(address(lz), o, bytes32(0), m); bytes memory proofs; - for (uint256 i; i < 4; ++i) { + for (uint256 i; i < 5; ++i) { proofs = bytes.concat(proofs, abi.encodePacked(CHAIN, SENDER, APP, keccak256(p[i]))); } lz.efficientRequireProven(proofs); @@ -135,4 +225,13 @@ contract LayerZeroOracleTest is Test { vm.expectRevert(); lz.efficientRequireProven(bytes.concat(proofs, hex"00")); } + + function testMalformedMessageReverts() public { + bytes memory m = bytes.concat(this.encode(APP, payloads()), hex"00"); + Origin memory o = Origin(EID, SENDER, 1); + endpoint.approve(address(lz), o, bytes32(0), m); + vm.expectRevert(); + endpoint.deliver(address(lz), o, bytes32(0), m); + assertTrue(endpoint.approvals(keccak256(abi.encode(address(lz), o, bytes32(0), m)))); + } }