Verified contractPartialGPL-3.0-or-later WITH Classpath-exception-2.0
VaraQueueRootVerifier
Address0xeb005d5af2adbfa74c793064b421d45407c90531
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.38
- Same code
Only this contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- osaka
- Via IR
- yes
- License
- GPL-3.0-or-later WITH Classpath-exception-2.0
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,406,932
- Creation transaction
- 0x9cc7102c60…e385c5a48f
11 files
- src/VaraQueueRootVerifier.solmain7.27 KB
- dependencies/@openzeppelin-contracts-5.7.0/utils/cryptography/ECDSA.sol12.13 KB
- src/beefy/BeefyClient.sol36.6 KB
- src/beefy/VaraBridgeMetadata.sol1.88 KB
- src/beefy/utils/Bitfield.sol8.92 KB
- src/beefy/utils/Bits.sol971 B
- src/beefy/utils/MMRProof.sol1.67 KB
- src/beefy/utils/ScaleCodec.sol2.77 KB
- src/beefy/utils/SubstrateMerkleProof.sol3.15 KB
- src/interfaces/IQueueProgressVerifier.sol353 B
- src/interfaces/IVerifier.sol745 B
src/VaraQueueRootVerifier.sol
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
pragma solidity ^0.8.37;
import {BeefyClient} from "src/beefy/BeefyClient.sol";
import {VaraBridgeMetadata} from "src/beefy/VaraBridgeMetadata.sol";
import {IQueueProgressVerifier} from "src/interfaces/IQueueProgressVerifier.sol";
import {IVerifier} from "src/interfaces/IVerifier.sol";
/// Authenticates Vara queue snapshots against an exact retained accepted BEEFY root.
contract VaraQueueRootVerifier is IVerifier, IQueueProgressVerifier {
BeefyClient public immutable beefyClient;
address public immutable messageQueue;
uint256 public immutable destinationChainId;
constructor(BeefyClient client_, address messageQueue_, uint256 destinationChainId_) {
require(address(client_).code.length != 0, "BEEFY client has no code");
require(
client_.minNumRequiredSignatures() == 334 && client_.fiatShamirRequiredSignatures() == 334
&& client_.MAX_VALIDATORS() == 1000 && client_.randaoCommitDelay() == 128
&& client_.randaoCommitExpiration() == 24,
"client policy mismatch"
);
require(messageQueue_ != address(0), "message queue is zero");
require(destinationChainId_ == block.chainid, "wrong deployment chain");
require(client_.destinationChainId() == destinationChainId_, "client chain mismatch");
require(client_.destinationQueue() == messageQueue_, "client queue mismatch");
require(
client_.bridgeDomain() == _bridgeDomain(client_.sourceDomain(), destinationChainId_, messageQueue_),
"client bridge domain mismatch"
);
beefyClient = client_;
messageQueue = messageQueue_;
destinationChainId = destinationChainId_;
}
function safeVerifyProof(uint256 sourceBlock, bytes32 merkleRoot, bytes calldata proof)
external
view
returns (bool)
{
if (msg.sender != messageQueue || block.chainid != destinationChainId) {
return false;
}
try this.verifyProof(sourceBlock, merkleRoot, proof) returns (bool valid) {
return valid;
} catch {
return false;
}
}
function safeVerifyEmptyQueueProgress(uint256 sourceBlock, bytes calldata proof) external view returns (bool) {
if (msg.sender != messageQueue || block.chainid != destinationChainId) {
return false;
}
try this.verifyEmptyQueueProgress(sourceBlock, proof) returns (bool valid) {
return valid;
} catch {
return false;
}
}
function verifyEmptyQueueProgress(uint256 sourceBlock, bytes calldata proof) external view returns (bool) {
if (msg.sender != address(this) || sourceBlock > type(uint32).max) {
return false;
}
return _verifyProof(proof, bytes32(0), sourceBlock, true);
}
function verifyProof(uint256 sourceBlock, bytes32 merkleRoot, bytes calldata proof) external view returns (bool) {
if (msg.sender != address(this)) {
return false;
}
return _verifyProof(proof, merkleRoot, sourceBlock, false);
}
function _verifyProof(bytes calldata proof, bytes32 root, uint256 sourceBlock, bool emptyProgress)
private
view
returns (bool)
{
if (sourceBlock > type(uint32).max) {
return false;
}
if (proof.length < 576 || proof.length > 576 + 32 * 256 || (proof.length - 576) % 32 != 0) {
return false;
}
(
uint8 proofVersion,
uint8 bridgeVersion,
bool initialized,
bytes32 bridgeDomain,
uint64 sourceTimestampMs,
uint64 queueId,
uint64 anchorBlock,
bytes32 anchorRoot,
BeefyClient.MMRLeaf memory leaf,
bytes32[] memory items,
uint256 proofOrder
) = abi.decode(
proof,
(uint8, uint8, bool, bytes32, uint64, uint64, uint64, bytes32, BeefyClient.MMRLeaf, bytes32[], uint256)
);
if (items.length > 256 || (items.length < 256 && proofOrder >> items.length != 0)) {
return false;
}
if (proof.length != 576 + 32 * items.length) {
return false;
}
if (
keccak256(proof)
!= keccak256(
abi.encode(
proofVersion,
bridgeVersion,
initialized,
bridgeDomain,
sourceTimestampMs,
queueId,
anchorBlock,
anchorRoot,
leaf,
items,
proofOrder
)
)
) {
return false;
}
if (!beefyClient.isLive()) {
return false;
}
if ((emptyProgress ? root != bytes32(0) : root == bytes32(0)) || !initialized) {
return false;
}
VaraBridgeMetadata.Snapshot memory snapshot =
_snapshot(bridgeDomain, sourceTimestampMs, initialized, queueId, root);
if (
proofVersion != 2 || bridgeVersion != 2 || bridgeDomain != beefyClient.bridgeDomain()
|| bridgeDomain != _bridgeDomain(beefyClient.sourceDomain(), destinationChainId, messageQueue)
|| snapshot.queueRoot != root
) {
return false;
}
if (leaf.version != 0 || leaf.parentNumber != sourceBlock) {
return false;
}
if (uint64(sourceBlock) < beefyClient.mmrStartBlock() || sourceBlock >= anchorBlock) {
return false;
}
if (!beefyClient.isAcceptedAnchor(anchorBlock, anchorRoot)) {
return false;
}
if (VaraBridgeMetadata.hash(snapshot) != leaf.parachainHeadsRoot) {
return false;
}
bytes32 leafHash = keccak256(
VaraBridgeMetadata.encodeMMRLeaf(
leaf.version,
leaf.parentNumber,
leaf.parentHash,
leaf.nextAuthoritySetID,
leaf.nextAuthoritySetLen,
leaf.nextAuthoritySetRoot,
leaf.parachainHeadsRoot
)
);
return beefyClient.verifyMMRLeafProof(anchorBlock, anchorRoot, leafHash, items, proofOrder);
}
function _bridgeDomain(bytes32 sourceDomain, uint256 chainId, address queue) private pure returns (bytes32) {
return keccak256(abi.encodePacked("vara/gear-eth-bridge-domain/v2", sourceDomain, bytes32(chainId), queue));
}
function _snapshot(bytes32 bridgeDomain, uint64 sourceTimestampMs, bool initialized, uint64 queueId, bytes32 root)
private
pure
returns (VaraBridgeMetadata.Snapshot memory snapshot)
{
snapshot = VaraBridgeMetadata.Snapshot({
version: 2,
bridgeDomain: bridgeDomain,
sourceTimestampMs: sourceTimestampMs,
initialized: initialized,
queueId: queueId,
queueRoot: root
});
}
}
dependencies/@openzeppelin-contracts-5.7.0/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature is invalid.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
*
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
* is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
* invalidation or nonces for replay protection.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(err, errorArg);
return recovered;
}
/**
* @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
* formats. Returns (0,0,0) for invalid signatures.
*
* For 64-byte signatures, `v` is automatically normalized to 27 or 28.
* For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
*
* Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
*/
function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch mload(signature)
// - case 65: r,s,v signature (standard)
case 65 {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Variant of {parse} that takes a signature in calldata
*/
function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
assembly ("memory-safe") {
// Check the signature length
switch signature.length
// - case 65: r,s,v signature (standard)
case 65 {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
r := calldataload(signature.offset)
s := and(vs, shr(1, not(0)))
v := add(shr(255, vs), 27)
}
default {
r := 0
s := 0
v := 0
}
}
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError err, bytes32 errorArg) private pure {
if (err == RecoverError.NoError) {
return; // no error: do nothing
} else if (err == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (err == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (err == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
src/beefy/BeefyClient.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
import {VaraBridgeMetadata} from "./VaraBridgeMetadata.sol";
import {Bitfield} from "./utils/Bitfield.sol";
import {MMRProof} from "./utils/MMRProof.sol";
import {ScaleCodec} from "./utils/ScaleCodec.sol";
import {SubstrateMerkleProof} from "./utils/SubstrateMerkleProof.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @title BeefyClient
* @dev This is a client for verifying BEEFY commitments from the Polkadot network.
* it contains two ways to verify BEEFY commitments from a Substrate-based chain,
* one through an interactive protocol, and one through Fiat-Shamir transformation.
*
* The interactive protocol is defined in https://eprint.iacr.org/2025/057.pdf. Higher level documentation
* is available at https://docs.snowbridge.network/architecture/verification/polkadot.
*
* To submit new commitments, relayers must call the following methods sequentially:
* 1. submitInitial: Initializes the session for interactive submission and waits for the Randao delay period
* 2. commitPrevRandao: Commit to a random seed for generating a validator subsampling
* 3. createFinalBitfield: Generate the validator subsampling
* 4. submitFinal: Complete submission after providing the request validator signatures
*
*
* The non-interactive protocol eliminates the need for interaction by applying Fiat-Shamir transform.
* It is defined in Section 6 of https://eprint.iacr.org/2025/057.pdf, with higher-level documentation
* available at https://hackmd.io/8Jd7V74iSSeeHOIG76REWw
*
* To submit new commitments using the Fiat-Shamir approach, relayers call the following methods sequentially:
* 1. createFiatShamirFinalBitfield: Generate the validator subsampling using Fiat-Shamir
* 2. submitFiatShamir: Complete submission after providing the request validator signatures
*/
contract BeefyClient {
/* Events */
/**
* @dev Emitted when the MMR root is updated
* @param mmrRoot the updated MMR root
* @param blockNumber the beefy block number of the updated MMR root
*/
event NewMMRRoot(bytes32 mmrRoot, uint64 blockNumber);
/**
* @dev Emitted when a new ticket has been created
* @param relayer The relayer who created the ticket
* @param blockNumber the parent block number of the candidate MMR root
*/
event NewTicket(address relayer, uint64 blockNumber);
/**
* @dev Interactive session has expired
*/
event TicketExpired();
/* Types */
/**
* @dev The Commitment, with its payload, is the core thing we are trying to verify with
* this contract. It contains an MMR root that commits to the polkadot history, including
* past blocks and parachain blocks and can be used to verify both polkadot and parachain blocks.
*/
struct Commitment {
// Relay chain block number
uint32 blockNumber;
// ID of the validator set that signed the commitment
uint64 validatorSetID;
// The payload of the new commitment in beefy justifications (in
// our case, this is a new MMR root for all past polkadot blocks)
PayloadItem[] payload;
}
/**
* @dev Each PayloadItem is a piece of data signed by validators at a particular block.
*/
struct PayloadItem {
// An ID that references a description of the data in the payload item.
// Known payload ids can be found [upstream](https://github.com/paritytech/substrate/blob/fe1f8ba1c4f23931ae89c1ada35efb3d908b50f5/primitives/consensus/beefy/src/payload.rs#L27).
bytes2 payloadID;
// The contents of the payload item
bytes data;
}
/**
* @dev The ValidatorProof is a proof used to verify a commitment signature
*/
struct ValidatorProof {
// The parity bit to specify the intended solution
uint8 v;
// The x component on the secp256k1 curve
bytes32 r;
// The challenge solution
bytes32 s;
// Leaf index of the validator address in the merkle tree
uint256 index;
// Validator address
address account;
// Merkle proof for the validator
bytes32[] proof;
}
/**
* @dev A ticket tracks working state for the interactive submission of new commitments
*/
struct Ticket {
// The block number this ticket was issued
uint64 blockNumber;
// Length of the validator set that signed the commitment
uint32 validatorSetLen;
// The number of signatures required
uint32 numRequiredSignatures;
// The PREVRANDAO seed selected for this ticket session
uint256 prevRandao;
// Hash of a bitfield claiming which validators have signed
bytes32 bitfieldHash;
}
/// @dev The MMRLeaf describes the leaf structure of the MMR
struct MMRLeaf {
// Version of the leaf type
uint8 version;
// Parent number of the block this leaf describes
uint32 parentNumber;
// Parent hash of the block this leaf describes
bytes32 parentHash;
// Validator set id that will be part of consensus for the next block
uint64 nextAuthoritySetID;
// Length of that validator set
uint32 nextAuthoritySetLen;
// Merkle root of all public keys in that validator set
bytes32 nextAuthoritySetRoot;
// Merkle root of all parachain headers in this block
bytes32 parachainHeadsRoot;
}
/**
* @dev The ValidatorSet describes a BEEFY validator set
*/
struct ValidatorSet {
// Identifier for the set
uint128 id;
// Number of validators in the set
uint128 length;
// Merkle root of BEEFY validator addresses
bytes32 root;
}
/* State */
/// @dev The latest verified MMR root. Bootstrap keeps this zero until a signed update.
bytes32 public latestMMRRoot;
/// @dev The block number in the relay chain in which the latest MMR root was emitted.
uint64 public latestBeefyBlock;
/// @dev Bounded accepted history; bootstrap is deliberately not an accepted anchor.
mapping(uint64 blockNumber => bytes32 root) private acceptedAnchors;
uint64[64] private acceptedAnchorBlocks;
uint8 private nextAcceptedAnchor;
/// @dev Immutable source and destination identity and MMR history start.
bytes32 public immutable sourceDomain;
bytes32 public immutable bridgeDomain;
uint256 public immutable destinationChainId;
address public immutable destinationQueue;
uint64 public immutable mmrStartBlock;
/// @dev Source timestamp authenticated by the latest accepted commitment.
uint64 public lastAuthenticatedSourceTimestampMs;
/// @dev State of the current validator set
ValidatorSet public currentValidatorSet;
/// @dev State of the next validator set
ValidatorSet public nextValidatorSet;
/// @dev Pending tickets for commitment submission
mapping(bytes32 ticketID => Ticket) public tickets;
/* Constants */
/**
* @dev Fiat-Shamir domain separator ID
*/
bytes public constant FIAT_SHAMIR_DOMAIN_ID = bytes("SNOWBRIDGE-FIAT-SHAMIR-V1");
/**
* @dev Beefy payload id for MMR Root payload items:
* https://github.com/paritytech/substrate/blob/fe1f8ba1c4f23931ae89c1ada35efb3d908b50f5/primitives/consensus/beefy/src/payload.rs#L33
*/
// forge-lint: disable-next-line(unsafe-typecast)
bytes2 public constant MMR_ROOT_ID = bytes2("mh");
uint256 public constant randaoCommitDelay = 128;
uint256 public constant randaoCommitExpiration = 24;
uint256 public constant minNumRequiredSignatures = 334;
uint256 public constant fiatShamirRequiredSignatures = 334;
uint256 public constant MAX_VALIDATORS = 1000;
uint256 public constant MAX_SOURCE_AGE_MS = 86_400_000;
uint256 public constant MAX_FUTURE_SOURCE_SKEW_MS = 120_000;
/* Errors */
error InvalidBitfield();
error InvalidBitfieldLength();
error InvalidBootstrap();
error InvalidCommitment();
error InvalidMMRLeaf();
error InvalidMMRLeafProof();
error InvalidMMRRootLength();
error InvalidSignature();
error InvalidSourceTimestamp();
error InvalidTicket();
error InvalidValidatorProof();
error InvalidValidatorProofLength();
error InvalidValidatorSet();
error ClientExpired();
error CommitmentNotRelevant();
error PrevRandaoAlreadyCaptured();
error PrevRandaoNotCaptured();
error StaleCommitment();
error WaitPeriodNotOver();
constructor(
bytes32 sourceDomain_,
uint256 destinationChainId_,
address destinationQueue_,
uint64 mmrStartBlock_,
uint64 initialBeefyBlock_,
uint64 initialSourceTimestampMs_,
ValidatorSet memory initialValidatorSet_,
ValidatorSet memory nextValidatorSet_
) {
uint256 nowMs = block.timestamp * 1000;
if (
sourceDomain_ == bytes32(0) || destinationChainId_ == 0 || destinationChainId_ != block.chainid
|| destinationQueue_ == address(0) || mmrStartBlock_ == 0 || initialBeefyBlock_ <= mmrStartBlock_
|| initialBeefyBlock_ > type(uint32).max || initialSourceTimestampMs_ == 0
|| uint256(initialSourceTimestampMs_) > nowMs + MAX_FUTURE_SOURCE_SKEW_MS
|| nowMs > uint256(initialSourceTimestampMs_) + MAX_SOURCE_AGE_MS
) {
revert InvalidBootstrap();
}
_validateValidatorSet(initialValidatorSet_);
_validateValidatorSet(nextValidatorSet_);
if (initialValidatorSet_.id >= type(uint64).max || nextValidatorSet_.id != initialValidatorSet_.id + 1) {
revert InvalidValidatorSet();
}
sourceDomain = sourceDomain_;
destinationChainId = destinationChainId_;
destinationQueue = destinationQueue_;
bridgeDomain = keccak256(
abi.encodePacked(
"vara/gear-eth-bridge-domain/v2", sourceDomain_, bytes32(destinationChainId_), destinationQueue_
)
);
mmrStartBlock = mmrStartBlock_;
latestBeefyBlock = initialBeefyBlock_;
lastAuthenticatedSourceTimestampMs = initialSourceTimestampMs_;
currentValidatorSet.id = initialValidatorSet_.id;
currentValidatorSet.length = initialValidatorSet_.length;
currentValidatorSet.root = initialValidatorSet_.root;
nextValidatorSet.id = nextValidatorSet_.id;
nextValidatorSet.length = nextValidatorSet_.length;
nextValidatorSet.root = nextValidatorSet_.root;
}
/* External Functions */
function isLive() external view returns (bool) {
return block.timestamp * 1000 <= uint256(lastAuthenticatedSourceTimestampMs) + MAX_SOURCE_AGE_MS;
}
/**
* @dev Begin submission of commitment
* @param commitment contains the commitment signed by the validators
* @param bitfield a bitfield claiming which validators have signed the commitment
* @param proof a proof that a single validator from currentValidatorSet has signed the commitment
*/
function submitInitial(Commitment calldata commitment, uint256[] calldata bitfield, ValidatorProof calldata proof)
external
{
_requireLive();
if (commitment.blockNumber <= latestBeefyBlock) {
revert StaleCommitment();
}
ValidatorSet storage vset = currentValidatorSet;
if (commitment.validatorSetID == nextValidatorSet.id) {
vset = nextValidatorSet;
} else if (commitment.validatorSetID != currentValidatorSet.id) {
revert InvalidCommitment();
}
// Check if merkle proof is valid based on the validatorSetRoot and if proof is included in bitfield
if (!isValidatorInSet(vset, proof.account, proof.index, proof.proof) || !Bitfield.isSet(bitfield, proof.index))
{
revert InvalidValidatorProof();
}
// Check if validatorSignature is correct, ie. check if it matches
// the signature of senderPublicKey on the commitmentHash
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
_verifySignature(commitmentHash, proof);
// For the initial submission, the supplied bitfield should claim that more than
// two thirds of the validator set have sign the commitment
if (
bitfield.length != Bitfield.containerLength(vset.length)
|| Bitfield.countSetBits(bitfield, vset.length) < computeQuorum(vset.length)
) {
revert InvalidBitfield();
}
// Validate that all padding bits (beyond vset.length) are zero
// This ensures the bitfield was created by createInitialBitfield or equivalent
Bitfield.validatePadding(bitfield, vset.length);
tickets[createTicketID(msg.sender, commitmentHash)] = Ticket({
blockNumber: uint64(block.number),
validatorSetLen: uint32(vset.length),
numRequiredSignatures: uint32(computeMaxRequiredSignatures(vset.length)),
prevRandao: 0,
bitfieldHash: keccak256(abi.encodePacked(bitfield))
});
emit NewTicket(msg.sender, commitment.blockNumber);
}
/**
* @dev Capture PREVRANDAO
* @param commitmentHash contains the commitmentHash signed by the validators
*/
function commitPrevRandao(bytes32 commitmentHash) external {
bytes32 ticketID = createTicketID(msg.sender, commitmentHash);
Ticket storage ticket = tickets[ticketID];
if (ticket.blockNumber == 0) {
revert InvalidTicket();
}
if (ticket.prevRandao != 0) {
revert PrevRandaoAlreadyCaptured();
}
// relayer must wait `randaoCommitDelay` blocks
if (block.number < ticket.blockNumber + randaoCommitDelay) {
revert WaitPeriodNotOver();
}
// relayer can capture within `randaoCommitExpiration` blocks
if (block.number > ticket.blockNumber + randaoCommitDelay + randaoCommitExpiration) {
delete tickets[ticketID];
emit TicketExpired();
return;
}
// Post-merge, the difficulty opcode now returns PREVRANDAO
ticket.prevRandao = block.prevrandao;
}
/**
* @dev Submit a commitment and leaf for final verification
* @param commitment contains the full commitment that was used for the commitmentHash
* @param bitfield claiming which validators have signed the commitment
* @param proofs a struct containing the data needed to verify all validator signatures
* @param leaf an MMR leaf provable using the MMR root in the commitment payload
* @param leafProof an MMR leaf proof
* @param leafProofOrder a bitfield describing the order of each item (left vs right)
*/
function submitFinal(
Commitment calldata commitment,
uint256[] calldata bitfield,
ValidatorProof[] calldata proofs,
MMRLeaf calldata leaf,
VaraBridgeMetadata.Snapshot calldata snapshot,
bytes32[] calldata leafProof,
uint256 leafProofOrder
) external {
_requireLive();
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
bytes32 ticketID = createTicketID(msg.sender, commitmentHash);
validateTicket(ticketID, commitment, bitfield);
bool is_next_session = false;
ValidatorSet storage vset = currentValidatorSet;
if (commitment.validatorSetID == nextValidatorSet.id) {
is_next_session = true;
vset = nextValidatorSet;
} else if (commitment.validatorSetID != currentValidatorSet.id) {
revert InvalidCommitment();
}
Bitfield.validatePadding(bitfield, vset.length);
verifyCommitment(commitmentHash, ticketID, bitfield, vset, proofs);
bytes32 newMMRRoot = ensureProvidesMMRRoot(commitment);
_acceptCommitment(commitment, newMMRRoot, leaf, snapshot, leafProof, leafProofOrder, is_next_session);
delete tickets[ticketID];
emit NewMMRRoot(newMMRRoot, commitment.blockNumber);
}
/**
* @dev Verify a leaf against an exact retained accepted root while the client is live.
* @param leafHash contains the merkle leaf to be verified
* @param proof contains simplified mmr proof
* @param proofOrder a bitfield describing the order of each item (left vs right)
*/
function verifyMMRLeafProof(
uint64 anchorBlock,
bytes32 anchorRoot,
bytes32 leafHash,
bytes32[] calldata proof,
uint256 proofOrder
) external view returns (bool) {
_requireLive();
return anchorRoot != bytes32(0) && acceptedAnchors[anchorBlock] == anchorRoot
&& MMRProof.verifyLeafProof(anchorRoot, leafHash, proof, proofOrder);
}
/// @dev Membership is independent of freshness; proof admission additionally requires a live client.
function isAcceptedAnchor(uint64 blockNumber, bytes32 root) external view returns (bool) {
return root != bytes32(0) && acceptedAnchors[blockNumber] == root;
}
/**
* @dev Helper to create an initial validator bitfield.
* @param bitsToSet contains indexes of all signed validators, should be deduplicated
* @param length of validator set
*/
function createInitialBitfield(uint256[] calldata bitsToSet, uint256 length)
external
pure
returns (uint256[] memory)
{
if (length == 0 || length > MAX_VALIDATORS || length < bitsToSet.length) {
revert InvalidBitfieldLength();
}
return Bitfield.createBitfield(bitsToSet, length);
}
/**
* @dev Compute the hash of a commitment
* @param commitment the commitment to hash
*/
function computeCommitmentHash(Commitment calldata commitment) external pure returns (bytes32) {
return keccak256(encodeCommitment(commitment));
}
/**
* @dev Helper to create a final bitfield, with subsampled validator selections
* @param commitmentHash contains the commitmentHash signed by the validators
* @param bitfield claiming which validators have signed the commitment
*/
function createFinalBitfield(bytes32 commitmentHash, uint256[] calldata bitfield)
external
view
returns (uint256[] memory)
{
Ticket storage ticket = tickets[createTicketID(msg.sender, commitmentHash)];
if (ticket.bitfieldHash != keccak256(abi.encodePacked(bitfield))) {
revert InvalidBitfield();
}
return Bitfield.subsample(ticket.prevRandao, bitfield, ticket.validatorSetLen, ticket.numRequiredSignatures);
}
/**
* @dev Helper to create a final bitfield with subsampled validator selections using the Fiat-Shamir approach
* @param commitment contains the full commitment that was used for the commitmentHash
* @param bitfield claiming which validators have signed the commitment
*/
function createFiatShamirFinalBitfield(Commitment calldata commitment, uint256[] calldata bitfield)
external
view
returns (uint256[] memory)
{
ValidatorSet storage vset = currentValidatorSet;
if (commitment.validatorSetID == nextValidatorSet.id) {
vset = nextValidatorSet;
} else if (commitment.validatorSetID != currentValidatorSet.id) {
revert InvalidCommitment();
}
if (
bitfield.length != Bitfield.containerLength(vset.length)
|| Bitfield.countSetBits(bitfield, vset.length) < computeQuorum(vset.length)
) {
revert InvalidBitfield();
}
Bitfield.validatePadding(bitfield, vset.length);
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
return fiatShamirFinalBitfield(commitmentHash, bitfield, vset);
}
/**
* @dev Submit a commitment and leaf using the Fiat-Shamir approach
* @param commitment contains the full commitment that was used for the commitmentHash
* @param bitfield claiming which validators have signed the commitment
* @param proofs a struct containing the data needed to verify all validator signatures
* @param leaf an MMR leaf provable using the MMR root in the commitment payload
* @param leafProof an MMR leaf proof
* @param leafProofOrder a bitfield describing the order of each item (left vs right)
*/
function submitFiatShamir(
Commitment calldata commitment,
uint256[] calldata bitfield,
ValidatorProof[] calldata proofs,
MMRLeaf calldata leaf,
VaraBridgeMetadata.Snapshot calldata snapshot,
bytes32[] calldata leafProof,
uint256 leafProofOrder
) external {
_requireLive();
if (commitment.blockNumber <= latestBeefyBlock) {
revert StaleCommitment();
}
bool is_next_session = false;
ValidatorSet storage vset = currentValidatorSet;
if (commitment.validatorSetID == nextValidatorSet.id) {
is_next_session = true;
vset = nextValidatorSet;
} else if (commitment.validatorSetID != currentValidatorSet.id) {
revert InvalidCommitment();
}
if (
bitfield.length != Bitfield.containerLength(vset.length)
|| Bitfield.countSetBits(bitfield, vset.length) < computeQuorum(vset.length)
) {
revert InvalidBitfield();
}
Bitfield.validatePadding(bitfield, vset.length);
bytes32 newMMRRoot = ensureProvidesMMRRoot(commitment);
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
verifyFiatShamirCommitment(commitmentHash, bitfield, vset, proofs);
_acceptCommitment(commitment, newMMRRoot, leaf, snapshot, leafProof, leafProofOrder, is_next_session);
emit NewMMRRoot(newMMRRoot, commitment.blockNumber);
}
/* Internal Functions */
// Protocol-specific tickets, sampling and signature counts are checked before this shared tail.
function _acceptCommitment(
Commitment calldata commitment,
bytes32 newMMRRoot,
MMRLeaf calldata leaf,
VaraBridgeMetadata.Snapshot calldata snapshot,
bytes32[] calldata leafProof,
uint256 leafProofOrder,
bool isNextSession
) internal {
_validateAuthenticatedLeaf(commitment, newMMRRoot, leaf, snapshot, leafProof, leafProofOrder);
if (isNextSession) {
if (leaf.nextAuthoritySetID <= nextValidatorSet.id) {
revert InvalidMMRLeaf();
}
currentValidatorSet = nextValidatorSet;
nextValidatorSet.id = leaf.nextAuthoritySetID;
nextValidatorSet.length = leaf.nextAuthoritySetLen;
nextValidatorSet.root = leaf.nextAuthoritySetRoot;
} else if (
leaf.nextAuthoritySetID != nextValidatorSet.id || leaf.nextAuthoritySetLen != nextValidatorSet.length
|| leaf.nextAuthoritySetRoot != nextValidatorSet.root
) {
revert InvalidMMRLeaf();
}
_recordAcceptedAnchor(commitment.blockNumber, newMMRRoot);
latestMMRRoot = newMMRRoot;
latestBeefyBlock = commitment.blockNumber;
lastAuthenticatedSourceTimestampMs = snapshot.sourceTimestampMs;
}
function _recordAcceptedAnchor(uint64 blockNumber, bytes32 root) internal {
if (blockNumber <= latestBeefyBlock) revert StaleCommitment();
if (root == bytes32(0)) revert InvalidCommitment();
delete acceptedAnchors[acceptedAnchorBlocks[nextAcceptedAnchor]];
acceptedAnchorBlocks[nextAcceptedAnchor] = blockNumber;
acceptedAnchors[blockNumber] = root;
nextAcceptedAnchor = uint8((uint256(nextAcceptedAnchor) + 1) % 64);
}
function _validateValidatorSet(ValidatorSet memory validatorSet) internal pure {
if (
validatorSet.length == 0 || validatorSet.length > MAX_VALIDATORS || validatorSet.root == bytes32(0)
|| validatorSet.id > type(uint64).max
) {
revert InvalidValidatorSet();
}
}
function _requireLive() internal view {
if (block.timestamp * 1000 > uint256(lastAuthenticatedSourceTimestampMs) + MAX_SOURCE_AGE_MS) {
revert ClientExpired();
}
}
function _validateAuthenticatedLeaf(
Commitment calldata commitment,
bytes32 newMMRRoot,
MMRLeaf calldata leaf,
VaraBridgeMetadata.Snapshot calldata snapshot,
bytes32[] calldata leafProof,
uint256 leafProofOrder
) internal view {
if (
newMMRRoot == bytes32(0) || leaf.version != 0 || commitment.blockNumber == 0
|| leaf.parentNumber != commitment.blockNumber - 1
) {
revert InvalidMMRLeaf();
}
if (
leaf.nextAuthoritySetLen == 0 || leaf.nextAuthoritySetLen > MAX_VALIDATORS
|| leaf.nextAuthoritySetRoot == bytes32(0)
) {
revert InvalidValidatorSet();
}
if (snapshot.bridgeDomain != bridgeDomain) {
revert InvalidSourceTimestamp();
}
if (
snapshot.sourceTimestampMs < lastAuthenticatedSourceTimestampMs
|| uint256(snapshot.sourceTimestampMs) > block.timestamp * 1000 + MAX_FUTURE_SOURCE_SKEW_MS
) {
revert InvalidSourceTimestamp();
}
if (VaraBridgeMetadata.hash(snapshot) != leaf.parachainHeadsRoot) {
revert InvalidMMRLeaf();
}
if (!MMRProof.verifyLeafProof(newMMRRoot, keccak256(encodeMMRLeaf(leaf)), leafProof, leafProofOrder)) {
revert InvalidMMRLeafProof();
}
}
function createTicketID(address account, bytes32 commitmentHash) internal pure returns (bytes32 value) {
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
/* reviewed: ... */
mstore(0x00, account)
mstore(0x20, commitmentHash)
value := keccak256(0x0, 0x40)
}
}
/**
* @dev Calculates 2/3 majority required for quorum for a given number of validators.
* @param numValidators The number of validators in the validator set.
*/
function computeQuorum(uint256 numValidators) internal pure returns (uint256) {
return numValidators - (numValidators - 1) / 3;
}
/**
* @dev Authenticate native quorum for tiny sets; larger sets retain the 1/3 + 1 sampling cap.
* @param numValidators The number of validators in the validator set.
*/
function computeMaxRequiredSignatures(uint256 numValidators) internal pure returns (uint256) {
return numValidators <= 3 ? computeQuorum(numValidators) : numValidators / 3 + 1;
}
/**
* @dev Verify commitment using the supplied signature proofs
*/
function verifyCommitment(
bytes32 commitmentHash,
bytes32 ticketID,
uint256[] calldata bitfield,
ValidatorSet storage vset,
ValidatorProof[] calldata proofs
) internal view {
Ticket storage ticket = tickets[ticketID];
// Verify that enough signature proofs have been supplied
uint256 numRequiredSignatures = ticket.numRequiredSignatures;
if (proofs.length != numRequiredSignatures) {
revert InvalidValidatorProofLength();
}
// Generate final bitfield indicating which validators need to be included in the proofs.
uint256[] memory finalbitfield =
Bitfield.subsample(ticket.prevRandao, bitfield, vset.length, numRequiredSignatures);
_requireDistinctAccounts(proofs);
for (uint256 i = 0; i < proofs.length; i++) {
ValidatorProof calldata proof = proofs[i];
// Check that validator is actually in a validator set
if (!isValidatorInSet(vset, proof.account, proof.index, proof.proof)) {
revert InvalidValidatorProof();
}
// Check that validator is in bitfield
if (!Bitfield.isSet(finalbitfield, proof.index)) {
revert InvalidValidatorProof();
}
// Check that validator signed the commitment
_verifySignature(commitmentHash, proof);
// Ensure no validator can appear more than once in bitfield
Bitfield.unset(finalbitfield, proof.index);
}
}
/**
* @dev Verify commitment with the sampled signatures using the Fiat-Shamir hash
*/
function verifyFiatShamirCommitment(
bytes32 commitmentHash,
uint256[] calldata bitfield,
ValidatorSet storage vset,
ValidatorProof[] calldata proofs
) internal view {
uint256 requiredSignatures = computeMaxRequiredSignatures(vset.length);
if (proofs.length != requiredSignatures) {
revert InvalidValidatorProofLength();
}
uint256[] memory finalbitfield = fiatShamirFinalBitfield(commitmentHash, bitfield, vset);
_requireDistinctAccounts(proofs);
for (uint256 i = 0; i < proofs.length; i++) {
ValidatorProof calldata proof = proofs[i];
// Check that validator is in bitfield
if (!Bitfield.isSet(finalbitfield, proof.index)) {
revert InvalidValidatorProof();
}
// Check that validator is actually in a validator set
if (!isValidatorInSet(vset, proof.account, proof.index, proof.proof)) {
revert InvalidValidatorProof();
}
// Check that validator signed the commitment
_verifySignature(commitmentHash, proof);
// Ensure no validator can appear more than once in bitfield
Bitfield.unset(finalbitfield, proof.index);
}
}
function _verifySignature(bytes32 commitmentHash, ValidatorProof calldata proof) internal pure {
if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) {
revert InvalidSignature();
}
}
// Reject repeated EVM keys even if an authenticated root contains them at different positions.
function _requireDistinctAccounts(ValidatorProof[] calldata proofs) private pure {
uint256 capacity = 1;
while (capacity < proofs.length * 2) capacity <<= 1;
address[] memory seen = new address[](capacity);
for (uint256 i; i < proofs.length; i++) {
address account = proofs[i].account;
if (account == address(0)) {
revert InvalidValidatorProof();
}
uint256 slot = uint256(keccak256(abi.encodePacked(account))) & (capacity - 1);
while (seen[slot] != address(0)) {
if (seen[slot] == account) {
revert InvalidValidatorProof();
}
slot = (slot + 1) & (capacity - 1);
}
seen[slot] = account;
}
}
function createFiatShamirHash(bytes32 commitmentHash, bytes32 bitFieldHash, ValidatorSet storage vset)
internal
view
returns (bytes32)
{
return sha256(
bytes.concat(
FIAT_SHAMIR_DOMAIN_ID,
sha256(
bytes.concat(
commitmentHash,
bitFieldHash,
vset.root,
bytes32(uint256(vset.id)),
bytes32(uint256(vset.length))
)
)
)
);
}
/**
* @dev Helper to create a final bitfield with subsampled validator selections using the Fiat-Shamir approach
* @param commitmentHash the hash of the full commitment that was used for the commitmentHash
* @param bitfield claiming which validators have signed the commitment
* @param vset the validator set state
*/
function fiatShamirFinalBitfield(bytes32 commitmentHash, uint256[] calldata bitfield, ValidatorSet storage vset)
internal
view
returns (uint256[] memory)
{
bytes32 bitFieldHash = keccak256(abi.encodePacked(bitfield));
bytes32 fiatShamirHash = createFiatShamirHash(commitmentHash, bitFieldHash, vset);
uint256 requiredSignatures = computeMaxRequiredSignatures(vset.length);
return Bitfield.subsample(uint256(fiatShamirHash), bitfield, vset.length, requiredSignatures);
}
// Ensure that the commitment provides exactly one nonzero 32-byte MMR root.
function ensureProvidesMMRRoot(Commitment calldata commitment) internal pure returns (bytes32 root) {
bool found;
for (uint256 i = 0; i < commitment.payload.length; i++) {
if (commitment.payload[i].payloadID != MMR_ROOT_ID) continue;
if (found) {
revert InvalidCommitment();
}
found = true;
if (commitment.payload[i].data.length != 32) {
revert InvalidMMRRootLength();
}
root = bytes32(commitment.payload[i].data);
}
if (!found) {
revert CommitmentNotRelevant();
}
if (root == bytes32(0)) {
revert InvalidCommitment();
}
}
function encodeCommitment(Commitment calldata commitment) internal pure returns (bytes memory) {
return bytes.concat(
encodeCommitmentPayload(commitment.payload),
ScaleCodec.encodeU32(commitment.blockNumber),
ScaleCodec.encodeU64(commitment.validatorSetID)
);
}
function encodeCommitmentPayload(PayloadItem[] calldata items) internal pure returns (bytes memory) {
bytes memory payload = ScaleCodec.checkedEncodeCompactU32(items.length);
for (uint256 i = 0; i < items.length; i++) {
payload = bytes.concat(
payload, items[i].payloadID, ScaleCodec.checkedEncodeCompactU32(items[i].data.length), items[i].data
);
}
return payload;
}
function encodeMMRLeaf(MMRLeaf calldata leaf) internal pure returns (bytes memory) {
return VaraBridgeMetadata.encodeMMRLeaf(
leaf.version,
leaf.parentNumber,
leaf.parentHash,
leaf.nextAuthoritySetID,
leaf.nextAuthoritySetLen,
leaf.nextAuthoritySetRoot,
leaf.parachainHeadsRoot
);
}
/**
* @dev Checks if a validators address is a member of the merkle tree
* @param vset The validator set
* @param account The address of the validator to check for inclusion in `vset`.
* @param index The leaf index of the account in the merkle tree of validator set addresses.
* @param proof Merkle proof required for validation of the address
* @return true if the validator is in the set
*/
function isValidatorInSet(ValidatorSet storage vset, address account, uint256 index, bytes32[] calldata proof)
internal
view
returns (bool)
{
bytes32 hashedLeaf = keccak256(abi.encodePacked(account));
return SubstrateMerkleProof.verify(vset.root, hashedLeaf, index, vset.length, proof);
}
/**
* @dev Basic validation of a ticket for submitFinal
*/
function validateTicket(bytes32 ticketID, Commitment calldata commitment, uint256[] calldata bitfield)
internal
view
{
Ticket storage ticket = tickets[ticketID];
if (ticket.blockNumber == 0) {
// submitInitial hasn't been called yet
revert InvalidTicket();
}
if (ticket.prevRandao == 0) {
// commitPrevRandao hasn't been called yet
revert PrevRandaoNotCaptured();
}
if (commitment.blockNumber <= latestBeefyBlock) {
// ticket is obsolete
revert StaleCommitment();
}
if (ticket.bitfieldHash != keccak256(abi.encodePacked(bitfield))) {
// The provided claims bitfield isn't the same one that was
// passed to submitInitial
revert InvalidBitfield();
}
}
}
src/beefy/VaraBridgeMetadata.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.37;
import {ScaleCodec} from "./utils/ScaleCodec.sol";
library VaraBridgeMetadata {
error InvalidBridgeMetadata();
struct Snapshot {
uint8 version;
bytes32 bridgeDomain;
uint64 sourceTimestampMs;
bool initialized;
uint64 queueId;
bytes32 queueRoot;
}
uint8 internal constant VERSION = 2;
bytes4 internal constant MAGIC = bytes4("vara");
// SCALE: u8 + u32 + H256 + u64 + u32 + H256 + H256 = 113 bytes.
function encodeMMRLeaf(
uint8 version,
uint32 parentNumber,
bytes32 parentHash,
uint64 nextAuthoritySetID,
uint32 nextAuthoritySetLen,
bytes32 nextAuthoritySetRoot,
bytes32 extraRoot
) internal pure returns (bytes memory) {
return bytes.concat(
ScaleCodec.encodeU8(version),
ScaleCodec.encodeU32(parentNumber),
parentHash,
ScaleCodec.encodeU64(nextAuthoritySetID),
ScaleCodec.encodeU32(nextAuthoritySetLen),
nextAuthoritySetRoot,
extraRoot
);
}
function hash(Snapshot memory snapshot) internal pure returns (bytes32) {
if (
snapshot.version != VERSION
|| (!snapshot.initialized && (snapshot.queueId != 0 || snapshot.queueRoot != bytes32(0)))
) {
revert InvalidBridgeMetadata();
}
return keccak256(
bytes.concat(
ScaleCodec.encodeU8(snapshot.version),
MAGIC,
snapshot.bridgeDomain,
ScaleCodec.encodeU64(snapshot.sourceTimestampMs),
ScaleCodec.encodeU8(snapshot.initialized ? 1 : 0),
ScaleCodec.encodeU64(snapshot.queueId),
snapshot.queueRoot
)
);
}
}
src/beefy/utils/Bitfield.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
import {Bits} from "./Bits.sol";
library Bitfield {
using Bits for uint256;
error InvalidSamplingParams();
error InvalidBitfieldPadding();
error InvalidBitfieldIndex();
/**
* @dev Constants used to efficiently calculate the hamming weight of a bitfield. See
* https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation for an explanation of those constants.
*/
uint256 internal constant M1 = 0x5555555555555555555555555555555555555555555555555555555555555555;
uint256 internal constant M2 = 0x3333333333333333333333333333333333333333333333333333333333333333;
uint256 internal constant M4 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f;
uint256 internal constant M8 = 0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff;
uint256 internal constant M16 = 0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff;
uint256 internal constant M32 = 0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff;
uint256 internal constant M64 = 0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff;
uint256 internal constant M128 = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
uint256 internal constant ONE = uint256(1);
/**
* @dev Core subsampling algorithm. Draws a random number, derives an index in the bitfield,
* and sets the bit if it is in the `priorBitfield` and not yet set. Repeats that `n` times.
* @param seed Source of randomness for selecting validator signatures.
* @param priorBitfield Bitfield indicating which validators claim to have signed the commitment.
* @param priorBitfieldSize Number of bits in priorBitfield Must be <= priorBitfield.length * 256.
* @param n Number of unique bits in priorBitfield that must be set in the output.
* Must be <= number of set bits in priorBitfield.
*/
function subsample(uint256 seed, uint256[] memory priorBitfield, uint256 priorBitfieldSize, uint256 n)
internal
pure
returns (uint256[] memory outputBitfield)
{
if (
priorBitfield.length != Bitfield.containerLength(priorBitfieldSize)
|| n > countSetBits(priorBitfield, priorBitfieldSize)
) {
revert InvalidSamplingParams();
}
outputBitfield = new uint256[](priorBitfield.length);
uint256 found = 0;
for (uint256 i = 0; found < n;) {
uint256 index = makeIndex(seed, i, priorBitfieldSize);
// require randomly selected bit to be set in priorBitfield and not yet set in bitfield
if (!isSet(priorBitfield, index) || isSet(outputBitfield, index)) {
unchecked {
i++;
}
continue;
}
set(outputBitfield, index);
unchecked {
found++;
i++;
}
}
}
/**
* @dev Helper to create a bitfield.
*/
function createBitfield(uint256[] calldata bitsToSet, uint256 length)
internal
pure
returns (uint256[] memory bitfield)
{
bitfield = new uint256[](containerLength(length));
for (uint256 i = 0; i < bitsToSet.length; i++) {
if (bitsToSet[i] >= length || isSet(bitfield, bitsToSet[i])) {
revert InvalidBitfieldIndex();
}
set(bitfield, bitsToSet[i]);
}
return bitfield;
}
/**
* @notice Calculates the number of set bits in the first `maxBits` bits of the bitfield.
*
* @dev Example usage:
* If a bitfield has bits set at positions [0, 5, 10, 256, 300]:
* - countSetBits(bitfield, 11) returns 3 (bits 0, 5, 10)
* - countSetBits(bitfield, 257) returns 4 (bits 0, 5, 10, 256)
* - countSetBits(bitfield, 1000) returns 5 (all bits)
*
* @param self The bitfield to count bits in
* @param maxBits The maximum number of bits to count (counting from bit 0)
* @return count The number of set bits in the first `maxBits` positions
*/
function countSetBits(uint256[] memory self, uint256 maxBits) internal pure returns (uint256) {
if (maxBits == 0 || self.length == 0) {
return 0;
}
unchecked {
uint256 count = 0;
uint256 fullElements = maxBits / 256;
uint256 remainingBits = maxBits % 256;
// Count bits in full 256-bit elements
for (uint256 i = 0; i < fullElements && i < self.length; i++) {
uint256 x = self[i];
x = (x & M1) + ((x >> 1) & M1); //put count of each 2 bits into those 2 bits
x = (x & M2) + ((x >> 2) & M2); //put count of each 4 bits into those 4 bits
x = (x & M4) + ((x >> 4) & M4); //put count of each 8 bits into those 8 bits
x = (x & M8) + ((x >> 8) & M8); //put count of each 16 bits into those 16 bits
x = (x & M16) + ((x >> 16) & M16); //put count of each 32 bits into those 32 bits
x = (x & M32) + ((x >> 32) & M32); //put count of each 64 bits into those 64 bits
x = (x & M64) + ((x >> 64) & M64); //put count of each 128 bits into those 128 bits
x = (x & M128) + ((x >> 128) & M128); //put count of each 256 bits into those 256 bits
count += x;
}
// Count bits in the partial element (if any)
if (remainingBits > 0 && fullElements < self.length) {
uint256 mask = (ONE << remainingBits) - 1;
uint256 x = self[fullElements] & mask;
x = (x & M1) + ((x >> 1) & M1);
x = (x & M2) + ((x >> 2) & M2);
x = (x & M4) + ((x >> 4) & M4);
x = (x & M8) + ((x >> 8) & M8);
x = (x & M16) + ((x >> 16) & M16);
x = (x & M32) + ((x >> 32) & M32);
x = (x & M64) + ((x >> 64) & M64);
x = (x & M128) + ((x >> 128) & M128);
count += x;
}
return count;
}
}
function isSet(uint256[] memory self, uint256 index) internal pure returns (bool) {
uint256 element = index >> 8;
// forge-lint: disable-next-line(unsafe-typecast)
return self[element].bit(uint8(index)) == 1;
}
function set(uint256[] memory self, uint256 index) internal pure {
uint256 element = index >> 8;
// forge-lint: disable-next-line(unsafe-typecast)
self[element] = self[element].setBit(uint8(index));
}
function unset(uint256[] memory self, uint256 index) internal pure {
uint256 element = index >> 8;
// forge-lint: disable-next-line(unsafe-typecast)
self[element] = self[element].clearBit(uint8(index));
}
function makeIndex(uint256 seed, uint256 iteration, uint256 length) internal pure returns (uint256 index) {
// Handle case where length is 0 to prevent infinite loop in subsample
if (length == 0) {
return 0;
}
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
/* reviewed: ... */
mstore(0x00, seed)
mstore(0x20, iteration)
index := mod(keccak256(0x00, 0x40), length)
}
}
// Calculate length of uint256 bitfield array based on rounding up to number of uint256 needed
function containerLength(uint256 bitfieldSize) internal pure returns (uint256) {
return (bitfieldSize + 255) / 256;
}
/**
* @dev Validate that all padding bits in the bitfield (beyond length) are zero.
* @param bitfield The bitfield to validate
* @param length The number of valid bits (padding starts after this)
*/
function validatePadding(uint256[] memory bitfield, uint256 length) internal pure {
uint256 containerLen = containerLength(length);
if (containerLen == 0 || bitfield.length == 0) {
return;
}
// Check if there are padding bits in the last element
uint256 validBitsInLastElement = length % 256;
if (validBitsInLastElement == 0) {
// All bits in last element are valid, no padding
return;
}
// Create a mask for padding bits: all bits from validBitsInLastElement to 255
uint256 paddingMask = type(uint256).max << validBitsInLastElement;
uint256 lastElement = bitfield[containerLen - 1];
if ((lastElement & paddingMask) != 0) {
revert InvalidBitfieldPadding();
}
}
}
src/beefy/utils/Bits.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Code from https://github.com/ethereum/solidity-examples
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
library Bits {
uint256 internal constant ONE = uint256(1);
// Sets the bit at the given 'index' in 'self' to '1'.
// Returns the modified value.
function setBit(uint256 self, uint8 index) internal pure returns (uint256) {
return self | (ONE << index);
}
// Sets the bit at the given 'index' in 'self' to '0'.
// Returns the modified value.
function clearBit(uint256 self, uint8 index) internal pure returns (uint256) {
return self & ~(ONE << index);
}
// Get the value of the bit at the given 'index' in 'self'.
function bit(uint256 self, uint8 index) internal pure returns (uint8) {
return uint8((self >> index) & 1);
}
}
src/beefy/utils/MMRProof.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
library MMRProof {
error ProofSizeExceeded();
uint256 internal constant MAXIMUM_PROOF_SIZE = 256;
/**
* @dev Verify inclusion of a leaf in an MMR
* @param root MMR root hash
* @param leafHash leaf hash
* @param proof an array of hashes
* @param proofOrder a bitfield describing the order of each item (left vs right)
*/
function verifyLeafProof(bytes32 root, bytes32 leafHash, bytes32[] calldata proof, uint256 proofOrder)
internal
pure
returns (bool)
{
if (proof.length > MAXIMUM_PROOF_SIZE) {
revert ProofSizeExceeded();
}
if (proof.length < MAXIMUM_PROOF_SIZE && (proofOrder >> proof.length) != 0) {
return false;
}
bytes32 acc = leafHash;
for (uint256 i = 0; i < proof.length; i++) {
acc = hashPairs(acc, proof[i], (proofOrder >> i) & 1);
}
return root == acc;
}
function hashPairs(bytes32 x, bytes32 y, uint256 order) internal pure returns (bytes32 value) {
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
/* reviewed: ... */
switch order
case 0 {
mstore(0x00, x)
mstore(0x20, y)
}
default {
mstore(0x00, y)
mstore(0x20, x)
}
value := keccak256(0x0, 0x40)
}
}
}
src/beefy/utils/ScaleCodec.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
library ScaleCodec {
error UnsupportedCompactEncoding();
// Sources:
// * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528
// * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
function reverse64(uint64 input) internal pure returns (uint64 v) {
v = input;
// swap bytes
v = ((v & 0xFF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v & 0xFFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = (v >> 32) | (v << 32);
}
function reverse32(uint32 input) internal pure returns (uint32 v) {
v = input;
// swap bytes
v = ((v & 0xFF00FF00) >> 8) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = (v >> 16) | (v << 16);
}
function reverse16(uint16 input) internal pure returns (uint16 v) {
v = input;
// swap bytes
v = (v >> 8) | (v << 8);
}
function encodeU64(uint64 input) internal pure returns (bytes8) {
return bytes8(reverse64(input));
}
function encodeU32(uint32 input) internal pure returns (bytes4) {
return bytes4(reverse32(input));
}
function encodeU8(uint8 input) internal pure returns (bytes1) {
return bytes1(input);
}
// Supports compact encoding of integers in [0, uint32.MAX]
function encodeCompactU32(uint32 value) internal pure returns (bytes memory) {
if (value <= 2 ** 6 - 1) {
// add single byte flag
// forge-lint: disable-next-line(unsafe-typecast)
return abi.encodePacked(uint8(value << 2));
} else if (value <= 2 ** 14 - 1) {
// add two byte flag and create little endian encoding
return abi.encodePacked(ScaleCodec.reverse16(uint16(((value << 2) + 1))));
} else if (value <= 2 ** 30 - 1) {
// add four byte flag and create little endian encoding
return abi.encodePacked(ScaleCodec.reverse32(uint32((value << 2)) + 2));
} else {
return abi.encodePacked(uint8(3), ScaleCodec.reverse32(value));
}
}
function checkedEncodeCompactU32(uint256 value) internal pure returns (bytes memory) {
if (value > type(uint32).max) {
revert UnsupportedCompactEncoding();
}
// forge-lint: disable-next-line(unsafe-typecast)
return encodeCompactU32(uint32(value));
}
}
src/beefy/utils/SubstrateMerkleProof.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Modified for the Vara bridge; upstream provenance and licenses: ethereum/README.md.
pragma solidity ^0.8.37;
// Verify binary-merkle-tree proofs, promoting lone trailing nodes unchanged on odd layers.
// https://github.com/paritytech/polkadot-sdk/blob/48a8a0689248e4fba3e6615e0c8c9c83f9df3343/substrate/utils/binary-merkle-tree/src/lib.rs#L359
library SubstrateMerkleProof {
/**
* @notice Verify that a specific leaf element is part of the Merkle Tree at a specific position in the tree
*
* The tree would have been constructed using
* https://docs.rs/binary-merkle-tree/latest/binary_merkle_tree/fn.merkle_root.html
*
* This implementation adapted from
* https://docs.rs/binary-merkle-tree/latest/binary_merkle_tree/fn.verify_proof.html
*
* @param root the root of the merkle tree
* @param leaf the leaf which needs to be proven
* @param position the position of the leaf, index starting with 0
* @param width the width or number of leaves in the tree
* @param proof the array of proofs to help verify the leaf's membership, ordered from leaf to root
* @return a boolean value representing the success or failure of the operation
*/
function verify(bytes32 root, bytes32 leaf, uint256 position, uint256 width, bytes32[] calldata proof)
internal
pure
returns (bool)
{
(bool valid, bytes32 node) = computeRoot(leaf, position, width, proof);
return valid && root == node;
}
/// @dev Consume exactly the canonical siblings for (position, width); invalid proofs return (false, 0).
function computeRoot(bytes32 leaf, uint256 position, uint256 width, bytes32[] calldata proof)
internal
pure
returns (bool valid, bytes32 node)
{
if (position >= width) {
return (false, bytes32(0));
}
node = leaf;
uint256 proofIndex;
unchecked {
while (width > 1) {
if ((position & 1) == 1) {
if (proofIndex >= proof.length) {
return (false, bytes32(0));
}
node = efficientHash(proof[proofIndex++], node);
} else if (position + 1 < width) {
if (proofIndex >= proof.length) {
return (false, bytes32(0));
}
node = efficientHash(node, proof[proofIndex++]);
}
position >>= 1;
width = (width >> 1) + (width & 1);
}
}
if (proofIndex != proof.length) {
return (false, bytes32(0));
}
return (true, node);
}
function efficientHash(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
// forge-lint: disable-next-item(inline-assembly)
assembly ("memory-safe") {
/* reviewed: ... */
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
src/interfaces/IQueueProgressVerifier.sol
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
pragma solidity ^0.8.37;
/// @dev Optional verifier capability for advancing a queue through an authenticated empty snapshot.
interface IQueueProgressVerifier {
function safeVerifyEmptyQueueProgress(uint256 sourceBlock, bytes calldata proof) external view returns (bool);
}
src/interfaces/IVerifier.sol
// Copyright (C) Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
pragma solidity ^0.8.37;
/**
* @dev Interface for the Verifier contract.
*/
interface IVerifier {
/**
* @dev Authenticates a Vara queue root with a BEEFY-backed MMR proof.
* @param sourceBlock Original source block number, bounded to uint32.
* @param merkleRoot Queue root at the source block.
* @param proof Canonical v2 queue proof envelope.
* @return success `true` if proof is valid, `false` otherwise, including malformed proofs.
*/
function safeVerifyProof(uint256 sourceBlock, bytes32 merkleRoot, bytes calldata proof)
external
view
returns (bool success);
}
Compiler settingsShow
{
"debug": {
"revertStrings": "strip"
},
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "osaka",
"remappings": [
"@openzeppelin-contracts-5.7.0/=dependencies/@openzeppelin-contracts-5.7.0/",
"@openzeppelin-contracts-upgradeable-5.7.0/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
"forge-std-1.17.0/=dependencies/forge-std-1.17.0/",
"openzeppelin-foundry-upgrades-0.4.3/=dependencies/openzeppelin-foundry-upgrades-0.4.3/",
"forge-std/=dependencies/forge-std-1.17.0/src/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.7.0/",
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.7.0/",
"openzeppelin-foundry-upgrades/=dependencies/openzeppelin-foundry-upgrades-0.4.3/src/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.