Verified contractExactApache-2.0
BeefyClient
Address0xbcbebc20a0fdf9efd53b5852a71869b0cf25283f
- Balance
0 ETH
- Transactions
356
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 20,000 runs
- EVM version
- osaka
- Via IR
- yes
- License
- Apache-2.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,298,718
- Creation transaction
- 0xa0c89649a7…e8b2fcf6e4
9 files
- src/BeefyClient.solmain34.74 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol12.17 KB
- src/utils/Bitfield.sol10.14 KB
- src/utils/Bits.sol4.48 KB
- src/utils/MMRProof.sol1.48 KB
- src/utils/Math.sol3.41 KB
- src/utils/ScaleCodec.sol7.71 KB
- src/utils/SubstrateMerkleProof.sol5.09 KB
- src/utils/Uint16Array.sol4.22 KB
src/BeefyClient.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
import {ECDSA} from "openzeppelin/utils/cryptography/ECDSA.sol";
import {SubstrateMerkleProof} from "./utils/SubstrateMerkleProof.sol";
import {Bitfield} from "./utils/Bitfield.sol";
import {Uint16Array, createUint16Array} from "./utils/Uint16Array.sol";
import {Math} from "./utils/Math.sol";
import {MMRProof} from "./utils/MMRProof.sol";
import {ScaleCodec} from "./utils/ScaleCodec.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 {
using Math for uint16;
using Math for uint256;
/* 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;
}
/**
* @dev The ValidatorSetState describes a BEEFY validator set along with signature usage counters
*/
struct ValidatorSetState {
// Identifier for the set
uint128 id;
// Number of validators in the set
uint128 length;
// Merkle root of BEEFY validator addresses
bytes32 root;
// Number of times a validator signature has been used
Uint16Array usageCounters;
}
/* State */
/// @dev The latest verified MMR root
bytes32 public latestMMRRoot;
/// @dev The block number in the relay chain in which the latest MMR root was emitted
uint64 public latestBeefyBlock;
/// @dev State of the current validator set
ValidatorSetState public currentValidatorSet;
/// @dev State of the next validator set
ValidatorSetState 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");
/**
* @dev Minimum delay in number of blocks that a relayer must wait between calling
* submitInitial and commitPrevRandao. In production this should be set to MAX_SEED_LOOKAHEAD:
* https://eth2book.info/altair/part3/config/preset#max_seed_lookahead
*/
uint256 public immutable randaoCommitDelay;
/**
* @dev after randaoCommitDelay is reached, relayer must
* call commitPrevRandao within this number of blocks.
* Without this expiration, relayers can roll the dice infinitely to get the subsampling
* they desire.
*/
uint256 public immutable randaoCommitExpiration;
/**
* @dev The lower bound on the number of signatures required to validate a new commitment. Note
* that the final number of signatures is calculated dynamically with Randao randomness.
*/
uint256 public immutable minNumRequiredSignatures;
/**
* @dev The signatures required to validate a new commitment using Fiat-Shamir transform. Note
* that Fiat-shamir comes from the assumption on the hash-power of adversary
* and its not a crypto-economic argument.
*/
uint256 public immutable fiatShamirRequiredSignatures;
/* Errors */
error InvalidBitfield();
error InvalidBitfieldLength();
error InvalidCommitment();
error InvalidMMRLeaf();
error InvalidMMRLeafProof();
error InvalidMMRRootLength();
error InvalidSignature();
error InvalidTicket();
error InvalidValidatorProof();
error InvalidValidatorProofLength();
error CommitmentNotRelevant();
error PrevRandaoAlreadyCaptured();
error PrevRandaoNotCaptured();
error StaleCommitment();
error WaitPeriodNotOver();
constructor(
uint256 _randaoCommitDelay,
uint256 _randaoCommitExpiration,
uint256 _minNumRequiredSignatures,
uint256 _fiatShamirRequiredSignatures,
uint64 _initialBeefyBlock,
ValidatorSet memory _initialValidatorSet,
ValidatorSet memory _nextValidatorSet
) {
if (_nextValidatorSet.id != _initialValidatorSet.id + 1) {
revert("invalid-constructor-params");
}
randaoCommitDelay = _randaoCommitDelay;
randaoCommitExpiration = _randaoCommitExpiration;
minNumRequiredSignatures = _minNumRequiredSignatures;
fiatShamirRequiredSignatures = _fiatShamirRequiredSignatures;
latestBeefyBlock = _initialBeefyBlock;
currentValidatorSet.id = _initialValidatorSet.id;
currentValidatorSet.length = _initialValidatorSet.length;
currentValidatorSet.root = _initialValidatorSet.root;
currentValidatorSet.usageCounters = createUint16Array(currentValidatorSet.length);
nextValidatorSet.id = _nextValidatorSet.id;
nextValidatorSet.length = _nextValidatorSet.length;
nextValidatorSet.root = _nextValidatorSet.root;
nextValidatorSet.usageCounters = createUint16Array(nextValidatorSet.length);
}
/* External Functions */
/**
* @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 {
if (commitment.blockNumber <= latestBeefyBlock) {
revert StaleCommitment();
}
ValidatorSetState storage vset = currentValidatorSet;
uint16 signatureUsageCount;
if (commitment.validatorSetID == currentValidatorSet.id) {
signatureUsageCount = currentValidatorSet.usageCounters.get(proof.index);
currentValidatorSet.usageCounters
.set(proof.index, signatureUsageCount.saturatingAdd(1));
} else if (commitment.validatorSetID == nextValidatorSet.id) {
signatureUsageCount = nextValidatorSet.usageCounters.get(proof.index);
nextValidatorSet.usageCounters.set(proof.index, signatureUsageCount.saturatingAdd(1));
vset = nextValidatorSet;
} else {
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));
if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) {
revert InvalidSignature();
}
// 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(
computeNumRequiredSignatures(
vset.length, signatureUsageCount, minNumRequiredSignatures
)
),
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,
bytes32[] calldata leafProof,
uint256 leafProofOrder
) external {
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
bytes32 ticketID = createTicketID(msg.sender, commitmentHash);
validateTicket(ticketID, commitment, bitfield);
bool is_next_session = false;
ValidatorSetState storage vset = currentValidatorSet;
if (commitment.validatorSetID == nextValidatorSet.id) {
is_next_session = true;
vset = nextValidatorSet;
} else if (commitment.validatorSetID != currentValidatorSet.id) {
revert InvalidCommitment();
}
// 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);
verifyCommitment(commitmentHash, ticketID, bitfield, vset, proofs);
bytes32 newMMRRoot = ensureProvidesMMRRoot(commitment);
if (is_next_session) {
// The id for candidate nextValidatorSet should be greater than the current
// nextValidatorSet id
if (leaf.nextAuthoritySetID <= nextValidatorSet.id) {
revert InvalidMMRLeaf();
}
bool leafIsValid = MMRProof.verifyLeafProof(
newMMRRoot, keccak256(encodeMMRLeaf(leaf)), leafProof, leafProofOrder
);
if (!leafIsValid) {
revert InvalidMMRLeafProof();
}
currentValidatorSet = nextValidatorSet;
nextValidatorSet.id = leaf.nextAuthoritySetID;
nextValidatorSet.length = leaf.nextAuthoritySetLen;
nextValidatorSet.root = leaf.nextAuthoritySetRoot;
nextValidatorSet.usageCounters = createUint16Array(leaf.nextAuthoritySetLen);
}
latestMMRRoot = newMMRRoot;
latestBeefyBlock = commitment.blockNumber;
delete tickets[ticketID];
emit NewMMRRoot(newMMRRoot, commitment.blockNumber);
}
/**
* @dev Verify that the supplied MMR leaf is included in the latest verified MMR root.
* @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(bytes32 leafHash, bytes32[] calldata proof, uint256 proofOrder)
external
view
returns (bool)
{
return MMRProof.verifyLeafProof(latestMMRRoot, leafHash, proof, proofOrder);
}
/**
* @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 < 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) {
ValidatorSetState 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();
}
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,
bytes32[] calldata leafProof,
uint256 leafProofOrder
) external {
if (commitment.blockNumber <= latestBeefyBlock) {
revert StaleCommitment();
}
bool is_next_session = false;
ValidatorSetState 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();
}
// 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);
bytes32 newMMRRoot = ensureProvidesMMRRoot(commitment);
bytes32 commitmentHash = keccak256(encodeCommitment(commitment));
verifyFiatShamirCommitment(commitmentHash, bitfield, vset, proofs);
if (is_next_session) {
// The id for candidate nextValidatorSet should be greater than the current
// nextValidatorSet id
if (leaf.nextAuthoritySetID <= nextValidatorSet.id) {
revert InvalidMMRLeaf();
}
bool leafIsValid = MMRProof.verifyLeafProof(
newMMRRoot, keccak256(encodeMMRLeaf(leaf)), leafProof, leafProofOrder
);
if (!leafIsValid) {
revert InvalidMMRLeafProof();
}
currentValidatorSet = nextValidatorSet;
nextValidatorSet.id = leaf.nextAuthoritySetID;
nextValidatorSet.length = leaf.nextAuthoritySetLen;
nextValidatorSet.root = leaf.nextAuthoritySetRoot;
nextValidatorSet.usageCounters = createUint16Array(leaf.nextAuthoritySetLen);
}
latestMMRRoot = newMMRRoot;
latestBeefyBlock = commitment.blockNumber;
emit NewMMRRoot(newMMRRoot, commitment.blockNumber);
}
/* Internal Functions */
// Creates a unique ticket ID for a new interactive prover-verifier session
function createTicketID(address account, bytes32 commitmentHash)
internal
pure
returns (bytes32 value)
{
assembly {
mstore(0x00, account)
mstore(0x20, commitmentHash)
value := keccak256(0x0, 0x40)
}
}
/**
* @dev Calculates the number of required signatures for `submitFinal`.
* @param validatorSetLen The length of the validator set
* @param signatureUsageCount A counter of the number of times the validator signature was previously used in a call to `submitInitial` within the session.
* @param minRequiredSignatures The minimum amount of signatures to verify
*/
// For more details on the calculation, read the following:
// 1. https://docs.snowbridge.network/architecture/verification/polkadot#signature-sampling
// 2. https://hackmd.io/9OedC7icR5m-in_moUZ_WQ
function computeNumRequiredSignatures(
uint256 validatorSetLen,
uint256 signatureUsageCount,
uint256 minRequiredSignatures
) internal pure returns (uint256) {
// Start with the minimum number of signatures.
uint256 numRequiredSignatures = minRequiredSignatures;
// Add signatures based on the number of validators in the validator set.
numRequiredSignatures += Math.log2(validatorSetLen, Math.Rounding.Ceil);
// Add signatures based on the signature usage count.
numRequiredSignatures += 1 + (2 * Math.log2(signatureUsageCount + 1, Math.Rounding.Ceil));
// Never require more signatures than 1/3 + 1, which is sufficient to ensure at least one honest validator.
return Math.min(numRequiredSignatures, computeMaxRequiredSignatures(validatorSetLen));
}
/**
* @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 We have 2/3rd +1 honesty assumption on polkadot validators. Hence it is sufficient (for both random sampling and Fiat Shamir) to check 1/3rd +1 validator signatures to ensure at least 1 honest validator signed the payload.
* @param numValidators The number of validators in the validator set.
*/
function computeMaxRequiredSignatures(uint256 numValidators) internal pure returns (uint256) {
return numValidators / 3 + 1;
}
/**
* @dev Verify commitment using the supplied signature proofs
*/
function verifyCommitment(
bytes32 commitmentHash,
bytes32 ticketID,
uint256[] calldata bitfield,
ValidatorSetState 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);
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
if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) {
revert InvalidSignature();
}
// 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,
ValidatorSetState storage vset,
ValidatorProof[] calldata proofs
) internal view {
uint256 requiredSignatures = Math.min(
fiatShamirRequiredSignatures, computeMaxRequiredSignatures(vset.length)
);
if (proofs.length != requiredSignatures) {
revert InvalidValidatorProofLength();
}
uint256[] memory finalbitfield = fiatShamirFinalBitfield(commitmentHash, bitfield, vset);
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
if (ECDSA.recover(commitmentHash, proof.v, proof.r, proof.s) != proof.account) {
revert InvalidSignature();
}
// Ensure no validator can appear more than once in bitfield
Bitfield.unset(finalbitfield, proof.index);
}
}
function createFiatShamirHash(
bytes32 commitmentHash,
bytes32 bitFieldHash,
ValidatorSetState 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,
ValidatorSetState storage vset
) internal view returns (uint256[] memory) {
bytes32 bitFieldHash = keccak256(abi.encodePacked(bitfield));
bytes32 fiatShamirHash = createFiatShamirHash(commitmentHash, bitFieldHash, vset);
uint256 requiredSignatures =
Math.min(fiatShamirRequiredSignatures, computeMaxRequiredSignatures(vset.length));
return
Bitfield.subsample(uint256(fiatShamirHash), bitfield, vset.length, requiredSignatures);
}
// Ensure that the commitment provides a new MMR root
function ensureProvidesMMRRoot(Commitment calldata commitment)
internal
pure
returns (bytes32)
{
for (uint256 i = 0; i < commitment.payload.length; i++) {
if (commitment.payload[i].payloadID == MMR_ROOT_ID) {
return bytes32(commitment.payload[i].data);
}
}
revert CommitmentNotRelevant();
}
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 bytes.concat(
ScaleCodec.encodeU8(leaf.version),
ScaleCodec.encodeU32(leaf.parentNumber),
leaf.parentHash,
ScaleCodec.encodeU64(leaf.nextAuthoritySetID),
ScaleCodec.encodeU32(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(
ValidatorSetState 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();
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 derives the `address(0)`.
*/
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 error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, 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 error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, 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 error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, 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 error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, 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 error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
src/utils/Bitfield.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
import {Bits} from "./Bits.sol";
library Bitfield {
using Bits for uint256;
error InvalidSamplingParams();
error InvalidBitfieldPadding();
/**
* @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++) {
set(bitfield, bitsToSet[i]);
}
return bitfield;
}
/**
* @notice Calculates the number of set bits by using the hamming weight of the bitfield.
* The algorithm below is implemented after https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation.
* Further improvements are possible, see the article above.
*/
function countSetBits(uint256[] memory self) internal pure returns (uint256) {
unchecked {
uint256 count = 0;
for (uint256 i = 0; 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;
}
return count;
}
}
/**
* @notice Calculates the number of set bits in the first `maxBits` bits of the bitfield.
* This is a bounded variant of `countSetBits` that only counts bits within the specified range.
*
* @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;
}
assembly {
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/utils/Bits.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Code from https://github.com/ethereum/solidity-examples
pragma solidity 0.8.34;
library Bits {
uint256 internal constant ONE = uint256(1);
uint256 internal constant ONES = type(uint256).max;
// 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);
}
// Sets the bit at the given 'index' in 'self' to:
// '1' - if the bit is '0'
// '0' - if the bit is '1'
// Returns the modified value.
function toggleBit(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);
}
// Check if the bit at the given 'index' in 'self' is set.
// Returns:
// 'true' - if the value of the bit is '1'
// 'false' - if the value of the bit is '0'
function bitSet(uint256 self, uint8 index) internal pure returns (bool) {
return (self >> index) & 1 == 1;
}
// Checks if the bit at the given 'index' in 'self' is equal to the corresponding
// bit in 'other'.
// Returns:
// 'true' - if both bits are '0' or both bits are '1'
// 'false' - otherwise
function bitEqual(uint256 self, uint256 other, uint8 index) internal pure returns (bool) {
return ((self ^ other) >> index) & 1 == 0;
}
// Get the bitwise NOT of the bit at the given 'index' in 'self'.
function bitNot(uint256 self, uint8 index) internal pure returns (uint8) {
return uint8(1 - ((self >> index) & 1));
}
// Computes the bitwise AND of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitAnd(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) {
return uint8(((self & other) >> index) & 1);
}
// Computes the bitwise OR of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitOr(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) {
return uint8(((self | other) >> index) & 1);
}
// Computes the bitwise XOR of the bit at the given 'index' in 'self', and the
// corresponding bit in 'other', and returns the value.
function bitXor(uint256 self, uint256 other, uint8 index) internal pure returns (uint8) {
return uint8(((self ^ other) >> index) & 1);
}
// Gets 'numBits' consecutive bits from 'self', starting from the bit at 'startIndex'.
// Returns the bits as a 'uint'.
// Requires that:
// - '0 < numBits <= 256'
// - 'startIndex < 256'
// - 'numBits + startIndex <= 256'
function bits(uint256 self, uint8 startIndex, uint16 numBits) internal pure returns (uint256) {
require(0 < numBits && startIndex < 256 && startIndex + numBits <= 256, "out of bounds");
return (self >> startIndex) & (ONES >> (256 - numBits));
}
// Computes the index of the highest bit set in 'self'.
// Returns the highest bit set as an 'uint8'.
// Requires that 'self != 0'.
function highestBitSet(uint256 self) internal pure returns (uint8 highest) {
require(self != 0, "should not be zero");
uint256 val = self;
for (uint8 i = 128; i >= 1; i >>= 1) {
if (val & (((ONE << i) - 1) << i) != 0) {
highest += i;
val >>= i;
}
}
}
// Computes the index of the lowest bit set in 'self'.
// Returns the lowest bit set as an 'uint8'.
// Requires that 'self != 0'.
function lowestBitSet(uint256 self) internal pure returns (uint8 lowest) {
require(self != 0, "should not be zero");
uint256 val = self;
for (uint8 i = 128; i >= 1; i >>= 1) {
if (val & ((ONE << i) - 1) == 0) {
lowest += i;
val >>= i;
}
}
}
}
src/utils/MMRProof.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
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) {
// Size of the proof is bounded, since `proofOrder` can only contain `MAXIMUM_PROOF_SIZE` orderings.
if (proof.length > MAXIMUM_PROOF_SIZE) {
revert ProofSizeExceeded();
}
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) {
assembly {
switch order
case 0 {
mstore(0x00, x)
mstore(0x20, y)
}
default {
mstore(0x00, y)
mstore(0x20, x)
}
value := keccak256(0x0, 0x40)
}
}
}
src/utils/Math.sol
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2023 OpenZeppelin
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
// Code from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol
pragma solidity 0.8.34;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
// forge-lint: disable-next-line(incorrect-shift)
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Safely adds two unsigned 16-bit integers, preventing overflow by saturating to max uint16.
*/
function saturatingAdd(uint16 a, uint16 b) internal pure returns (uint16) {
unchecked {
uint16 c = a + b;
if (c < a) {
return 0xFFFF;
}
return c;
}
}
/**
* @dev Safely subtracts two unsigned 256-bit integers, preventing overflow by saturating to min uint256.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
if (b >= a) {
return 0;
}
return a - b;
}
}
}
src/utils/ScaleCodec.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
library ScaleCodec {
error UnsupportedCompactEncoding();
uint256 internal constant MAX_COMPACT_ENCODABLE_UINT = 2 ** 30 - 1;
// 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 reverse256(uint256 input) internal pure returns (uint256 v) {
v = input;
// swap bytes
v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64)
| ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
function reverse128(uint128 input) internal pure returns (uint128 v) {
v = input;
// swap bytes
v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = (v >> 64) | (v << 64);
}
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 encodeU256(uint256 input) internal pure returns (bytes32) {
return bytes32(reverse256(input));
}
function encodeU128(uint128 input) internal pure returns (bytes16) {
return bytes16(reverse128(input));
}
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 encodeU16(uint16 input) internal pure returns (bytes2) {
return bytes2(reverse16(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 encodeCompactU128(uint128 value) internal pure returns (bytes memory) {
// 1) up to 2^6 - 1
if (value <= 63) {
// single byte = (value << 2)
// (lowest two bits = 00)
// forge-lint: disable-next-line(unsafe-typecast)
return abi.encodePacked(uint8(value << 2));
}
// 2) up to 2^14 - 1
if (value <= 0x3FFF) {
// two bytes = (value << 2) + 0x01
// (lowest two bits = 01)
// forge-lint: disable-next-line(unsafe-typecast)
uint16 encoded = uint16(value << 2) | 0x01;
// We must store it in little-endian
return abi.encodePacked(reverse16(encoded));
}
// 3) up to 2^30 - 1
if (value <= 0x3FFFFFFF) {
// four bytes = (value << 2) + 0x02
// (lowest two bits = 10)
// forge-lint: disable-next-line(unsafe-typecast)
uint32 encoded = (uint32(value) << 2) | 0x02;
return abi.encodePacked(reverse32(encoded));
}
// 4) otherwise
// big integer => prefix + little-endian bytes (no leading zeros)
// prefix = 0x03 + ((numValueBytes - 4) << 2)
// where numValueBytes is how many bytes needed to represent `value`.
bytes memory littleEndian = _toLittleEndianNoLeadingZeros(value);
// forge-lint: disable-next-line(unsafe-typecast)
uint8 len = uint8(littleEndian.length); // number of bytes needed
// Substrate: prefix's lower 2 bits = 0b11,
// the remaining upper bits = (len - 4).
// Combined: prefix = 0x03 + ((len - 4) << 2).
uint8 prefix = ((len - 4) << 2) | 0x03;
// Concatenate prefix + actual bytes
return abi.encodePacked(prefix, littleEndian);
}
// Convert `value` into a little-endian byte array with no leading zeros.
// (Leading zeros in LE = trailing zeros in big-endian.)
function _toLittleEndianNoLeadingZeros(uint128 value) private pure returns (bytes memory) {
// Even if value=0, that case is handled above in smaller branches,
// but let's just handle it gracefully anyway:
if (value == 0) {
return hex"00";
}
// Temporarily build up to 16 bytes in a buffer.
bytes memory buf = new bytes(16);
uint128 current = value;
uint8 i = 0;
while (current != 0) {
// forge-lint: disable-next-line(unsafe-typecast)
buf[i] = bytes1(uint8(current & 0xFF));
current >>= 8;
unchecked {
i++;
}
}
// i is now the actual number of bytes used
// Copy them into a new array of the correct size
bytes memory out = new bytes(i);
for (uint8 j = 0; j < i; j++) {
out[j] = buf[j];
}
return out;
}
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/utils/SubstrateMerkleProof.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
// Used to verify merkle proofs generated by substrate's `binary-merkle-tree`. See:
// https://github.com/paritytech/polkadot-sdk/blob/48a8a0689248e4fba3e6615e0c8c9c83f9df3343/substrate/utils/binary-merkle-tree/src/lib.rs#L359
// The crucial property reproduced below is the PROMOTION rule for odd layers: when a layer has an
// odd number of nodes the lone trailing node is carried up to the next layer UNCHANGED (not hashed
// with itself) — see `merkelize_row` upstream ("Odd number of items. Promote the item to the upper
// layer."). The matching proof generator used in production is the relayer's
// `relayer/crypto/merkle/merkle.go` (`Tree.Hash` / `Tree.MerklePath`, which `continue`s past the
// promoted node and emits no sibling for it). Keep all three in sync.
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;
}
/**
* @notice Reconstruct the merkle root from a leaf and its proof.
* @dev Walk the tree by geometry (not by proof.length) so that the number of sibling hashes
* is dictated by (position, width). A lone trailing node in an odd-width layer is
* promoted to the next layer unchanged and consumes no proof element, exactly as
* substrate's binary-merkle-tree builds the tree. `valid` is true only when `position`
* is in range and the proof length matches the canonical path for the leaf, which binds
* it to a single leaf position: a short (lone-promoted) proof can no longer alias onto
* the many other indices that share its leading decision bits. `root` is `bytes32(0)`
* whenever `valid` is false, so a caller that forgets to check `valid` fails closed.
* @return valid whether the proof is structurally valid for `(position, width)`
* @return root the reconstructed root, or `bytes32(0)` when `valid` is false
*/
function computeRoot(bytes32 leaf, uint256 position, uint256 width, bytes32[] calldata proof)
internal
pure
returns (bool, bytes32)
{
bytes32 node = leaf;
if (position >= width) {
return (false, bytes32(0));
}
uint256 i = 0;
unchecked {
while (width > 1) {
// Promotion rule: the lone trailing node of an odd-width layer is carried up
// unchanged and has no sibling, so it consumes no proof element. Mirrors
// `merkelize_row` in substrate's binary-merkle-tree:
// https://github.com/paritytech/polkadot-sdk/blob/48a8a0689248e4fba3e6615e0c8c9c83f9df3343/substrate/utils/binary-merkle-tree/src/lib.rs#L397
bool promoted = position + 1 == width && width & 1 == 1;
if (!promoted) {
// A genuine sibling is required here. A proof too short for this leaf's
// canonical path is invalid.
if (i >= proof.length) {
return (false, bytes32(0));
}
if (position & 1 == 1) {
node = efficientHash(proof[i], node);
} else {
node = efficientHash(node, proof[i]);
}
i++;
}
position = position >> 1;
width = ((width - 1) >> 1) + 1;
}
}
// The proof must contain exactly the canonical number of siblings -- no more, no less.
if (i == proof.length) {
return (true, node);
}
return (false, bytes32(0));
}
function efficientHash(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
src/utils/Uint16Array.sol
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2023 Snowfork <[email protected]>
pragma solidity 0.8.34;
/**
* @title A utility library for 16 bit counters packed in 256 bit array.
* @dev The BeefyClient needs to store a count of how many times a validators signature is used. In solidity
* a uint16 would take up as much space as a uin256 in storage, making storing counters for 1000 validators
* expensive in terms of gas. The BeefyClient only needs 16 bits per counter. This library allows us to pack
* 16 uint16 into a single uint256 and save 16x storage.
*
* Layout of 32 counters (2 uint256)
* We store all counts in a single large uint256 array and convert from index from the logical uint16 array
* to the physical uint256 array.
*
* 0 1 2
* uint256[] |-- -- -- -- -- -- -- -- -- -- -- -- YY -- -- --|-- -- -- -- -- -- XX -- -- -- -- -- -- -- -- --|
* uint16[] |--|--|--|--|--|--|--|--|--|--|--|--|YY|--|--|--|--|--|--|--|--|--|XX|--|--|--|--|--|--|--|--|--|
* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
*
* Logical Index Layout
* We use the first 4
* |-------...---------|----|
* 256 4 0
* ^index ^bit-index
*
* In the above table counter YY is at logical index 12 in the uint16 array. It will convert to a physical
* index of 0 in the physical uint256 array and then to bit-index of 192 to 207 of that uint256. In the
* above table counter XX is at logical index 22. It will convert to a physical index of 1 in the array and
* then to bit-index 96 to 111 of uint256[1].
*/
using {get, set} for Uint16Array global;
error IndexOutOfBounds();
/**
* @dev stores the backing array and the length.
*/
struct Uint16Array {
uint256[] data;
uint256 length;
}
/**
* @dev Creates a new counter which can store at least `length` counters.
* @param length The amount of counters.
*/
function createUint16Array(uint256 length) pure returns (Uint16Array memory) {
// create space for `length` elements and round up if needed.
uint256 bufferLength = length / 16 + (length % 16 == 0 ? 0 : 1);
return Uint16Array({data: new uint256[](bufferLength), length: length});
}
/**
* @dev Gets the counter at the logical index
* @param self The array.
* @param index The logical index.
*/
function get(Uint16Array storage self, uint256 index) view returns (uint16) {
if (index >= self.length) {
revert IndexOutOfBounds();
}
// Right-shift the index by 4. This truncates the first 4 bits (bit-index) leaving us with the index
// into the array.
uint256 element = index >> 4;
// Mask out the first 4 bits of the logical index to give us the bit-index.
// forge-lint: disable-next-line(unsafe-typecast)
uint8 inside = uint8(index & 0x0F);
// find the element in the array, shift until its bit index and mask to only take the first 16 bits.
return uint16((self.data[element] >> (16 * inside)) & 0xFFFF);
}
/**
* @dev Sets the counter at the logical index.
* @param self The array.
* @param index The logical index of the counter in the array.
* @param value The value to set the counter to.
*/
function set(Uint16Array storage self, uint256 index, uint16 value) {
if (index >= self.length) {
revert IndexOutOfBounds();
}
// Right-shift the index by 4. This truncates the first 4 bits (bit-index) leaving us with the index
// into the array.
uint256 element = index >> 4;
// Mask out the first 4 bytes of the logical index to give us the bit-index.
// forge-lint: disable-next-line(unsafe-typecast)
uint8 inside = uint8(index & 0x0F);
// Create a zero mask which will clear the existing value at the bit-index.
uint256 zero = ~(uint256(0xFFFF) << (16 * inside));
// Shift the value to the bit index.
uint256 shiftedValue = uint256(value) << (16 * inside);
// Take the element, apply the zero mask to clear the existing value, and then apply the shifted value with bitwise or.
self.data[element] = self.data[element] & zero | shiftedValue;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 20000,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"canonical-weth/=lib/canonical-weth/contracts/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/openzeppelin-contracts/contracts/",
"prb/math/=lib/prb-math/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@prb/test/=lib/prb-math/lib/prb-test/src/",
"ds-test/=lib/prb-math/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"prb-math/=lib/prb-math/src/",
"prb-test/=lib/prb-math/lib/prb-test/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.