Verified contractExactBUSL-1.1
ProtocolParams
Address0x7ff7f17b537d01cedcb08686b6ad1b4c11053c3f
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.28
- Same code
Only this contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,399,855
- Creation transaction
- 0xfe8e003783…404d77963e
49 files
- src/protocol/ProtocolParams.solmain30.78 KB
- lib/elliptic-curve-solidity/contracts/EllipticCurve.sol13.69 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.87 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/IAccessControlUpgradeable.sol2.93 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol6.64 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol9.38 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.48 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol2.85 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.54 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol864 B
- lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol12.8 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SignedMathUpgradeable.sol1.27 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol637 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol882 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol473 B
- lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol6.32 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.8 KB
- lib/openzeppelin-contracts/contracts/utils/Bytes.sol11.34 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol5.51 KB
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts/contracts/utils/Strings.sol19.88 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol12.17 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol4.25 KB
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.4 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/interfaces/ITBVPausable.sol162 B
- src/lib/BTCVaultTypes.sol2.18 KB
- src/protocol/abstract/ProtocolTemplateUpg.sol803 B
- src/protocol/interfaces/IProtocolParams.sol15.65 KB
- src/protocol/lib/BTCProofOfPossession.sol24.52 KB
- src/protocol/lib/EthProofOfPossession.sol2.82 KB
- src/protocol/lib/OpKeyVersionSearch.sol3.67 KB
- src/protocol/lib/helpers/BIP322Utils.sol13.61 KB
- src/protocol/lib/helpers/BIP340Utils.sol4.72 KB
- src/protocol/lib/helpers/CompactSize.sol8.52 KB
- src/protocol/lib/helpers/Secp256k1.sol3.33 KB
- src/protocol/lib/taproot/BIP341.sol15.55 KB
- src/protocol/lib/taproot/TaprootConstants.sol2.38 KB
- src/protocol/lib/types/BTCVaultRegistryTypes.sol2.94 KB
- src/protocol/lib/types/Constants.sol794 B
- src/protocol/lib/types/Errors.sol15.33 KB
- src/utility/TBVAccessControlUpg.sol974 B
- src/utility/TBVPausableUpg.sol2.9 KB
- src/utility/TBVTemplateUpg.sol2.04 KB
- src/utility/types/Errors.sol1.75 KB
src/protocol/ProtocolParams.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Constants} from "./lib/types/Constants.sol";
import {Errors} from "./lib/types/Errors.sol";
import {BIP341} from "./lib/taproot/BIP341.sol";
import {IProtocolParams} from "./interfaces/IProtocolParams.sol";
import {BTCVaultTypes} from "../lib/BTCVaultTypes.sol";
import {BTCVaultRegistryTypes} from "./lib/types/BTCVaultRegistryTypes.sol";
import {BTCProofOfPossession} from "./lib/BTCProofOfPossession.sol";
import {EthProofOfPossession} from "./lib/EthProofOfPossession.sol";
import {OpKeyVersionSearch} from "./lib/OpKeyVersionSearch.sol";
import {ProtocolTemplateUpg} from "./abstract/ProtocolTemplateUpg.sol";
/// @title ProtocolParams
/// @notice Centralized parameter management contract for the BTC Vault protocol
/// @dev Upgradeable contract using UUPS pattern with role-based access control
/// @dev All protocol parameters are stored and managed through this contract
contract ProtocolParams is ProtocolTemplateUpg, IProtocolParams {
/// @notice Maximum number of universal challengers that can be set: 60M Block gas limit / 40k storage operations = 15000
uint256 public constant MAX_UNIVERSAL_CHALLENGERS_SIZE = 1500;
/// @notice Upper bound for `expiredPegInGraceBlocks` (~138 days at 12s blocks).
/// @dev Caps how long an Expired vault remains claimable on-chain. Without this ceiling, a
/// misconfiguration could pin vaultd's artifact retention indefinitely and turn the
/// `Expired` status into a near-permanent state for the chain's lifetime.
uint64 public constant MAX_EXPIRED_PEGIN_GRACE_BLOCKS = 1_000_000;
/// @notice Minimum activation window guaranteed to a vault ACKed at the last legal block (~5 minutes at 12s blocks).
/// @dev Floor on `pegInActivationTimeout - (pegInAckTimeout + peginActivationDelay)`. Without it the tuple
/// could leave a worst-case window of a single block, which no depositor can reliably hit.
uint64 public constant MIN_ACTIVATION_WINDOW_BLOCKS = 30;
/// @notice Upper bound for the offchain `feeRate`, in sat/vB.
/// @dev `feeRate` sizes every transaction in a vault's Bitcoin graph, and that graph is
/// signed at pegin but broadcast at pegout. The fee is immutable in between: there is
/// no RBF and no re-funding once the keepers pre-sign against the Claim's txid. A rate
/// published above what nodes will relay therefore yields vaults that can never be
/// settled, and the failure only surfaces at pegout with operator funds already
/// committed. Bitcoin Core refuses to relay above 10,000 sat/vB (`maxfeerate` default)
/// and signing gives out above 25,000 sat/vB, so this ceiling sits an order of
/// magnitude below the point of no return.
uint64 public constant MAX_FEE_RATE_SAT_VB = 1000;
/// @notice Bitcoin block duration used by the approved cross-chain timing model.
uint256 public constant BTC_BLOCK_TIME_SECONDS = 600;
/// @notice Ethereum slot duration used by the approved cross-chain timing model.
uint256 public constant ETH_SLOT_TIME_SECONDS = 12;
/// @notice Safety multiplier applied to the modeled Ethereum activation duration.
uint256 public constant PEGIN_ACTIVATION_SAFETY_MULTIPLIER = 2;
// ========== PegIn Parameters ==========
/// @notice Struct to hold all TBV protocol parameters together for easier management and future extensibility
TBVProtocolParams private _tbvProtocolParams;
// ========== Universal Challengers Parameters ==========
/// @notice Latest version number for universal challengers
uint16 public latestUniversalChallengersVersion;
/// @notice Mapping from version number to universal challengers array
/// @dev Enables versioning of universal challengers for protocol upgrades
mapping(uint16 => BTCVaultTypes.AddressBTCKeyPair[]) private universalChallengersVersions;
// ========== Offchain Parameters ==========
/// @notice Latest version number for offchain parameters
uint16 public latestOffchainParamsVersion;
/// @notice Mapping from version number to offchain parameters
/// @dev Enables versioning of offchain parameters for protocol upgrades
/// @dev Includes Bitcoin timing parameters (t1, t2, t3) and security council configuration
mapping(uint16 => IProtocolParams.VersionedOffchainParams) private offchainParamsVersions;
// ========== Vault Core Version (RFC 004) ==========
/// @notice Currently-active vault Core protocol version
/// @dev Stamped onto every new vault at peg-in submission. Changed by admin
/// during coordinated Core upgrades or rollbacks. See RFC 004.
uint16 public activeVaultCoreVersion;
// ========== Universal Challenger Operation Keys ==========
/// @notice Global UC operation-key epoch, bumped on every UC op-key / op-ETH append
uint64 internal ucKeyEpoch;
/// @notice UC op-BTC-key history (v1+); v0 = roster genesis opBtcKey for ucAdmin, derived on read
mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion)) private _ucOpBtcKeyVersions;
/// @notice Latest UC operation-BTC-key version: ucAdmin => version (0 = genesis)
mapping(address => uint16) private _ucLatestOpBtcKeyVersion;
/// @notice UC op-ETH-key history (v1+); v0 = ucAdmin, derived on read
mapping(address => mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion)) private _ucOpEthKeyVersions;
/// @notice Latest UC operation-ETH-key version: ucAdmin => version (0 = admin default)
mapping(address => uint16) private _ucLatestOpEthKeyVersion;
/// @notice UC roster genesis op-key v0: ucAdmin => v0 BTC key (written once at first listing)
mapping(address => bytes32) private _ucGenesisOpBtcKey;
/// @notice Reverse lookup: UC op-key (any version) => ucAdmin (intra-role uniqueness across versions)
mapping(bytes32 => address) private _ucAdminByBtcKey;
struct ProverInfo {
bytes32 pegoutCircuitVkHash;
bytes32 trustedCheckpoint;
}
/// @inheritdoc IProtocolParams
mapping(uint16 circuitVersion => ProverInfo) public override getProverInfo;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/// @notice Initialize the contract with default parameter values
/// @param admin The address that will have admin and upgrader roles
/// @param initialOffchainParams Initial offchain parameters for version 1; prover info may be registered afterward
/// @param initialUniversalChallengers Initial universal challengers for version 1
/// @param initialVaultCoreVersion Initial active vault Core version (RFC 004)
function initialize(
address admin,
TBVProtocolParams memory initialParams,
IProtocolParams.VersionedOffchainParams memory initialOffchainParams,
BTCVaultTypes.AddressBTCKeyPair[] memory initialUniversalChallengers,
uint16 initialVaultCoreVersion
) external initializer {
if (admin == address(0)) revert Errors.ZeroAddress();
__TBVTemplateUpg_init(admin);
// Initialize TBV protocol parameters
_setTBVParams(initialParams);
// Initialize offchain params version 1 with provided values
_updateOffchainParams(initialOffchainParams);
// Initialize universal challengers version 1 with provided values
_updateUniversalChallengers(initialUniversalChallengers);
// Initialize active vault Core version (RFC 004)
_setActiveVaultCoreVersion(initialVaultCoreVersion);
}
// ========== Universal Challengers Functions ==========
/// @notice Add a new version of universal challengers
/// @param challengers Array of universal challengers for this version
/// @dev Auto-increments the version number
/// @dev Once a version is set, it cannot be modified (immutable)
function addUniversalChallengersVersion(BTCVaultTypes.AddressBTCKeyPair[] calldata challengers) external onlyAdmin {
_updateUniversalChallengers(challengers);
}
/// @notice Get universal challengers for a specific roster version
/// @param versionNumber The version number
/// @return Array of universal challengers for the specified version
/// @dev The version axis is roster membership, not key rotation. Each pair's `btcPubKey` is
/// the member's genesis roster key, not updated by op-key rotation.
/// Resolve keys per member via `getOperationBtcKeyAtEpochOrGenesis`
/// (current epoch = `ucKeyEpochCurrent`).
function getUniversalChallengersByVersion(uint16 versionNumber)
external
view
returns (BTCVaultTypes.AddressBTCKeyPair[] memory)
{
return universalChallengersVersions[versionNumber];
}
/// @notice Get the current active universal challengers
/// @return Array of current universal challengers
/// @dev Current in roster membership only. Each pair's `btcPubKey` is the member's genesis
/// roster key, not updated by op-key rotation. Resolve keys per member via
/// `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `ucKeyEpochCurrent`).
function getCurrentUniversalChallengers() external view returns (BTCVaultTypes.AddressBTCKeyPair[] memory) {
return universalChallengersVersions[latestUniversalChallengersVersion];
}
// ========== UC Operation Key Functions ==========
/// @inheritdoc IProtocolParams
function ucKeyEpochCurrent() external view returns (uint64) {
return ucKeyEpoch;
}
/// @inheritdoc IProtocolParams
function latestOperationBtcKeyVersion(address ucAdmin) external view returns (uint16) {
return _ucLatestOpBtcKeyVersion[ucAdmin];
}
/// @inheritdoc IProtocolParams
function latestOperationEthKeyVersion(address ucAdmin) external view returns (uint16) {
return _ucLatestOpEthKeyVersion[ucAdmin];
}
/// @inheritdoc IProtocolParams
function getOperationBtcKeyByVersion(address ucAdmin, uint16 version) external view returns (bytes32) {
if (version == 0) return _ucGenesisOpBtcKeyResolved(ucAdmin);
return _ucOpBtcKeyVersions[ucAdmin][version].key;
}
/// @inheritdoc IProtocolParams
function getCurrentOperationBtcKey(address ucAdmin) external view returns (bytes32) {
uint16 latest = _ucLatestOpBtcKeyVersion[ucAdmin];
if (latest == 0) return _ucGenesisOpBtcKeyResolved(ucAdmin);
return _ucOpBtcKeyVersions[ucAdmin][latest].key;
}
/// @inheritdoc IProtocolParams
function getOperationEthKeyByVersion(address ucAdmin, uint16 version) external view returns (address) {
if (version == 0) return ucAdmin;
return _ucOpEthKeyVersions[ucAdmin][version].key;
}
/// @inheritdoc IProtocolParams
function getCurrentOperationEthKey(address ucAdmin) external view returns (address) {
uint16 latest = _ucLatestOpEthKeyVersion[ucAdmin];
if (latest == 0) return ucAdmin;
return _ucOpEthKeyVersions[ucAdmin][latest].key;
}
/// @inheritdoc IProtocolParams
function setOperationEthKey(address newOpEthKey, bytes calldata ethPopSignature) external {
_requireCurrentUcAdmin(msg.sender);
if (newOpEthKey == address(0)) revert Errors.ZeroAddress();
// Self-PoP against the NEW op-ETH key, owned by the UC admin (caller).
if (!EthProofOfPossession.verify(newOpEthKey, msg.sender, "", ethPopSignature)) {
revert Errors.InvalidEthProofOfPossession();
}
uint16 latest = _ucLatestOpEthKeyVersion[msg.sender];
if (latest == type(uint16).max) revert Errors.OperationKeyVersionOverflow();
uint16 newVersion = latest + 1;
ucKeyEpoch += 1;
_ucLatestOpEthKeyVersion[msg.sender] = newVersion;
_ucOpEthKeyVersions[msg.sender][newVersion] =
BTCVaultRegistryTypes.OpEthKeyVersion({key: newOpEthKey, epoch: ucKeyEpoch});
emit OperationEthKeyVersionAdded(msg.sender, newVersion, newOpEthKey, ucKeyEpoch);
}
/// @inheritdoc IProtocolParams
function setOperationBtcKey(bytes32 newOpBtcKey, bytes calldata btcPopSignature) external {
_requireCurrentUcAdmin(msg.sender);
if (!BIP341.isValidXOnlyKey(newOpBtcKey)) revert Errors.InvalidBTCPublicKey();
address claimedBy = _ucAdminByBtcKey[newOpBtcKey];
if (claimedBy != address(0) && claimedBy != msg.sender) revert Errors.BtcKeyAlreadyRegistered();
if (!BTCProofOfPossession.verifyWithPayload(
btcPopSignature,
newOpBtcKey,
msg.sender,
BTCProofOfPossession.ACTION_SET_OPERATION_BTC_KEY,
abi.encodePacked(newOpBtcKey)
)) {
revert Errors.InvalidBTCProofOfPossession();
}
uint16 latest = _ucLatestOpBtcKeyVersion[msg.sender];
if (latest == type(uint16).max) revert Errors.OperationKeyVersionOverflow();
uint16 newVersion = latest + 1;
ucKeyEpoch += 1;
_ucLatestOpBtcKeyVersion[msg.sender] = newVersion;
_ucOpBtcKeyVersions[msg.sender][newVersion] =
BTCVaultRegistryTypes.OpBtcKeyVersion({key: newOpBtcKey, epoch: ucKeyEpoch});
_ucAdminByBtcKey[newOpBtcKey] = msg.sender;
emit OperationBtcKeyVersionAdded(msg.sender, newVersion, newOpBtcKey, ucKeyEpoch);
}
/// @inheritdoc IProtocolParams
function getOperationBtcKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (bytes32) {
uint16 v =
OpKeyVersionSearch.findAtEpoch(_ucOpBtcKeyVersions[ucAdmin], _ucLatestOpBtcKeyVersion[ucAdmin], epoch);
if (v == 0) return _ucGenesisOpBtcKeyResolved(ucAdmin);
return _ucOpBtcKeyVersions[ucAdmin][v].key;
}
/// @inheritdoc IProtocolParams
function getOperationBtcKeyAtEpochOrGenesis(address ucAdmin, uint64 epoch, bytes32 rosterGenesisKey)
external
view
returns (bytes32)
{
uint16 v =
OpKeyVersionSearch.findAtEpoch(_ucOpBtcKeyVersions[ucAdmin], _ucLatestOpBtcKeyVersion[ucAdmin], epoch);
if (v == 0) return rosterGenesisKey;
return _ucOpBtcKeyVersions[ucAdmin][v].key;
}
/// @inheritdoc IProtocolParams
function getOperationEthKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (address) {
uint16 v =
OpKeyVersionSearch.findAtEpoch(_ucOpEthKeyVersions[ucAdmin], _ucLatestOpEthKeyVersion[ucAdmin], epoch);
if (v == 0) return ucAdmin;
return _ucOpEthKeyVersions[ucAdmin][v].key;
}
/// @notice Revert unless `caller` is a UC admin in the latest membership version (admin gate)
function _requireCurrentUcAdmin(address caller) private view {
BTCVaultTypes.AddressBTCKeyPair[] memory current =
universalChallengersVersions[latestUniversalChallengersVersion];
for (uint256 i = 0; i < current.length; i++) {
if (current[i].ethAddress == caller) return;
}
revert Errors.Unauthorized();
}
/// @notice Genesis (v0) operation BTC key for a UC.
/// @dev Fast path is the O(1) `_ucGenesisOpBtcKey` mapping; otherwise falls back to scanning the
/// current membership roster for the admin's entry and returning its op-key.
function _ucGenesisOpBtcKeyResolved(address ucAdmin) private view returns (bytes32) {
bytes32 genesis = _ucGenesisOpBtcKey[ucAdmin];
if (genesis != bytes32(0)) return genesis;
BTCVaultTypes.AddressBTCKeyPair[] memory current =
universalChallengersVersions[latestUniversalChallengersVersion];
for (uint256 i = 0; i < current.length; i++) {
if (current[i].ethAddress == ucAdmin) return current[i].btcPubKey;
}
return bytes32(0);
}
// ========== TBV Protocol Parameters Functions ==========
/// @notice Get all TBV protocol parameters
/// @return The TBV protocol parameters
function getTBVProtocolParams() external view returns (TBVProtocolParams memory) {
return _tbvProtocolParams;
}
/// @notice Get individual TBV protocol parameters
///
function minimumPegInAmount() external view returns (uint256) {
return _tbvProtocolParams.minimumPegInAmount;
}
/// @notice Get the maximum peg-in amount
/// @return The maximum peg-in amount in satoshis (0 = unlimited)
function maxPegInAmount() external view returns (uint256) {
return _tbvProtocolParams.maxPegInAmount;
}
/// @notice Get the peg-in ACK timeout
/// @return The peg-in ACK timeout in Ethereum blocks
function pegInAckTimeout() external view returns (uint256) {
return _tbvProtocolParams.pegInAckTimeout;
}
/// @notice Get the peg-in activation timeout
/// @return The peg-in activation timeout in Ethereum blocks
function pegInActivationTimeout() external view returns (uint256) {
return _tbvProtocolParams.pegInActivationTimeout;
}
/// @notice Get the post-expiry grace window for `claimExpiredVault`
/// @return The grace window in Ethereum blocks measured from the activation deadline
function expiredPegInGraceBlocks() external view returns (uint256) {
return _tbvProtocolParams.expiredPegInGraceBlocks;
}
/// @notice Get the observation window enforced between ACK completion and application activation
/// @return The delay in Ethereum blocks measured from the vault's `verifiedAt` block
function peginActivationDelay() external view returns (uint256) {
return _tbvProtocolParams.peginActivationDelay;
}
/// @notice Set all TBV protocol parameters in a single transaction
/// @param params The TBV protocol parameters to set
/// @dev Validates all parameters before setting. If any parameter is invalid, the entire transaction reverts with an error.
function setTBVParams(TBVProtocolParams memory params) external onlyAdmin {
_setTBVParams(params);
}
/// @notice Set all TBV protocol parameters
function _setTBVParams(TBVProtocolParams memory params) internal {
_validateTBVProtocolParams(params);
uint16 offchainParamsVersion = latestOffchainParamsVersion;
if (offchainParamsVersion > 0) {
_validatePeginTiming(params.pegInActivationTimeout, offchainParamsVersions[offchainParamsVersion].tRefund);
}
_tbvProtocolParams = params;
emit ProtocolParamsUpdated(params);
}
// ========== Prover Info ==========
/// @inheritdoc IProtocolParams
function registerProverInfo(uint16 circuitVersion, bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint)
external
onlyAdmin
{
if (getProverInfo[circuitVersion].trustedCheckpoint != bytes32(0)) {
revert Errors.ProverInfoAlreadyRegistered(circuitVersion);
}
if (circuitVersion == 0 || pegoutCircuitVkHash == bytes32(0) || trustedCheckpoint == bytes32(0)) {
revert Errors.ZeroValue();
}
getProverInfo[circuitVersion] = ProverInfo(pegoutCircuitVkHash, trustedCheckpoint);
emit ProverInfoRegistered(circuitVersion, pegoutCircuitVkHash, trustedCheckpoint);
}
// ========== Offchain Parameters Functions ==========
/// @inheritdoc IProtocolParams
function addOffchainParamsVersion(IProtocolParams.VersionedOffchainParams calldata params) external onlyAdmin {
_updateOffchainParams(params);
}
/// @notice Get offchain parameters for a specific version
/// @param versionNumber The version number
/// @return The offchain parameters for the specified version
function getOffchainParamsByVersion(uint16 versionNumber)
external
view
returns (IProtocolParams.VersionedOffchainParams memory)
{
return offchainParamsVersions[versionNumber];
}
/// @notice Get the latest offchain parameters
/// @return The latest offchain parameters
function getLatestOffchainParams() external view returns (IProtocolParams.VersionedOffchainParams memory) {
return offchainParamsVersions[latestOffchainParamsVersion];
}
// ========== Vault Core Version Functions (RFC 004) ==========
/// @notice Set the active vault Core version (admin-only)
/// @param newVersion The new active vault Core version
/// @dev Accepts upgrades and rollbacks; rejects 0 and the current version
function setActiveVaultCoreVersion(uint16 newVersion) external onlyAdmin {
_setActiveVaultCoreVersion(newVersion);
}
function _setActiveVaultCoreVersion(uint16 newVersion) internal {
if (newVersion == 0) revert Errors.ZeroValue();
uint16 prev = activeVaultCoreVersion;
if (newVersion == prev) revert Errors.InvalidAmount();
activeVaultCoreVersion = newVersion;
emit ActiveVaultCoreVersionUpdated(prev, newVersion);
}
// ========== Internal Set Functions ==========
function _updateOffchainParams(IProtocolParams.VersionedOffchainParams memory params) internal {
_validateOffchainParams(params);
_validatePeginTiming(_tbvProtocolParams.pegInActivationTimeout, params.tRefund);
// Initialization is exempt; every later parameter update requires registered prover info.
uint16 currentVersion = latestOffchainParamsVersion;
if (currentVersion > 0 && getProverInfo[params.proverCircuitVersion].trustedCheckpoint == bytes32(0)) {
revert Errors.ProverInfoNotRegistered(params.proverCircuitVersion);
}
uint16 newVersionNumber = currentVersion + 1;
latestOffchainParamsVersion = newVersionNumber;
offchainParamsVersions[newVersionNumber] = params;
emit OffchainParamsVersionAdded(newVersionNumber, params);
}
function _updateUniversalChallengers(BTCVaultTypes.AddressBTCKeyPair[] memory challengers) internal {
if (challengers.length > MAX_UNIVERSAL_CHALLENGERS_SIZE) {
revert Errors.ArrayExceedsMaxSize(challengers.length, MAX_UNIVERSAL_CHALLENGERS_SIZE);
}
_validateUniversalChallengers(challengers);
uint16 newVersionNumber = latestUniversalChallengersVersion + 1;
latestUniversalChallengersVersion = newVersionNumber;
BTCVaultTypes.AddressBTCKeyPair[] memory roster = new BTCVaultTypes.AddressBTCKeyPair[](challengers.length);
for (uint256 i = 0; i < challengers.length; i++) {
address ucAdmin = challengers[i].ethAddress;
bytes32 opKey = challengers[i].btcPubKey;
bytes32 genesis = _ucGenesisOpBtcKey[ucAdmin];
if (genesis == bytes32(0)) {
// First listing: seed v0 genesis and register the intra-role reverse lookup.
address claimedBy = _ucAdminByBtcKey[opKey];
if (claimedBy != address(0) && claimedBy != ucAdmin) revert Errors.DuplicateParticipant();
_ucGenesisOpBtcKey[ucAdmin] = opKey;
_ucAdminByBtcKey[opKey] = ucAdmin;
} else if (genesis != opKey) {
// Re-listing must repeat the existing genesis; membership never mutates keys.
revert Errors.InvalidBTCPublicKey();
}
roster[i] = BTCVaultTypes.AddressBTCKeyPair({ethAddress: ucAdmin, btcPubKey: opKey});
universalChallengersVersions[newVersionNumber].push(roster[i]);
}
emit UniversalChallengersVersionAdded(newVersionNumber, roster);
}
// ========== Internal Validation Functions ==========
/// @notice Validate BTC protocol parameters
/// @param params The BTC protocol parameters to validate
function _validateTBVProtocolParams(IProtocolParams.TBVProtocolParams memory params) private pure {
if (params.minimumPegInAmount < Constants.BTC_DUST_THRESHOLD) {
revert Errors.AmountBelowMinimumThreshold(params.minimumPegInAmount, Constants.BTC_DUST_THRESHOLD);
}
// maxPegInAmount must be >= minimumPegInAmount (if both are set)
// Zero values are allowed for maxPegInAmount to disable the maximum limit
if (params.maxPegInAmount > 0 && params.maxPegInAmount < params.minimumPegInAmount) {
revert Errors.MaxPegInBelowMinPegIn(params.maxPegInAmount, params.minimumPegInAmount);
}
if (params.pegInAckTimeout == 0 || params.pegInActivationTimeout == 0) {
revert Errors.ZeroValue();
}
// Activation timeout must exceed the ACK timeout plus the observation window by at least
// `MIN_ACTIVATION_WINDOW_BLOCKS` so that a vault ACKed at the last legal block still has a usable activation
// window. Both deadlines are measured from `createdAt` while the observation window is measured from
// `verifiedAt`, so the worst case is an ACK set completing at `createdAt + pegInAckTimeout`, which pushes the
// earliest activation to `createdAt + pegInAckTimeout + peginActivationDelay`. Widened to uint256 so an
// overlarge parameter pair reverts here rather than panicking on uint64 overflow.
if (
uint256(params.pegInActivationTimeout)
< uint256(params.pegInAckTimeout) + uint256(params.peginActivationDelay)
+ uint256(MIN_ACTIVATION_WINDOW_BLOCKS)
) {
revert Errors.InvalidAmount();
}
if (params.maxHtlcOutputCount == 0) revert Errors.ZeroValue();
if (params.maxFundingInputCount == 0) revert Errors.ZeroValue();
// expiredPegInGraceBlocks must be non-zero
if (params.expiredPegInGraceBlocks == 0) revert Errors.ZeroValue();
// Cap the grace window. Unbounded values would let governance pin vaultd's artifact
// retention near-indefinitely and effectively make `Expired` non-terminal for the chain's
// lifetime, which the post-expiry recovery flow is not designed to support.
if (params.expiredPegInGraceBlocks > MAX_EXPIRED_PEGIN_GRACE_BLOCKS) revert Errors.InvalidAmount();
}
/// @notice Validate offchain parameters
/// @param params The offchain parameters to validate
function _validateOffchainParams(IProtocolParams.VersionedOffchainParams memory params) private pure {
// Validate timing parameters are non-zero
if (params.timelockAssert == 0) revert Errors.ZeroValue();
if (params.timelockChallengeAssert == 0) revert Errors.ZeroValue();
if (params.timelockAssert > type(uint16).max) revert Errors.InvalidAmount();
// Validate security council configuration
if (params.securityCouncilKeys.length == 0) {
revert Errors.InvalidSecurityCouncilConfig();
}
// Validate security council keys and reject duplicate signers
for (uint256 i = 0; i < params.securityCouncilKeys.length; i++) {
bytes32 key = params.securityCouncilKeys[i];
if (!BIP341.isValidXOnlyKey(key)) {
revert Errors.InvalidSecurityCouncilConfig();
}
for (uint256 j = 0; j < i; j++) {
if (params.securityCouncilKeys[j] == key) revert Errors.InvalidSecurityCouncilConfig();
}
}
// Validate council quorum
if (params.councilQuorum == 0) {
revert Errors.InvalidSecurityCouncilConfig();
}
if (params.councilQuorum > params.securityCouncilKeys.length) {
revert Errors.InvalidSecurityCouncilConfig();
}
// Validate TX graph construction parameters
if (params.feeRate == 0) revert Errors.ZeroValue();
if (params.feeRate > MAX_FEE_RATE_SAT_VB) revert Errors.InvalidAmount();
// Validate BaBe cut-and-choose parameters
if (params.babeTotalInstances == 0) revert Errors.ZeroValue();
if (params.babeInstancesToFinalize == 0) revert Errors.ZeroValue();
if (params.babeInstancesToFinalize >= params.babeTotalInstances) revert Errors.InvalidAmount();
// Validate maximum vault provider commission cap; it must admit at least the hardcoded minimum
if (params.maxVpCommissionBps < Constants.MIN_VP_COMMISSION_BPS || params.maxVpCommissionBps >= 10000) {
revert Errors.InvalidAmount();
}
// Validate atomic swap timing parameters
if (params.tRefund == 0) revert Errors.ZeroValue();
if (params.tStale == 0) revert Errors.ZeroValue();
if (params.minPeginFeeRate == 0) revert Errors.ZeroValue();
if (params.proverCircuitVersion == 0) revert Errors.ZeroValue();
if (params.minPrepeginDepth == 0) revert Errors.ZeroValue();
}
/// @notice Validate that the Bitcoin refund window safely outlasts the Ethereum activation window
/// @param _pegInActivationTimeout Activation window in Ethereum blocks
/// @param _tRefund Refund window in Bitcoin blocks
function _validatePeginTiming(uint64 _pegInActivationTimeout, uint32 _tRefund) private pure {
uint256 refundDuration = uint256(_tRefund) * BTC_BLOCK_TIME_SECONDS;
uint256 requiredRefundDuration =
uint256(_pegInActivationTimeout) * ETH_SLOT_TIME_SECONDS * PEGIN_ACTIVATION_SAFETY_MULTIPLIER;
if (refundDuration <= requiredRefundDuration) {
revert Errors.UnsafePeginTimingConfiguration(_tRefund, _pegInActivationTimeout);
}
}
/// @notice Validate universal challengers array
/// @param challengers The universal challengers to validate
function _validateUniversalChallengers(BTCVaultTypes.AddressBTCKeyPair[] memory challengers) private pure {
if (challengers.length == 0) revert Errors.InvalidParticipantsList();
for (uint256 i = 0; i < challengers.length; i++) {
if (challengers[i].ethAddress == address(0)) {
revert Errors.ZeroAddress();
}
if (!BIP341.isValidXOnlyKey(challengers[i].btcPubKey)) {
revert Errors.InvalidBTCPublicKey();
}
// Reject duplicate ETH addresses or BTC public keys within the same list
for (uint256 j = i + 1; j < challengers.length; j++) {
if (challengers[i].ethAddress == challengers[j].ethAddress) {
revert Errors.DuplicateParticipant();
}
if (challengers[i].btcPubKey == challengers[j].btcPubKey) {
revert Errors.DuplicateParticipant();
}
}
}
}
/// @notice Get the contract version
/// @return Version string
function version() external pure returns (string memory) {
return "1.0.0";
}
}
lib/elliptic-curve-solidity/contracts/EllipticCurve.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
** @title Elliptic Curve Library
** @dev Library providing arithmetic operations over elliptic curves.
** This library does not check whether the inserted points belong to the curve
** `isOnCurve` function should be used by the library user to check the aforementioned statement.
** @author Witnet Foundation
*/
library EllipticCurve {
// Pre-computed constant for 2 ** 255
uint256 private constant U255_MAX_PLUS_1 =
57896044618658097711785492504343953926634992332820282019728792003956564819968;
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 t;
while (_x != 0) {
t = r / _x;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, _x) = (_x, r - t * _x);
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(
uint256 _base,
uint256 _exp,
uint256 _pp
)
internal pure
returns (uint256)
{
require(_pp != 0, "EllipticCurve: modulus is zero");
if (_base == 0) return 0;
if (_exp == 0) return 1;
uint256 r = 1;
uint256 bit = U255_MAX_PLUS_1;
assembly {
for {
} gt(bit, 0) {
} {
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, bit)))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 2))))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 4))))),
_pp
)
r := mulmod(
mulmod(r, r, _pp),
exp(_base, iszero(iszero(and(_exp, div(bit, 8))))),
_pp
)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp
)
internal pure
returns (uint256)
{
require(
_prefix == 0x02 || _prefix == 0x03,
"EllipticCurve:innvalid compressed EC point prefix"
);
// x^3 + ax + b
uint256 y2 = addmod(
mulmod(_x, mulmod(_x, _x, _pp), _pp),
addmod(mulmod(_x, _aa, _pp), _bb, _pp),
_pp
);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp
)
internal pure
returns (bool)
{
if (0 == _x || _x >= _pp || 0 == _y || _y >= _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1 == _x2) {
// y1 = -y2 mod p
if (addmod(_y1, _y2, _pp) == 0) {
return (0, 0);
} else {
// P1 = P2
(x, y, z) = jacDouble(_x1, _y1, 1, _aa, _pp);
}
} else {
(x, y, z) = jacAdd(_x1, _y1, 1, _x2, _y2, 1, _pp);
}
// Get back to affine
return toAffine(x, y, z, _pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(_x1, _y1, x, y, _aa, _pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(_k, _x, _y, 1, _aa, _pp);
// Get back to affine
return toAffine(x1, y1, z1, _pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
if (_x1 == 0 && _y1 == 0) return (_x2, _y2, _z2);
if (_x2 == 0 && _y2 == 0) return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(
zs[0] != zs[2] || zs[1] != zs[3],
"Use jacDouble function instead"
);
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(
hr[1],
addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp),
_pp
);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa the a scalar in the curve equation
/// @param _pp the modulus
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
if (_z == 0) return (_x, _y, _z);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
// x, y, z at this point represent the squares of _x, _y, _z
uint256 x = mulmod(_x, _x, _pp); //x1^2
uint256 y = mulmod(_y, _y, _pp); //y1^2
uint256 z = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, y, _pp), _pp);
// m
uint m = addmod(
mulmod(3, x, _pp),
mulmod(_aa, mulmod(z, z, _pp), _pp),
_pp
);
// x, y, z at this point will be reassigned and rather represent qx, qy, qz from the paper
// This allows to reduce the gas cost and stack footprint of the algorithm
// qx
x = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
y = addmod(
mulmod(m, addmod(s, _pp - x, _pp), _pp),
_pp - mulmod(8, mulmod(y, y, _pp), _pp),
_pp
);
// qz = 2*y1*z1
z = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (x, y, z);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp
)
internal pure
returns (uint256, uint256, uint256)
{
// Early return in case that `_d == 0`
if (_d == 0) {
return (_x, _y, _z);
}
uint256 remaining = _d;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(qx, qy, qz, _x, _y, _z, _pp);
}
remaining = remaining / 2;
(_x, _y, _z) = jacDouble(_x, _y, _z, _aa, _pp);
}
return (qx, qy, qz);
}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(account),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
lib/openzeppelin-contracts-upgradeable/contracts/access/IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward 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 Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SignedMathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* @custom:stateless
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bool success = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
bool success = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
bool success = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Bytes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The
* `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Concatenate an array of bytes into a single bytes object.
*
* For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
* `abi.encodePacked`.
*
* NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
* significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
*/
function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
uint256 length = 0;
for (uint256 i = 0; i < buffers.length; ++i) {
length += buffers[i].length;
}
bytes memory result = new bytes(length);
uint256 offset = 0x20;
for (uint256 i = 0; i < buffers.length; ++i) {
bytes memory input = buffers[i];
assembly ("memory-safe") {
mcopy(add(result, offset), add(input, 0x20), mload(input))
}
unchecked {
offset += input.length;
}
}
return result;
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 0x20) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i = 0; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
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);
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.24;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @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 Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @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 Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/interfaces/ITBVPausable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
interface ITBVPausable {
enum PauseState {
None,
Frozen,
Paused
}
}
src/lib/BTCVaultTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/// @title BTCVaultTypes
/// @notice Shared BTC vault types used across protocol and application boundaries
library BTCVaultTypes {
/// @notice Struct pairing an Ethereum address with its corresponding BTC public key
struct AddressBTCKeyPair {
address ethAddress;
bytes32 btcPubKey;
}
/// @notice Vault keeper roster-registration input: identity + genesis op-key + required payout
/// @dev adminEthAddress is the immutable authority + history key; opBtcKey is op-key v0;
/// payoutScript is recorded as payout v1 (v0 is the BIP-86 default, derived on read).
/// opEthKey optionally bootstraps a distinct operation-ETH key at first listing or appends
/// a replacement when re-listing a removed keeper (address(0) retains the current key).
/// ethPopSignature is the EIP-191 self-PoP by opEthKey, required when opEthKey is set and
/// ignored otherwise.
struct VaultKeeperRegistration {
address adminEthAddress;
bytes32 opBtcKey;
bytes payoutScript;
address opEthKey;
bytes ethPopSignature;
}
/// @notice Pegin request status enum
enum BTCVaultStatus {
Pending, // Request submitted, waiting for ACKs
Verified, // All ACKs collected, ready for secret activation
Active, // Secret revealed, vault is active and usable
Redeemed, // Vault has been redeemed, BTC is claimable
Expired // Pegin request expired (timeout exceeded before activation)
}
/// @notice Vault fields needed for lightweight reads and activation callbacks
struct BTCVaultBasicInfo {
address depositor; // Original vault creator
bytes32 depositorBtcPubKey; // Depositor's x-only BTC public key
uint256 amount; // Vault amount in satoshis
address vaultProvider; // Vault provider assigned to this vault
BTCVaultStatus status; // Current vault lifecycle state
address applicationEntryPoint; // Application that owns the vault
uint256 createdAt; // Ethereum block number when the vault was created
}
}
src/protocol/abstract/ProtocolTemplateUpg.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {TBVTemplateUpg} from "../../utility/TBVTemplateUpg.sol";
/// @title ProtocolTemplateUpg
/// @notice Protocol-level role IDs for the TBV governance template
abstract contract ProtocolTemplateUpg is TBVTemplateUpg {
function _ADMIN_ROLE() internal pure override returns (bytes32) {
return keccak256("TBV_PROTOCOL_ADMIN");
}
function _PAUSE_GUARDIAN_ROLE() internal pure override returns (bytes32) {
return keccak256("TBV_PROTOCOL_PAUSE_GUARDIAN");
}
function _FREEZE_GUARDIAN_ROLE() internal pure override returns (bytes32) {
return keccak256("TBV_PROTOCOL_FREEZE_GUARDIAN");
}
function TBV_PROTOCOL_ADMIN() public pure returns (bytes32) {
return _ADMIN_ROLE();
}
}
src/protocol/interfaces/IProtocolParams.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {BTCVaultTypes} from "../../lib/BTCVaultTypes.sol";
/// @title IProtocolParams
/// @notice Interface for the ProtocolParams contract
interface IProtocolParams {
struct TBVProtocolParams {
// ------------- PegIn Configuration -------------
/// @notice Minimum amount that depositor must lock into the vault (in satoshis)
/// @dev Anti-spam mechanism to prevent system abuse
uint64 minimumPegInAmount;
/// @notice Maximum amount that depositor can lock into the vault (in satoshis)
uint64 maxPegInAmount;
/// @notice Timeout for all required ACKs to be submitted (in ETH blocks)
/// @dev Short window (e.g. ~1 day). If ACKs are not collected within this window, the vault can be expired.
uint64 pegInAckTimeout;
/// @notice Timeout for pegin activation after vault creation (in ETH blocks)
/// @dev Window from createdAt within which activateVaultWithSecret must be called
uint64 pegInActivationTimeout;
/// @notice Maximum number of HTLC outputs allowed in a batched Pre-PegIn transaction
/// @dev Prevents Pre-PegIns with too many outputs that can't all be processed before tStale expiry
uint8 maxHtlcOutputCount;
/// @notice Grace window after the activation deadline during which `claimExpiredVault` may be called (in ETH blocks)
/// @dev Cutoff is `block.number > (block.number at reportExpired) + expiredPegInGraceBlocks`. Must align with vaultd's
/// deferred artifact retention window so on-chain claims remain actionable off-chain.
uint64 expiredPegInGraceBlocks;
/// @notice Observation window enforced between ACK completion and application activation (in ETH blocks)
/// @dev Measured from `verifiedAt`, the block at which the final required ACK moved the vault to `Verified`.
/// A complete ACK set asserts the Pre-PegIn is confirmed to `minPrepeginDepth` on Bitcoin, so an ACKed
/// vault with no corresponding Bitcoin transaction is an observable protocol violation. This window
/// denies colluding participants the ability to ACK and activate atomically, giving monitoring time to
/// pause the application before vaultBTC is minted as Aave collateral. Only `activateVaultWithSecret`
/// is gated; `activateVaultWithSecretAndRedeem` mints nothing and stays available as an unwind path.
/// Set to 0 to disable.
uint64 peginActivationDelay;
/// @notice Maximum number of funding inputs allowed in a Pre-PegIn or Claim transaction
/// @dev Enforced on-chain against `unsignedPrePeginTx` at peg-in submission. Off-chain actors read the
/// same bound to size Claim transactions, which never reach this contract. Bounding the input side
/// denies a depositor the ability to fan one Ethereum submission out into an unbounded per-input
/// `getrawtransaction` storm across every VP, VK and UC ingesting the resulting `PegInSubmitted`
/// event. Appended after `peginActivationDelay` so it extends the existing packed slot rather
/// than shifting the offsets of the fields above it.
uint8 maxFundingInputCount;
}
/// @notice Versioned offchain parameters for off-chain actors
/// @dev These parameters are used by off-chain actors for data availability and protocol operation
struct VersionedOffchainParams {
// Bitcoin timing parameters (in BTC blocks)
uint256 timelockAssert; // Timelock for assert period (blocks)
uint256 timelockChallengeAssert; // Timelock for challenge-assert period (blocks)
bytes32[] securityCouncilKeys; // Array of BTC public keys for security council members
uint8 councilQuorum; // Number of signatures required for council action (n-of-m multisig)
// TX Graph Construction Parameters
uint64 feeRate; // Fee rate in sat/vB (e.g., 2 = 2 sat/vB)
// BaBe Cut-and-Choose Protocol Parameters
uint16 babeTotalInstances; // Total number of GC instances created in cut-and-choose protocol
uint8 babeInstancesToFinalize; // Number of GC instances to finalize (closed instances used for evaluation)
// Maximum vault provider commission in basis points (10000 = 100%, 1 = 0.01%).
// Must be >= Constants.MIN_VP_COMMISSION_BPS (1) and < 10000
// Individual VPs set their own commission in [MIN_VP_COMMISSION_BPS, this cap] during registration and
// commission updates
uint16 maxVpCommissionBps;
// ------------- Atomic Swap Timing Parameters (in BTC blocks) -------------
/// @notice Refund timelock for atomic swap pre-pegin transaction (in BTC blocks)
/// @dev After this many BTC blocks, the depositor can reclaim funds if the swap was not completed
uint32 tRefund;
/// @notice Staleness threshold for pre-pegin transactions (in BTC blocks)
/// @dev Pre-pegin transactions older than this are considered stale and should be rejected by off-chain actors
uint32 tStale;
/// @notice Minimum fee rate for pegin transactions (in sat/vB)
/// @dev Off-chain actors validate that the pegin tx meets this minimum fee rate before ACKing
uint64 minPeginFeeRate;
// ------------- Prover Circuit Version -------------
/// @notice Prover circuit version matching the prover CircuitVersion enum
/// @dev Identifies which prover circuit (universal SP1 ELF set) to use for this parameter set
uint16 proverCircuitVersion;
/// @notice Minimum number of BTC confirmations required for a Pre-PegIn transaction before ACK signing
/// @dev Off-chain actors (VP, VK, UC) must wait for this many confirmations before signing ACKs
uint32 minPrepeginDepth;
}
// ========== Events ==========
/// @notice Emitted once when a circuit version's verifier and checkpoint are approved
/// @param circuitVersion The nonzero on-chain circuit version
/// @param pegoutCircuitVkHash Outer peg-out SP1 VK hash in bytes32() form
/// @param trustedCheckpoint Approved bootstrap beacon block root
event ProverInfoRegistered(uint16 indexed circuitVersion, bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint);
/// @notice Emitted when a new version of offchain parameters is added
/// @param version The version number
/// @param params The offchain parameters for this version
event OffchainParamsVersionAdded(uint16 indexed version, VersionedOffchainParams params);
/// @notice Emitted when a new version of universal challengers is added
/// @param version The version number
/// @param challengers Array of universal challengers for this version
event UniversalChallengersVersionAdded(uint256 indexed version, BTCVaultTypes.AddressBTCKeyPair[] challengers);
/// @notice Emitted when protocol parameters are updated
/// @param params The updated protocol parameters
event ProtocolParamsUpdated(IProtocolParams.TBVProtocolParams params);
/// @notice Emitted when the active vault Core version changes
/// @param previousVersion The previously active Core version (0 at initialization)
/// @param newVersion The newly active Core version
event ActiveVaultCoreVersionUpdated(uint16 indexed previousVersion, uint16 indexed newVersion);
/// @notice Emitted when a UC appends an operation-BTC-key version
event OperationBtcKeyVersionAdded(address indexed ucAdmin, uint16 indexed version, bytes32 opBtcKey, uint64 epoch);
/// @notice Emitted when a UC appends an operation-ETH-key version
event OperationEthKeyVersionAdded(address indexed ucAdmin, uint16 indexed version, address opEthKey, uint64 epoch);
// ========== Universal Challengers Functions ==========
/// @notice Add a new version of universal challengers
/// @param challengers Array of universal challenger roster registrations for this version
/// @dev Auto-increments the version number
function addUniversalChallengersVersion(BTCVaultTypes.AddressBTCKeyPair[] calldata challengers) external;
/// @notice Get the latest universal challengers version number
/// @return The latest version number
function latestUniversalChallengersVersion() external view returns (uint16);
/// @notice Get universal challengers for a specific roster version
/// @param versionNumber The version number
/// @return Array of universal challengers for the specified version
/// @dev The version axis is roster membership, not key rotation; each pair's `btcPubKey` is
/// the member's genesis roster key. Resolve keys per member via
/// `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `ucKeyEpochCurrent`).
function getUniversalChallengersByVersion(uint16 versionNumber)
external
view
returns (BTCVaultTypes.AddressBTCKeyPair[] memory);
/// @notice Get the current active universal challengers
/// @return Array of current universal challengers
/// @dev Current in roster membership only; each pair's `btcPubKey` is the member's genesis
/// roster key. Resolve keys per member via
/// `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `ucKeyEpochCurrent`).
function getCurrentUniversalChallengers() external view returns (BTCVaultTypes.AddressBTCKeyPair[] memory);
// ========== UC Operation Key Functions ==========
/// @notice Global UC operation-key epoch counter
function ucKeyEpochCurrent() external view returns (uint64);
/// @notice Latest UC operation-BTC-key version (0 = genesis)
function latestOperationBtcKeyVersion(address ucAdmin) external view returns (uint16);
/// @notice UC operation-BTC-key by version (v0 = genesis op key)
function getOperationBtcKeyByVersion(address ucAdmin, uint16 version) external view returns (bytes32);
/// @notice Current UC operation-BTC-key (latest version, or genesis when unrotated)
function getCurrentOperationBtcKey(address ucAdmin) external view returns (bytes32);
/// @notice Latest UC operation-ETH-key version (0 = admin default)
function latestOperationEthKeyVersion(address ucAdmin) external view returns (uint16);
/// @notice UC operation-ETH-key by version (v0 = ucAdmin)
function getOperationEthKeyByVersion(address ucAdmin, uint16 version) external view returns (address);
/// @notice Current UC operation-ETH-key (latest version, or admin when unrotated)
function getCurrentOperationEthKey(address ucAdmin) external view returns (address);
/// @notice Append a new UC operation BTC key version (admin-gated, new-key self-PoP)
function setOperationBtcKey(bytes32 newOpBtcKey, bytes calldata btcPopSignature) external;
/// @notice Append a new UC operation ETH (relay/ACK) key version (admin-gated, new-key self-PoP)
function setOperationEthKey(address newOpEthKey, bytes calldata ethPopSignature) external;
/// @notice UC op-BTC key bonded to a vault's ucKeyEpoch (v0 = genesis op key)
function getOperationBtcKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (bytes32);
/// @notice UC op-BTC key bonded to a vault's ucKeyEpoch against an explicit roster-version genesis:
/// latest op-key version whose epoch <= bonded epoch, else `rosterGenesisKey`
/// @dev The caller supplies the UC's key from the vault's FROZEN membership version as the v0
/// genesis. Correct even if the UC rotated across versions or was later dropped from the roster.
function getOperationBtcKeyAtEpochOrGenesis(address ucAdmin, uint64 epoch, bytes32 rosterGenesisKey)
external
view
returns (bytes32);
/// @notice UC op-ETH key bonded to a vault's ucKeyEpoch (v0 = ucAdmin)
function getOperationEthKeyAtEpoch(address ucAdmin, uint64 epoch) external view returns (address);
// ========== Prover Info ==========
/// @notice Register the approved verifier and checkpoint for a circuit version
/// @dev Admin-only, set-once. Required for offchain parameter updates, but does not gate PegIns.
/// @param circuitVersion Nonzero on-chain circuit version; must not already be registered
/// @param pegoutCircuitVkHash Nonzero approved outer peg-out SP1 VK hash; no cryptographic validation
/// @param trustedCheckpoint Nonzero bootstrap beacon block root; zero is reserved for unregistered versions
function registerProverInfo(uint16 circuitVersion, bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint) external;
/// @notice Get the approved verifier inputs; unregistered versions return zeros
/// @param circuitVersion Version from the vault's frozen offchain parameters, not the latest params
/// @return pegoutCircuitVkHash Outer peg-out SP1 VK hash in bytes32() form
/// @return trustedCheckpoint Approved bootstrap beacon block root, or zero if unregistered
function getProverInfo(uint16 circuitVersion)
external
view
returns (bytes32 pegoutCircuitVkHash, bytes32 trustedCheckpoint);
// ========== Offchain Parameters Functions ==========
/// @notice Add a new version of offchain parameters
/// @dev Requires registered prover info for proverCircuitVersion, whether higher, equal, or lower.
/// @dev Auto-increments the version number; each parameter set is immutable.
/// @param params The offchain parameters for this version
function addOffchainParamsVersion(VersionedOffchainParams calldata params) external;
/// @notice Get the latest offchain parameters version number
/// @return The latest version number
function latestOffchainParamsVersion() external view returns (uint16);
/// @notice Get offchain parameters for a specific version
/// @param versionNumber The version number
/// @return The offchain parameters for the specified version
function getOffchainParamsByVersion(uint16 versionNumber) external view returns (VersionedOffchainParams memory);
/// @notice Get the latest offchain parameters
/// @return The latest offchain parameters
function getLatestOffchainParams() external view returns (VersionedOffchainParams memory);
// ========== Vault Core Version Functions ==========
/// @notice Get the currently active vault Core version (RFC 004)
/// @dev Stamped onto every new vault at peg-in submission
/// @return The active vault Core version
function activeVaultCoreVersion() external view returns (uint16);
/// @notice Set the active vault Core version (admin-only)
/// @dev Accepts upgrades and rollbacks; rejects 0 and the current version
/// @param newVersion The new active vault Core version
function setActiveVaultCoreVersion(uint16 newVersion) external;
// ========== Upgrade Functions ==========
/// @notice Get the contract version
/// @return Version string
function version() external pure returns (string memory);
function minimumPegInAmount() external view returns (uint256);
function maxPegInAmount() external view returns (uint256);
function pegInAckTimeout() external view returns (uint256);
function pegInActivationTimeout() external view returns (uint256);
function expiredPegInGraceBlocks() external view returns (uint256);
function peginActivationDelay() external view returns (uint256);
function getTBVProtocolParams() external view returns (TBVProtocolParams memory);
}
src/protocol/lib/BTCProofOfPossession.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import "./helpers/Secp256k1.sol";
import "./helpers/BIP340Utils.sol";
import "./helpers/BIP322Utils.sol";
/**
* @title BTCProofOfPossession
* @notice Library for verifying Bitcoin BIP-322 proof of possession signatures
* @dev Verifies that a BTC private key signed a message containing an Ethereum
* address hex representation to prove ownership
* @dev BIP-322 verification supports P2WPKH (using ECDSA) and P2TR key-path
* (using Schnorr) address types
* @dev This library is deployed as an EXTERNAL library to reduce contract size
*/
library BTCProofOfPossession {
// ========== CONSTANTS ==========
/// @notice Action constants for PoP signature context
bytes32 internal constant ACTION_REGISTER = keccak256("register");
/// @notice Action constant for declaring/rotating an operation BTC key
bytes32 internal constant ACTION_SET_OPERATION_BTC_KEY = keccak256("set_operation_btc_key");
/// @notice Minimum valid BIP-322 PoP signature length (P2TR with
/// SIGHASH_DEFAULT: 1 count + 1 length + 64 sig)
uint256 internal constant MIN_POP_SIGNATURE_LENGTH = 66;
/// @notice Maximum valid BIP-322 PoP signature length (P2WPKH: 1 count +
/// 1 sigLen + 73 DER+sighash + 1 pkLen + 33 pk)
uint256 internal constant MAX_POP_SIGNATURE_LENGTH = 109;
// ========== ERRORS ==========
/// @notice Error for invalid BTC PoP signature length
error InvalidBTCPopSignatureLength(uint256 length, uint256 minLength, uint256 maxLength);
/// @notice Error for invalid action string
error InvalidAction(bytes32 action);
/// @notice Error for public key mismatch
error PublicKeyMismatch(bytes32 expected, bytes32 actual);
/// @notice Error for invalid S value (not normalized)
error InvalidSValue(bytes32 s);
/// @notice Error for unsupported address type
error UnsupportedAddressType(uint8 witnessItemCount);
/// @notice Error for invalid BIP-322 signature
error InvalidBIP322Signature(uint256 offset, uint256 length);
/// @notice Error for invalid witness data
error InvalidWitnessData(uint256 offset, uint256 expected, uint256 actual);
// ========== EXTERNAL FUNCTIONS ==========
/**
* @notice Verify a BIP-322 proof of possession
* @dev Verifies that the BTC private key corresponding to bip340PubKeyX
* signed the owner address
* @dev Includes chain ID, action, and verifying contract address to prevent
* cross-chain, cross-context, and cross-contract replay attacks
* @dev Message format:
* "0x<address>:<chainId>:<action>:<verifying_contract>"
* @dev Both address and verifying_contract are lowercase hex strings
* @dev BIP-322 signatures are witness-encoded and must be between 66 and
* 109 bytes
* @param signature The BIP-322 witness-encoded signature
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param owner The Ethereum address that was in the signed message
* @param action The action context for the signature
* @return True if the signature is valid
*/
function verify(bytes memory signature, bytes32 bip340PubKeyX, address owner, bytes32 action)
external
view
returns (bool)
{
if (action != ACTION_REGISTER) {
revert InvalidAction(action);
}
bytes memory message = buildMessage(owner, block.chainid, action, address(this));
if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
}
return verify(signature, bip340PubKeyX, message);
}
/**
* @notice Verify a BIP-322 proof of possession bound to an extra payload
* @dev Message format:
* "0x<address>:<chainId>:<action>:<verifying_contract>:<payload_hex>"
* Lowercase hex for address, verifying_contract and payload.
* @dev The payload is included in the signed message, so an attacker
* cannot replay a signature with a different payload.
* @param signature The BIP-322 witness-encoded signature
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param owner The Ethereum address that was in the signed message
* @param action The action context (ACTION_SET_OPERATION_BTC_KEY)
* @param payload Arbitrary payload bytes bound into the signed message
* @return True if the signature is valid
*/
function verifyWithPayload(
bytes memory signature,
bytes32 bip340PubKeyX,
address owner,
bytes32 action,
bytes memory payload
) external view returns (bool) {
if (action != ACTION_SET_OPERATION_BTC_KEY) {
revert InvalidAction(action);
}
bytes memory message = buildMessageWithPayload(owner, block.chainid, action, address(this), payload);
if (signature.length < MIN_POP_SIGNATURE_LENGTH || signature.length > MAX_POP_SIGNATURE_LENGTH) {
revert InvalidBTCPopSignatureLength(signature.length, MIN_POP_SIGNATURE_LENGTH, MAX_POP_SIGNATURE_LENGTH);
}
return verify(signature, bip340PubKeyX, message);
}
// ========== INTERNAL FUNCTIONS ==========
/**
* @notice Verify BIP-322 proof of possession signature
* @dev Detects address type from witness structure
* - P2TR key-path: 1 witness item (Schnorr signature)
* - P2WPKH: 2 witness items (ECDSA signature + compressed public key)
* @param signature The BIP-322 simple signature bytes (witness data)
* @param bip340PubKeyX The 32-byte BIP-340 x-only public key to verify
* against
* @param message The message that was signed
* @return True if the signature is valid and matches the public key
*/
function verify(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message) internal pure returns (bool) {
if (signature.length == 0 || message.length == 0) {
revert InvalidBIP322Signature(signature.length, message.length);
}
if (signature.length < 2) {
revert InvalidWitnessData(0, 2, signature.length);
}
uint8 witnessItemCount = uint8(signature[0]);
if (witnessItemCount == 1) {
return verifyBIP322P2TR(signature, bip340PubKeyX, message);
}
if (witnessItemCount == 2) {
return verifyBIP322P2WPKH(signature, bip340PubKeyX, message);
}
revert UnsupportedAddressType(witnessItemCount);
}
/**
* @notice Verify BIP-322 signature for P2TR (Taproot) address with key-path spending
* @dev Uses BIP-340 Schnorr signature verification with tweaked output key
* @dev Accepts both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
* @param signature The witness data containing the Schnorr signature
* @param bip340PubKeyX The x-only internal public key
* @param message The message that was signed
* @return True if verification succeeds
*/
function verifyBIP322P2TR(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
internal
pure
returns (bool)
{
uint8 witnessItemCount = uint8(signature[0]);
if (witnessItemCount != 1) {
revert InvalidWitnessData(0, 1, witnessItemCount);
}
uint8 sigLength = uint8(signature[1]);
if (sigLength != 64 && sigLength != 65) {
revert InvalidWitnessData(1, 64, sigLength);
}
// Canonical BIP-322 P2TR witness is exactly 2 + sigLength bytes
// (1 witnessItemCount + 1 sigLength + sigLength). Trailing bytes
// are rejected to prevent proof malleability.
if (signature.length != 2 + uint256(sigLength)) {
revert InvalidWitnessData(0, 2 + uint256(sigLength), signature.length);
}
uint8 hashType = 0x00;
if (sigLength == 65) {
hashType = uint8(signature[66]);
if (hashType != 0x01) {
revert InvalidWitnessData(66, 0x01, hashType);
}
}
bytes32 r;
bytes32 s;
assembly {
r := mload(add(signature, 34))
s := mload(add(signature, 66))
}
bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2TR(message, bip340PubKeyX, hashType);
bytes32 tweakedPubKeyX = BIP322Utils.taprootTweakPubKey(bip340PubKeyX);
bool valid = BIP340Utils.verify(uint256(tweakedPubKeyX), uint256(r), uint256(s), msgHash);
if (!valid) {
revert InvalidBIP322Signature(2, sigLength);
}
return true;
}
/**
* @notice Verify BIP-322 signature for P2WPKH (SegWit) address
* @dev Uses ECDSA signature verification and recovers the public key
* @param signature The witness data containing ECDSA signature and public key
* @param bip340PubKeyX The x-only public key to verify against
* @param message The message that was signed
* @return True if verification succeeds
*/
function verifyBIP322P2WPKH(bytes memory signature, bytes32 bip340PubKeyX, bytes memory message)
internal
pure
returns (bool)
{
(bytes32 r, bytes32 s, bytes memory compressedPubKey) = parseP2WPKHWitnessWithPubKey(signature);
bytes32 pubKeyX;
assembly {
let dataStart := add(compressedPubKey, 32)
pubKeyX := mload(add(dataStart, 1))
}
if (pubKeyX != bip340PubKeyX) {
revert PublicKeyMismatch(bip340PubKeyX, pubKeyX);
}
if (!Secp256k1.isNormalizedSignature(s)) {
revert InvalidSValue(s);
}
bytes32 msgHash = BIP322Utils.calculateBIP322SigHashP2WPKH(message, compressedPubKey);
return verifyECDSARecoveryWithCompressedKey(msgHash, r, s, compressedPubKey);
}
function parseP2WPKHWitnessWithPubKey(bytes memory signature)
internal
pure
returns (bytes32 r, bytes32 s, bytes memory compressedPubKey)
{
// For P2WPKH, witness contains: [signature, pubkey]
// BIP-322 witness format: [num_items, sig_length, signature, pubkey_length, pubkey]
if (uint8(signature[0]) != 2) {
revert InvalidWitnessData(0, 2, uint8(signature[0]));
}
uint8 sigLength = uint8(signature[1]);
// Canonical P2WPKH witness is exactly 2 (header) + sigLength
// (DER+sighash) + 1 (pubkey length byte) + 33 (compressed pubkey)
// bytes. The sigLength floor of 9 corresponds to the shortest
// canonical ECDSA DER signature (0x30 0x06 0x02 0x01 <r> 0x02 0x01
// <s>) plus the sighash byte. Reject non-canonical lengths to
// prevent witness malleability.
if (sigLength < 9 || signature.length != uint256(sigLength) + 36) {
revert InvalidWitnessData(1, uint256(sigLength) + 36, signature.length);
}
uint256 offset = 2;
// The signature must use the SIGHASH_ALL (0x01) flag at the end
uint8 lastByte = uint8(signature[offset + sigLength - 1]);
if (lastByte != 0x01) {
revert InvalidWitnessData(offset + sigLength - 1, 0x01, lastByte);
}
uint8 derLength = sigLength - 1;
// Parse DER signature
(r, s) = parseDERSignature(signature, offset, derLength);
offset += sigLength;
// Extract public key
if (uint8(signature[offset]) != 33) {
revert InvalidWitnessData(offset, 33, uint8(signature[offset]));
}
offset++;
// Get compressed public key (33 bytes) - optimized with assembly
compressedPubKey = new bytes(33);
assembly {
let src := add(add(signature, 32), offset)
let dst := add(compressedPubKey, 32)
// Copy bytes 0..31 of the compressed pubkey
// (= signature[offset .. offset+32)).
mstore(dst, mload(src))
// Copy byte 32 only. mload at src+1 reads
// signature[offset+1 .. offset+33), whose low byte
// (selected via byte(31, _)) is signature[offset+32].
// mstore8 writes a single byte, keeping the destination
// write strictly within the 33-byte buffer. Previously
// a second `mstore` at src+32 read 32 bytes past the
// signature tail and wrote 32 bytes past compressedPubKey.
mstore8(add(dst, 32), byte(31, mload(add(src, 1))))
}
return (r, s, compressedPubKey);
}
function verifyECDSARecoveryWithCompressedKey(bytes32 msgHash, bytes32 r, bytes32 s, bytes memory compressedPubKey)
internal
pure
returns (bool)
{
require(compressedPubKey.length == 33, "Invalid compressed key length");
bytes32 expectedPubKeyX;
assembly {
let dataStart := add(compressedPubKey, 32)
expectedPubKeyX := mload(add(dataStart, 1))
}
uint8 prefix = uint8(compressedPubKey[0]);
require(prefix == 0x02 || prefix == 0x03, "Invalid compressed key prefix");
uint8 expectedYParity = prefix - 0x02;
for (uint8 v = 27; v <= 28; v++) {
uint8 recoveryId = v - 27;
(uint256 recoveredX, uint256 recoveredY) =
Secp256k1.recover(uint256(msgHash), recoveryId, uint256(r), uint256(s));
if (recoveredX != 0 && recoveredY != 0) {
if (bytes32(recoveredX) == expectedPubKeyX) {
uint8 recoveredYParity = uint8(recoveredY & 1);
if (recoveredYParity == expectedYParity) {
return true;
}
}
}
}
revert InvalidBIP322Signature(0, 64);
}
function buildMessage(address owner, uint256 chainId, bytes32 action, address verifyingContract)
private
pure
returns (bytes memory)
{
string memory actionString;
if (action == ACTION_REGISTER) {
actionString = "register";
} else if (action == ACTION_SET_OPERATION_BTC_KEY) {
actionString = "set_operation_btc_key";
} else {
revert InvalidAction(action);
}
return abi.encodePacked(
addressToHex(owner), ":", uintToBytes(chainId), ":", actionString, ":", addressToHex(verifyingContract)
);
}
/// @notice Encode the high 16 bytes of `data` as 32 lowercase ASCII hex
/// characters using SWAR (SIMD-within-a-register) nibble expansion.
/// @dev Adapted from Mikhail Vladimirov's toHex16. The final correction term
/// uses `* 39` (0x27) instead of the original `* 7`: `* 7` maps nibbles
/// >= 10 to uppercase A-F, `* 39` maps them to lowercase a-f, which is the
/// casing the signed proof-of-possession message requires.
/// @param data The 16 bytes to encode (held in the high half of the value)
/// @return result 32 bytes, each an ASCII hex character for one input nibble
function _toHex16(bytes16 data) internal pure returns (bytes32 result) {
result = (bytes32(data) & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000)
| (bytes32(data) & 0x0000000000000000FFFFFFFFFFFFFFFF00000000000000000000000000000000) >> 64;
result = (result & 0xFFFFFFFF000000000000000000000000FFFFFFFF000000000000000000000000)
| (result & 0x00000000FFFFFFFF000000000000000000000000FFFFFFFF0000000000000000) >> 32;
result = (result & 0xFFFF000000000000FFFF000000000000FFFF000000000000FFFF000000000000)
| (result & 0x0000FFFF000000000000FFFF000000000000FFFF000000000000FFFF00000000) >> 16;
result = (result & 0xFF000000FF000000FF000000FF000000FF000000FF000000FF000000FF000000)
| (result & 0x00FF000000FF000000FF000000FF000000FF000000FF000000FF000000FF0000) >> 8;
result = (result & 0xF000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000) >> 4
| (result & 0x0F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F00) >> 8;
result = bytes32(
0x3030303030303030303030303030303030303030303030303030303030303030 + uint256(result)
+ (((uint256(result) + 0x0606060606060606060606060606060606060606060606060606060606060606) >> 4)
& 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F) * 39
);
}
function buildMessageWithPayload(
address owner,
uint256 chainId,
bytes32 action,
address verifyingContract,
bytes memory payload
) private pure returns (bytes memory) {
return abi.encodePacked(buildMessage(owner, chainId, action, verifyingContract), ":", bytesToHex(payload));
}
/// @notice Lowercase hex-encode arbitrary-length bytes, without a `0x` prefix
/// @dev Full 16-byte chunks are encoded with `_toHex16` and written in a single MSTORE; a
/// trailing 1..15-byte chunk is encoded then copied char-by-char so the write stays within
/// `result`. Optimized form from #507 (audit follow-up); equivalent to the naive loop.
function bytesToHex(bytes memory data) internal pure returns (bytes memory) {
uint256 len = data.length;
bytes memory result = new bytes(len * 2);
uint256 offset;
while (offset + 16 <= len) {
bytes16 chunk;
assembly {
// Load data[offset..offset+16) into the high half of `chunk` and zero the low half.
// MLOAD reads 32 bytes; bytes [offset+16, offset+32) may extend past the data
// contents into adjacent allocated memory, so they are masked off here.
chunk := and(
mload(add(add(data, 0x20), offset)),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
)
}
bytes32 hexed = _toHex16(chunk);
assembly {
// offset + 16 <= len, so this 32-byte write stays within result.
mstore(add(add(result, 0x20), mul(offset, 2)), hexed)
}
offset += 16;
}
if (offset < len) {
bytes16 chunk;
assembly {
chunk := and(
mload(add(add(data, 0x20), offset)),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000
)
}
bytes32 hexed = _toHex16(chunk);
uint256 tailChars = (len - offset) * 2;
for (uint256 j = 0; j < tailChars; j++) {
result[offset * 2 + j] = hexed[j];
}
}
return result;
}
/// @notice Lowercase hex-encode a 20-byte address with a `0x` prefix
/// @dev The address is left-aligned into a word; the first 16 bytes encode to
/// 32 chars and bytes 16..19 to the leading 8 chars of the second half
/// (the remaining chars encode the zero padding and are dropped).
function addressToHex(address addr) internal pure returns (bytes memory) {
bytes32 word = bytes32(bytes20(addr));
return abi.encodePacked("0x", _toHex16(bytes16(word)), bytes8(_toHex16(bytes16(word << 128))));
}
function uintToBytes(uint256 value) private pure returns (bytes memory) {
if (value == 0) return "0";
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits;
while (value != 0) {
index--;
buffer[index] = bytes1(uint8(48 + value % 10));
value /= 10;
}
return buffer;
}
function parseDERSignature(bytes memory data, uint256 offset, uint256 length)
private
pure
returns (bytes32 r, bytes32 s)
{
// Minimum valid DER: 0x30 LEN 0x02 0x01 <r> 0x02 0x01 <s> = 8 bytes
if (length < 8 || data[offset] != 0x30) {
revert InvalidBIP322Signature(offset, length);
}
// BIP-66: outer SEQUENCE length must cover the remaining bytes exactly.
// Rejects trailing garbage and length-field/content disagreement.
if (uint8(data[offset + 1]) != length - 2) {
revert InvalidBIP322Signature(offset + 1, length);
}
uint256 end = offset + length;
uint256 pos = offset + 2;
(r, pos) = parseDERInteger(data, pos, end);
(s, pos) = parseDERInteger(data, pos, end);
if (pos != end) {
revert InvalidBIP322Signature(pos, end);
}
return (r, s);
}
/**
* @notice Parse a single BIP-66 canonical DER INTEGER into a bytes32 value
* @dev Enforces minimal encoding: rejects non-canonical leading 0x00 bytes
* and rejects high-bit-set first bytes (negative-integer encoding)
* @param data The buffer containing the DER-encoded signature
* @param pos The offset of the INTEGER tag within `data`
* @param end The exclusive upper bound within which the integer must fit
* @return value The integer left-padded into a bytes32 (big-endian)
* @return newPos The offset immediately after the parsed integer
*/
function parseDERInteger(bytes memory data, uint256 pos, uint256 end)
private
pure
returns (bytes32 value, uint256 newPos)
{
// INTEGER tag + length byte must fit within the remaining bytes
if (pos + 2 > end || data[pos] != 0x02) {
revert InvalidBIP322Signature(pos, end);
}
pos++;
uint8 intLength = uint8(data[pos]);
pos++;
// secp256k1 scalars fit in 32 bytes; canonical DER allows up to 33
// bytes when a leading 0x00 padding is required. Length 0 is invalid.
if (intLength == 0 || intLength > 33 || pos + intLength > end) {
revert InvalidBIP322Signature(pos, intLength);
}
uint8 firstByte = uint8(data[pos]);
// High bit set on the first byte would encode a negative integer.
// BIP-66 requires ECDSA scalars to be encoded as positive integers.
if (firstByte & 0x80 != 0) {
revert InvalidBIP322Signature(pos, intLength);
}
// A 33-byte encoding is only canonical when it is exactly 0x00 padding
// of a 32-byte value whose high bit is set. Any other 33-byte content
// would represent a scalar >= 2**256, which is out of range.
if (intLength == 33 && firstByte != 0x00) {
revert InvalidBIP322Signature(pos, intLength);
}
// A leading 0x00 byte is only canonical when it is strictly required
// to keep the integer positive (next byte has its high bit set).
// Rejecting redundant 0x00 padding enforces BIP-66 signature
// malleability resistance.
if (intLength > 1 && firstByte == 0x00 && uint8(data[pos + 1]) & 0x80 == 0) {
revert InvalidBIP322Signature(pos, intLength);
}
uint256 valueStart = pos;
uint8 valueLen = intLength;
if (intLength == 33) {
// Strip the mandatory 0x00 padding; the scalar fits in 32 bytes.
valueStart++;
valueLen = 32;
}
value = bytesToBytes32(data, valueStart, valueLen);
newPos = pos + intLength;
}
function bytesToBytes32(bytes memory data, uint256 offset, uint256 length) private pure returns (bytes32 result) {
require(length <= 32, "Length exceeds 32 bytes");
// Defense-in-depth: callers within this library already enforce
// offset + length <= data.length, but checking it at the unsafe-assembly
// boundary localizes the safety property and guards against future
// callers that might violate the invariant.
require(offset + length <= data.length, "Out of bounds");
assembly {
result := mload(add(add(data, 32), offset))
if lt(length, 32) { result := shr(mul(sub(32, length), 8), result) }
}
return result;
}
}
src/protocol/lib/EthProofOfPossession.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {ECDSA} from "../../../lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "../../../lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol";
/// @title EthProofOfPossession
/// @notice Self-proof-of-possession for operation-ETH keys. A participant declaring an
/// operation-ETH key — rotating post-registration or bootstrapping one at registration —
/// must present an EIP-191 signature produced by the NEW key over a message bound to the
/// action, the new key, the admin (caller), and this contract + chain.
/// @dev The op-ETH key is the ACK signer; ACK tracking and the all-ACKed completion check key on the
/// recovered op-ETH address. Without this proof an admin could rotate onto an address it does
/// not control — e.g. another participant's op-ETH — so a single signature from that address
/// would satisfy two required ACK slots. Requiring the new key to sign makes that impossible:
/// only the holder of the private key can produce a signature that recovers to the address.
/// `address(this)` + `block.chainid` scope the proof to this registry and chain; `caller` scopes
/// it to the rotating admin; `payload` carries any role-specific binding (e.g. the app entry
/// point for keepers). Mirrors `BTCProofOfPossession.ACTION_SET_OPERATION_BTC_KEY`.
library EthProofOfPossession {
/// @notice Action tag for the operation-ETH-key rotation proof, mirroring the BTC PoP action
bytes32 public constant ACTION_SET_OPERATION_ETH_KEY = keccak256("set_operation_eth_key");
/// @notice Verify that `newOpEthKey` signed the rotation message bound to `caller` and `payload`
/// @param newOpEthKey The operation-ETH key being set; the recovered signer must equal it
/// @param caller The participant admin the key will serve (the rotating admin, or the
/// registrant / listed keeper admin when the key is bootstrapped at registration)
/// @param payload Role-specific binding bytes (empty for VP/UC, the app entry point for VK)
/// @param signature The EIP-191 signature produced by `newOpEthKey`
/// @return True if the signature recovers to `newOpEthKey`
function verify(address newOpEthKey, address caller, bytes memory payload, bytes memory signature)
internal
view
returns (bool)
{
bytes32 messageHash = keccak256(
abi.encodePacked(ACTION_SET_OPERATION_ETH_KEY, newOpEthKey, caller, address(this), block.chainid, payload)
);
bytes32 ethSignedHash = MessageHashUtils.toEthSignedMessageHash(messageHash);
return ECDSA.recover(ethSignedHash, signature) == newOpEthKey;
}
}
src/protocol/lib/OpKeyVersionSearch.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {BTCVaultRegistryTypes} from "./types/BTCVaultRegistryTypes.sol";
/// @title OpKeyVersionSearch
/// @notice Binary search over a participant's append-only operation-key / payout version history to
/// resolve the version bonded at a given epoch in O(log n) rather than O(n).
/// @dev Correctness relies on the append-only invariant that, within a single participant's history,
/// the stored `epoch` is STRICTLY INCREASING with the version index: every append stamps a
/// freshly-bumped registry epoch onto `version = latest + 1`, and versions are contiguous
/// `1..latest` with no gaps. So "the latest version whose epoch <= target" is a monotonic
/// predicate and can be found by binary search.
///
/// This replaces a linear newest->oldest scan, which is a DoS vector: the walk length equals the
/// number of rotations a participant made AFTER a vault was bonded, and the participant controls
/// its own rotation count. Enough rotations make a vault's redeem / ACK / signature-verify walk
/// exceed the block gas limit, permanently locking that vault (and its consumed application caps)
/// — a griefing vector against depositors bonded to a compromised participant. Binary search
/// bounds the work at `ceil(log2(latest)) <= 16` reads (version is `uint16`), independent of the
/// rotation count. Result is byte-identical to the linear scan.
/// Returns `0` when no stored version qualifies, so the caller falls back to the derived v0
/// (registration key / admin / BIP-86 default).
library OpKeyVersionSearch {
/// @notice Largest operation-BTC-key version in `[1, latest]` whose epoch <= `epoch`, else 0
function findAtEpoch(
mapping(uint16 => BTCVaultRegistryTypes.OpBtcKeyVersion) storage versions,
uint16 latest,
uint64 epoch
) internal view returns (uint16) {
uint256 lo = 1;
uint256 hi = latest;
uint256 found = 0;
while (lo <= hi) {
uint256 mid = (lo + hi) >> 1;
if (versions[uint16(mid)].epoch <= epoch) {
found = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return uint16(found);
}
/// @notice Largest operation-ETH-key version in `[1, latest]` whose epoch <= `epoch`, else 0
function findAtEpoch(
mapping(uint16 => BTCVaultRegistryTypes.OpEthKeyVersion) storage versions,
uint16 latest,
uint64 epoch
) internal view returns (uint16) {
uint256 lo = 1;
uint256 hi = latest;
uint256 found = 0;
while (lo <= hi) {
uint256 mid = (lo + hi) >> 1;
if (versions[uint16(mid)].epoch <= epoch) {
found = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return uint16(found);
}
/// @notice Largest payout-script version in `[1, latest]` whose epoch <= `epoch`, else 0
function findAtEpoch(
mapping(uint16 => BTCVaultRegistryTypes.PayoutScriptVersion) storage versions,
uint16 latest,
uint64 epoch
) internal view returns (uint16) {
uint256 lo = 1;
uint256 hi = latest;
uint256 found = 0;
while (lo <= hi) {
uint256 mid = (lo + hi) >> 1;
if (versions[uint16(mid)].epoch <= epoch) {
found = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return uint16(found);
}
}
src/protocol/lib/helpers/BIP322Utils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import {BIP341} from "../taproot/BIP341.sol";
/**
* @title BIP322Utils
* @notice Utility functions for BIP-322 signature verification
* @dev Implements BIP-322 transaction construction and sighash calculation
* @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0322.mediawiki
* @dev NOTE: for wallet compatibility SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
* for Taproot addresses; only SIGHASH_ALL is supported for P2WPKH addresses.
*/
library BIP322Utils {
/// @notice Maximum scriptPubKey length encodable as a single-byte Bitcoin
/// compact size. Values 0xFD-0xFF are reserved as multi-byte size
/// prefixes, so a 1-byte length cast is only canonical for lengths
/// 0..0xFC (= 252).
uint256 internal constant MAX_SINGLE_BYTE_COMPACT_SIZE = 252;
/// @notice Thrown when a scriptPubKey exceeds the single-byte compact-size
/// length encoding range used by buildToSpendTx and calculateTaprootSigHash.
error ScriptPubKeyTooLong();
/**
* @notice Compute the Taproot tweaked output key for key-path spending
* @dev For key-path only (no script tree), output_key = internal_key + hash("TapTweak" || internal_key) * G
* @dev Uses BIP341 library for standardized Taproot key tweaking
* @param internalPubKeyX The x-only internal public key
* @return The x-only tweaked output key
*/
function taprootTweakPubKey(bytes32 internalPubKeyX) internal pure returns (bytes32) {
// Use BIP341.computeOutputKey for key-path only spending (empty merkle root)
(bytes32 outputKey,) = BIP341.computeOutputKey(internalPubKeyX, "");
return outputKey;
}
/**
* @notice Calculate BIP-340 tagged hash for BIP-322
* @dev Implements: sha256(sha256(tag) || sha256(tag) || msg)
* @param message The message to hash
* @return The tagged hash
*/
function getBIP340TaggedHash(bytes memory message) internal pure returns (bytes32) {
bytes32 tagHash = sha256(abi.encodePacked("BIP0322-signed-message"));
return sha256(abi.encodePacked(tagHash, tagHash, message));
}
/**
* @notice Convert internal public key to P2TR scriptPubKey
* @param bip340PubKeyX The x-only internal public key
* @return The P2TR scriptPubKey
*/
function pubKeyToP2TRScriptPubKey(bytes32 bip340PubKeyX) internal pure returns (bytes memory) {
// P2TR: OP_1 OP_PUSHBYTES_32 <taproot_output_key>
// For key-path only spending (no script tree), we must use the TWEAKED output key
bytes32 tweakedOutputKey = taprootTweakPubKey(bip340PubKeyX);
return abi.encodePacked(uint8(0x51), uint8(0x20), tweakedOutputKey);
}
/**
* @notice Build to_spend transaction and return its txid
* @param messageHash The BIP-340 tagged hash of the message
* @param scriptPubKey The scriptPubKey for the output
* @return The transaction ID
*/
function buildToSpendTx(bytes32 messageHash, bytes memory scriptPubKey) internal pure returns (bytes32) {
if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();
// to_spend transaction structure per BIP-322:
// version: 4 bytes (0x00000000)
// input count: 1 byte (0x01)
// input:
// - txid: 32 bytes (0x00...00)
// - vout: 4 bytes (0xffffffff)
// - scriptSig: varint + OP_0 OP_PUSHBYTES_32 <messageHash>
// - sequence: 4 bytes (0x00000000)
// output count: 1 byte (0x01)
// output:
// - value: 8 bytes (0x0000000000000000)
// - scriptPubKey: varint + scriptPubKey
// locktime: 4 bytes (0x00000000)
bytes memory scriptSig = abi.encodePacked(uint8(0x00), uint8(0x20), messageHash);
uint8 scriptSigLen = uint8(scriptSig.length);
// NOTE: All integers must be in little-endian byte order per Bitcoin protocol
bytes memory btcTx = abi.encodePacked(
hex"00000000", // version
uint8(0x01), // input count
bytes32(0), // input txid (all zeros)
hex"ffffffff", // input vout (0xffffffff, LE)
scriptSigLen, // scriptSig length
scriptSig, // scriptSig
hex"00000000", // sequence
uint8(0x01), // output count
hex"0000000000000000", // output value
uint8(scriptPubKey.length), // scriptPubKey length
scriptPubKey, // scriptPubKey
hex"00000000" // locktime
);
// Return double SHA-256 (Bitcoin txid)
return sha256(abi.encodePacked(sha256(btcTx)));
}
/**
* @notice Calculate BIP-341 Taproot sighash for BIP-322 context
* @dev This function is specifically designed for BIP-322 signature verification
* @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
* @dev This is NOT a generic BIP-341 sighash implementation - use only for BIP-322 verification
* @dev with support for SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) for wallet compatibility
* @param toSpendTxid The txid being spent
* @param scriptPubKey The scriptPubKey being spent
* @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
* @return The sighash
*/
function calculateTaprootSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey, uint8 hashType)
internal
pure
returns (bytes32)
{
// BIP-341 signature message format (SIGHASH_ALL or SIGHASH_DEFAULT):
// epoch (1) + hash_type (1) + version (4) + locktime (4) +
// sha_prevouts (32) + sha_amounts (32) + sha_scriptpubkeys (32) + sha_sequences (32) + sha_outputs (32) +
// spend_type (1) + input_index (4)
//
// NOTE: SIGHASH_ALL (0x01) and SIGHASH_DEFAULT (0x00) commit to ALL prevouts
// NOTE: For BIP-322, we support both SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01)
// NOTE: BIP-341 requires compact size prefixes for scriptPubKey serialization in sha_scriptpubkeys
// NOTE: BIP-322 toSign transaction uses sequence 0
// Validate sighash type: only SIGHASH_DEFAULT (0x00) and SIGHASH_ALL (0x01) are supported
require(hashType == 0x00 || hashType == 0x01, "Invalid sighash type");
if (scriptPubKey.length > MAX_SINGLE_BYTE_COMPACT_SIZE) revert ScriptPubKeyTooLong();
bytes memory sigMsg = abi.encodePacked(
uint8(0x00), // epoch
hashType, // hash_type (SIGHASH_DEFAULT = 0x00 or SIGHASH_ALL = 0x01)
hex"00000000", // nVersion
hex"00000000", // nLockTime
sha256(abi.encodePacked(toSpendTxid, hex"00000000")), // sha_prevouts
sha256(abi.encodePacked(hex"0000000000000000")), // sha_amounts
sha256(abi.encodePacked(uint8(scriptPubKey.length), scriptPubKey)), // sha_scriptpubkeys (with compact size)
sha256(abi.encodePacked(hex"00000000")), // sha_sequences (sequence is 0)
sha256(abi.encodePacked(hex"0000000000000000", uint8(1), uint8(0x6a))), // sha_outputs (value || OP_RETURN)
uint8(0x00), // spend_type (key-path, no annex)
hex"00000000" // input_index (always 0)
);
// Return tagged hash "TapSighash"
bytes32 tagHash = sha256(abi.encodePacked("TapSighash"));
return sha256(abi.encodePacked(tagHash, tagHash, sigMsg));
}
/**
* @notice Calculate BIP-143 SegWit v0 sighash for P2WPKH in BIP-322 context
* @dev This function is specifically designed for BIP-322 signature verification
* @dev It makes BIP-322-specific assumptions about transaction structure (e.g., sequence = 0, OP_RETURN output)
* @dev This is NOT a generic BIP-143 sighash implementation - use only for BIP-322 verification
* @param toSpendTxid The txid being spent
* @param scriptPubKey The scriptPubKey being spent (P2WPKH witness program: OP_0 <20-byte-hash>)
* @return The sighash
*/
function calculateSegwitSigHash(bytes32 toSpendTxid, bytes memory scriptPubKey) internal pure returns (bytes32) {
// BIP-143 sighash for witness v0 (P2WPKH)
// https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
//
// IMPORTANT: For P2WPKH, the scriptCode is not the witness program itself,
// but a P2PKH-style script: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
// Extract the 20-byte hash from scriptPubKey (skip OP_0 and length byte)
// scriptPubKey format: [OP_0 (0x00)] [0x14] [20-byte-hash]
require(scriptPubKey.length == 22, "Invalid P2WPKH scriptPubKey length");
require(uint8(scriptPubKey[0]) == 0x00 && uint8(scriptPubKey[1]) == 0x14, "Invalid P2WPKH scriptPubKey format");
bytes20 pubKeyHash;
assembly {
pubKeyHash := mload(add(scriptPubKey, 34)) // 32 (length prefix) + 2 (OP_0 + 0x14)
}
// Build P2PKH-style scriptCode: OP_DUP OP_HASH160 <20-byte-hash> OP_EQUALVERIFY OP_CHECKSIG
bytes memory scriptCode = abi.encodePacked(
uint8(0x76), // OP_DUP
uint8(0xa9), // OP_HASH160
uint8(0x14), // Push 20 bytes
pubKeyHash,
uint8(0x88), // OP_EQUALVERIFY
uint8(0xac) // OP_CHECKSIG
);
// Build BIP-143 sighash in parts to avoid stack too deep
// NOTE: BIP-143 uses double SHA256 for hashPrevouts, hashSequence, and hashOutputs
// NOTE: All integers must be in little-endian byte order per Bitcoin protocol
bytes32 hashPrevouts = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
toSpendTxid,
hex"00000000" // outpoint index
)
)
)
);
bytes32 hashSequence = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
hex"00000000" // sequence
)
)
)
);
bytes32 hashOutputs = sha256(
abi.encodePacked(
sha256(
abi.encodePacked(
hex"0000000000000000", // value
uint8(1), // scriptPubKey length
uint8(0x6a) // OP_RETURN
)
)
)
);
bytes memory part1 = abi.encodePacked(
hex"00000000", // nVersion
hashPrevouts, // hashPrevouts (double SHA256)
hashSequence, // hashSequence (double SHA256)
toSpendTxid, // outpoint hash
hex"00000000", // outpoint index
uint8(scriptCode.length), // scriptCode length
scriptCode // scriptCode (P2PKH format)
);
bytes memory part2 = abi.encodePacked(
hex"0000000000000000", // value
hex"00000000", // nSequence
hashOutputs, // hashOutputs (double SHA256)
hex"00000000", // nLockTime
hex"01000000" // sighash type (SIGHASH_ALL = 1, LE)
);
bytes memory sigMsg = abi.encodePacked(part1, part2);
return sha256(abi.encodePacked(sha256(sigMsg)));
}
/**
* @notice Calculate BIP-322 sighash for P2TR address
* @param message The message being signed
* @param bip340PubKeyX The x-only public key
* @param hashType The sighash type (0x00 for SIGHASH_DEFAULT, 0x01 for SIGHASH_ALL)
* @return The sighash to verify
*/
function calculateBIP322SigHashP2TR(bytes memory message, bytes32 bip340PubKeyX, uint8 hashType)
internal
pure
returns (bytes32)
{
// Get the BIP-340 tagged hash of the message
bytes32 messageHash = getBIP340TaggedHash(message);
// Build the scriptPubKey from the public key
bytes memory scriptPubKey = pubKeyToP2TRScriptPubKey(bip340PubKeyX);
// Build to_spend transaction
bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);
// Calculate BIP-341 sighash for the to_sign transaction
return calculateTaprootSigHash(toSpendTxid, scriptPubKey, hashType);
}
/**
* @notice Calculate BIP-322 sighash for P2WPKH address using compressed public key
* @param message The message being signed
* @param compressedPubKey The 33-byte compressed public key from witness
* @return The sighash to verify
*/
function calculateBIP322SigHashP2WPKH(bytes memory message, bytes memory compressedPubKey)
internal
pure
returns (bytes32)
{
require(compressedPubKey.length == 33, "Invalid compressed public key length");
// Get the BIP-340 tagged hash of the message
bytes32 messageHash = getBIP340TaggedHash(message);
// Build the scriptPubKey from the compressed public key
// P2WPKH: OP_0 OP_PUSHBYTES_20 <HASH160(pubkey)>
bytes32 sha = sha256(compressedPubKey);
bytes20 hash160 = ripemd160(abi.encodePacked(sha));
bytes memory scriptPubKey = abi.encodePacked(uint8(0x00), uint8(0x14), hash160);
// Build to_spend transaction
bytes32 toSpendTxid = buildToSpendTx(messageHash, scriptPubKey);
// Calculate BIP-143 sighash for the to_sign transaction
return calculateSegwitSigHash(toSpendTxid, scriptPubKey);
}
}
src/protocol/lib/helpers/BIP340Utils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
import {Secp256k1} from "./Secp256k1.sol";
/**
* @title BIP340Utils
* @notice Library for BIP-340 Schnorr signature verification on secp256k1
* @dev Uses an ecrecover optimization technique for efficient verification
*/
// Based on https://hackmd.io/@nZ-twauPRISEa6G9zg3XRw/SyjJzSLt9
library BIP340Utils {
/**
* @notice Verify a BIP-340 Schnorr signature
* @dev Uses the ecrecover hack to verify a schnorr signature more efficiently
* @param px The x-coordinate of the public key
* @param rx The x-coordinate of the R point in the signature
* @param s The s value of the signature
* @param m The message hash
* @return True if the signature is valid
*/
function verify(uint256 px, uint256 rx, uint256 s, bytes32 m) public pure returns (bool) {
// Check pubkey, rx, and s are in-range.
if (px >= Secp256k1.P || rx >= Secp256k1.P || s >= Secp256k1.N) {
return false;
}
(address exp, bool ok) = convToFakeAddr(rx);
if (!ok) {
return false;
}
uint256 e = computeChallenge(bytes32(rx), bytes32(px), m);
bytes32 sp = bytes32(Secp256k1.N - mulmod(s, px, Secp256k1.N));
bytes32 ep = bytes32(Secp256k1.N - mulmod(e, px, Secp256k1.N));
// 27 apparently used to signal even parity (which it will always have).
address rvh = ecrecover(sp, 27, bytes32(px), ep);
return rvh == exp; // if recovery fails we fail anyways
}
/**
* @notice Compute BIP-340 challenge value
* @dev Computes e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n
* @param rx The x-coordinate of the R point as bytes32
* @param px The x-coordinate of the public key as bytes32
* @param m The message hash
* @return The challenge value modulo curve order
*/
function computeChallenge(bytes32 rx, bytes32 px, bytes32 m) internal pure returns (uint256) {
// Precomputed `sha256("BIP0340/challenge")`.
//
// Saves ~10k gas, mostly from byte shuffling to prepare the call.
//bytes32 tag = sha256("BIP0340/challenge");
bytes32 tag = 0x7bb52d7a9fef58323eb1bf7a407db382d2f3f2d81bb1224f49fe518f6d48d37c;
// Let e = int(hashBIP0340/challenge(bytes(r) || bytes(P) || m)) mod n.
return uint256(sha256(abi.encodePacked(tag, tag, rx, px, m))) % Secp256k1.N;
}
/**
* @notice Lift x-coordinate to full point on secp256k1 curve
* @dev Given an x coordinate, returns the y coordinate of an even point on the secp256k1 curve
* @param _x The x-coordinate to lift
* @return y The y-coordinate of the even point
* @return success True if the operation was successful
*/
function liftX(uint256 _x) internal pure returns (uint256, bool) {
uint256 _pp = Secp256k1.P;
uint256 _aa = Secp256k1.A;
uint256 _bb = Secp256k1.B;
if (_x >= _pp) {
return (0, false);
}
// Use EllipticCurve library to derive y-coordinate (0x02 for even y)
uint256 y = EllipticCurve.deriveY(0x02, _x, _aa, _bb, _pp);
if (!EllipticCurve.isOnCurve(_x, y, _aa, _bb, _pp)) {
return (0, false);
}
return (y, true);
}
/**
* @notice Convert Jacobian x-coordinate to affine coordinates
* @dev Internal function for doing the affine conversion for only the x coordinate
* @param _x The x-coordinate in Jacobian form
* @param _z The z-coordinate in Jacobian form
* @param _pp The prime modulus
* @return The x-coordinate in affine form
*/
function xToAffine(uint256 _x, uint256 _z, uint256 _pp) internal pure returns (uint256) {
uint256 zInv = EllipticCurve.invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
return mulmod(_x, zInv2, _pp);
}
/**
* @notice Convert BIP-340 public key x-coordinate to Ethereum address format
* @dev Converts a BIP340 pubkey X coord to what it would look like as an Ethereum address
* @param px The x-coordinate of the BIP-340 public key
* @return addr The pseudo-Ethereum address
* @return success True if the conversion was successful
*/
function convToFakeAddr(uint256 px) internal pure returns (address, bool) {
(uint256 py, bool ok) = liftX(px);
if (!ok) {
return (address(0), false);
}
bytes32 h = keccak256(abi.encodePacked(bytes32(px), bytes32(py)));
return (address(uint160(uint256(h))), true);
}
}
src/protocol/lib/helpers/CompactSize.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title CompactSize
* @notice Bitcoin CompactSize integer encoding/decoding utilities
* @dev Implements Bitcoin's variable-length integer format used in transaction serialization
* @dev Reference: https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
*/
library CompactSize {
error InvalidCompactSize(uint256 offset, uint8 prefix, uint64 value, uint64 minValue);
error BufferTooShort(uint256 offset, uint256 requiredLength, uint256 availableLength);
// ============ Encoding Functions ============
/**
* @notice Encode an integer as Bitcoin CompactSize format
* @param value The integer to encode (uint64)
* @return Encoded bytes in CompactSize format
* @dev Format:
* - value < 0xFD: [value] (1 byte)
* - value <= 0xFFFF: [0xFD][value as LE uint16] (3 bytes)
* - value <= 0xFFFFFFFF: [0xFE][value as LE uint32] (5 bytes)
* - value > 0xFFFFFFFF: [0xFF][value as LE uint64] (9 bytes)
*/
function encode(uint64 value) internal pure returns (bytes memory) {
if (value < 0xFD) {
// Single byte
return abi.encodePacked(uint8(value));
} else if (value <= 0xFFFF) {
// 0xFD + 2 bytes (little-endian uint16)
return abi.encodePacked(uint8(0xFD), uint8(value), uint8((value >> 8)));
} else if (value <= 0xFFFFFFFF) {
// 0xFE + 4 bytes (little-endian uint32)
return abi.encodePacked(
uint8(0xFE), uint8(value), uint8((value >> 8)), uint8((value >> 16)), uint8((value >> 24))
);
} else {
// 0xFF + 8 bytes (little-endian uint64)
return abi.encodePacked(
uint8(0xFF),
uint8(value),
uint8((value >> 8)),
uint8((value >> 16)),
uint8((value >> 24)),
uint8((value >> 32)),
uint8((value >> 40)),
uint8((value >> 48)),
uint8((value >> 56))
);
}
}
/**
* @notice Get the encoded length for a given value
* @param value The value to measure
* @return Length in bytes of the CompactSize encoding
*/
function encodedLength(uint64 value) internal pure returns (uint8) {
if (value < 0xFD) return 1;
if (value <= 0xFFFF) return 3;
if (value <= 0xFFFFFFFF) return 5;
return 9;
}
// ============ Decoding Functions ============
/**
* @notice Decode CompactSize integer from bytes
* @param data The bytes to decode from
* @param offset Starting position in the data
* @return value The decoded uint64 value
* @return newOffset Position immediately after the decoded CompactSize
* @dev Reverts if data is malformed or insufficient
*/
function decode(bytes memory data, uint256 offset) internal pure returns (uint64 value, uint256 newOffset) {
if (offset >= data.length) revert BufferTooShort(offset, offset + 1, data.length);
uint8 firstByte = uint8(data[offset]);
if (firstByte < 0xFD) {
// Single byte value
return (uint64(firstByte), offset + 1);
} else if (firstByte == 0xFD) {
// 2-byte value (uint16)
if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
value = readUint16LE(data, offset + 1);
if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD); // Non-canonical encoding
return (value, offset + 3);
} else if (firstByte == 0xFE) {
// 4-byte value (uint32)
if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
value = readUint32LE(data, offset + 1);
if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000); // Non-canonical encoding
return (value, offset + 5);
} else {
// 8-byte value (uint64)
if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
value = readUint64LE(data, offset + 1);
if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000); // Non-canonical encoding
return (value, offset + 9);
}
}
/**
* @notice Decode CompactSize from calldata
* @param data The calldata to decode from
* @param offset Starting position
* @return value The decoded uint64 value
* @return newOffset Position immediately after the decoded CompactSize
*/
function decodeCalldata(bytes calldata data, uint256 offset)
internal
pure
returns (uint64 value, uint256 newOffset)
{
if (offset >= data.length) {
revert BufferTooShort(offset, offset + 1, data.length);
}
uint8 firstByte = uint8(data[offset]);
if (firstByte < 0xFD) {
return (uint64(firstByte), offset + 1);
} else if (firstByte == 0xFD) {
if (offset + 3 > data.length) revert BufferTooShort(offset, offset + 3, data.length);
value = readUint16LECalldata(data, offset + 1);
if (value < 0xFD) revert InvalidCompactSize(offset, firstByte, value, 0xFD);
return (value, offset + 3);
} else if (firstByte == 0xFE) {
if (offset + 5 > data.length) revert BufferTooShort(offset, offset + 5, data.length);
value = readUint32LECalldata(data, offset + 1);
if (value <= 0xFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x10000);
return (value, offset + 5);
} else {
if (offset + 9 > data.length) revert BufferTooShort(offset, offset + 9, data.length);
value = readUint64LECalldata(data, offset + 1);
if (value <= 0xFFFFFFFF) revert InvalidCompactSize(offset, firstByte, value, 0x100000000);
return (value, offset + 9);
}
}
// ============ Little-Endian Reading Helpers ============
/**
* @notice Read little-endian uint16 from bytes
*/
function readUint16LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
}
/**
* @notice Read little-endian uint32 from bytes
*/
function readUint32LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
}
/**
* @notice Read little-endian uint64 from bytes
*/
function readUint64LE(bytes memory data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
| (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
| (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
}
/**
* @notice Read little-endian uint16 from calldata
*/
function readUint16LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8);
}
/**
* @notice Read little-endian uint32 from calldata
*/
function readUint32LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24);
}
/**
* @notice Read little-endian uint64 from calldata
*/
function readUint64LECalldata(bytes calldata data, uint256 offset) internal pure returns (uint64) {
return uint64(uint8(data[offset])) | (uint64(uint8(data[offset + 1])) << 8)
| (uint64(uint8(data[offset + 2])) << 16) | (uint64(uint8(data[offset + 3])) << 24)
| (uint64(uint8(data[offset + 4])) << 32) | (uint64(uint8(data[offset + 5])) << 40)
| (uint64(uint8(data[offset + 6])) << 48) | (uint64(uint8(data[offset + 7])) << 56);
}
}
src/protocol/lib/helpers/Secp256k1.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
/**
* @title Secp256k1 public key recovery Library
* @dev Library providing arithmetic operations to recover the signer public key EC point from secp256k1 signed messages in Solidity
*/
library Secp256k1 {
// Curve Constants (secp256k1)
uint256 internal constant A = 0;
uint256 internal constant B = 7;
uint256 internal constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 internal constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 internal constant P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 internal constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @notice secp256k1 curve order divided by 2 (for BIP-62 compliance)
bytes32 internal constant N_DIV_2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
/// @dev recovers signer public key point value.
/// @param digest hashed message
/// @param v recovery id (0 or 1)
/// @param r first 32 bytes of signature
/// @param s last 32 bytes of signature
/// @return (x, y) EC point coordinates of the recovered public key
function recover(uint256 digest, uint8 v, uint256 r, uint256 s) internal pure returns (uint256, uint256) {
// Validate scalar ranges and recovery id up front. We restrict v to
// {0, 1}, which means the standard ECDSA x = r + (v >> 1) * N (mod P)
// collapses to x = r. Since N < P and r >= N is rejected, r already
// satisfies r < P, so no further reduction is required.
if (r == 0 || r >= N || s == 0 || s >= N || v > 1) {
return (0, 0);
}
uint256 x = r;
uint256 rInv = EllipticCurve.invMod(r, N);
// v encodes the parity of y directly: 0 -> 0x02 (even), 1 -> 0x03 (odd).
uint256 y = EllipticCurve.deriveY(uint8(0x02 + v), x, A, B, P);
// deriveY returns a value for any x via the (p+1)/4 shortcut, even when
// x lives on the twist rather than secp256k1. Reject off-curve points so
// downstream arithmetic only operates on secp256k1 group elements.
if (!EllipticCurve.isOnCurve(x, y, A, B, P)) {
return (0, 0);
}
// Q = rInv * (s * R - digest * G)
// Compute s * R
(uint256 qx, uint256 qy, uint256 qz) = EllipticCurve.jacMul(mulmod(rInv, s, N), x, y, 1, A, P);
// Compute -digest * G
uint256 digestModN = digest % N;
(uint256 qx2, uint256 qy2, uint256 qz2) = EllipticCurve.jacMul(mulmod(rInv, N - digestModN, N), GX, GY, 1, A, P);
// Add the two points
(uint256 qx3, uint256 qy3, uint256 qz3) = EllipticCurve.jacAdd(qx, qy, qz, qx2, qy2, qz2, P);
return EllipticCurve.toAffine(qx3, qy3, qz3, P);
}
/**
* @notice Validate that a signature S value is normalized (BIP-62)
* @param s The s value from the signature
* @return True if s is in the lower half of the curve order
*/
function isNormalizedSignature(bytes32 s) internal pure returns (bool) {
return uint256(s) <= uint256(N_DIV_2);
}
}
src/protocol/lib/taproot/BIP341.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {EllipticCurve} from "../../../../lib/elliptic-curve-solidity/contracts/EllipticCurve.sol";
import {TaprootConstants} from "./TaprootConstants.sol";
import {CompactSize} from "../helpers/CompactSize.sol";
/**
* @title BIP341
* @notice BIP341 Taproot cryptographic primitives
* @dev Implements tagged hashing, x-only public key operations, and Taproot output key computation
* @dev Reference: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
*/
library BIP341 {
error InvalidPoint(uint256 x, uint256 y);
error InvalidXOnlyKey(bytes32 xOnly);
error InvalidControlBlock(uint256 length, uint256 remainder);
error InvalidBase(uint256 base, uint256 modulus);
/// @dev Control-block byte 0 packs the leaf version in the high 7 bits and
/// the output-key y-parity in the low bit.
uint8 internal constant PARITY_MASK = 0x01;
uint8 internal constant LEAF_VERSION_MASK = 0xfe;
// ============ Tagged Hash Functions ============
/**
* @notice Compute BIP340-style tagged hash: SHA256(SHA256(tag) || SHA256(tag) || data)
* @param tag The domain separation tag as raw UTF-8 bytes (not padded)
* @param data The data to hash
* @return The 32-byte tagged hash
* @dev This prevents collision between different hash contexts
* @dev Reference: BIP-340 tagged hashes use raw tag bytes, not padded to 32 bytes
*/
function taggedHash(bytes memory tag, bytes memory data) internal pure returns (bytes32) {
bytes32 tagHash = sha256(tag);
return sha256(abi.encodePacked(tagHash, tagHash, data));
}
/**
* @notice Compute TapTweak tagged hash for Taproot output key computation
* @param internalPubKey The 32-byte x-only internal public key
* @param merkleRoot The merkle root of the TapTree (empty bytes for key-path only, 32 bytes for script-path)
* @return The tagged hash used for tweaking
* @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
*/
function tapTweakHash(bytes32 internalPubKey, bytes memory merkleRoot) internal pure returns (bytes32) {
return taggedHash(TaprootConstants.TAG_TAPTWEAK, abi.encodePacked(internalPubKey, merkleRoot));
}
/**
* @notice Compute TapLeaf tagged hash for a script leaf
* @param leafVersion The leaf version byte (0xC0 for Tapscript v0)
* @param script The script bytes
* @return The leaf hash
* @dev Format: TapLeaf || leaf_version || compact_size(script_len) || script
*/
function tapLeafHash(uint8 leafVersion, bytes memory script) internal pure returns (bytes32) {
// Encode script length using Bitcoin's CompactSize format (little-endian)
bytes memory scriptLength = CompactSize.encode(uint64(script.length));
return taggedHash(TaprootConstants.TAG_TAPLEAF, abi.encodePacked(leafVersion, scriptLength, script));
}
/**
* @notice Compute TapBranch tagged hash for merkle tree internal node
* @param left Left child hash
* @param right Right child hash
* @return The branch hash with lexicographic sorting applied
* @dev Hashes are sorted to ensure deterministic tree construction
*/
function tapBranchHash(bytes32 left, bytes32 right) internal pure returns (bytes32) {
// Lexicographic ordering: compare as big-endian integers
if (uint256(left) < uint256(right)) {
return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(left, right));
} else {
return taggedHash(TaprootConstants.TAG_TAPBRANCH, abi.encodePacked(right, left));
}
}
// ============ X-Only Public Key Operations ============
/**
* @notice Lift x-only public key to full (x, y) curve point
* @param xOnly The 32-byte x-coordinate
* @return x The x-coordinate (same as input)
* @return y The y-coordinate (even parity, i.e., y mod 2 == 0)
* @dev Uses secp256k1 curve equation: y^2 = x^3 + b (b = TaprootConstants.BB)
* @dev Always returns the even y-coordinate per BIP340 convention
*/
function liftX(bytes32 xOnly) internal pure returns (uint256 x, uint256 y) {
x = uint256(xOnly);
// Derive y from x using EllipticCurve library (0x02 = even parity per BIP340)
y = EllipticCurve.deriveY(
0x02, // even parity prefix
x,
TaprootConstants.AA,
TaprootConstants.BB,
TaprootConstants.PP
);
// Verify point is on curve
if (!EllipticCurve.isOnCurve(x, y, TaprootConstants.AA, TaprootConstants.BB, TaprootConstants.PP)) {
revert InvalidXOnlyKey(xOnly);
}
return (x, y);
}
/**
* @notice Check if a point's y-coordinate is even (quadratic residue)
* @param y The y-coordinate
* @return True if y is even (y mod 2 == 0)
*/
function hasEvenY(uint256 y) internal pure returns (bool) {
return (y & 1) == 0;
}
/**
* @notice Validate if an x-only public key represents a valid secp256k1 curve point
* @param xOnly The 32-byte x-coordinate to validate
* @return True if the x-coordinate has a corresponding valid y-coordinate on the curve
* @dev This ensures the key can be lifted to a full curve point without reverting
* @dev Uses inline computation to check if y^2 = x^3 + b (b = TaprootConstants.BB) has a valid square root
*/
function isValidXOnlyKey(bytes32 xOnly) internal pure returns (bool) {
uint256 x = uint256(xOnly);
uint256 pp = TaprootConstants.PP;
// x must be a canonical secp256k1 field element that lifts to a curve point
if (x == 0 || x >= pp) return false;
// Compute y^2 = x^3 + b (mod p), b = TaprootConstants.BB
uint256 y2 = addmod(
mulmod(x, mulmod(x, x, pp), pp),
TaprootConstants.BB, // secp256k1 curve parameter b
pp
);
// Check if y2 is a quadratic residue (has a square root) using Euler's criterion
// For prime p, y2 is a QR iff y2^((p-1)/2) ≡ 1 (mod p)
// For secp256k1, (p-1)/2 can be computed
uint256 euler = expPod(y2, TaprootConstants.PP_S1D2, pp);
// If Euler's criterion returns 1, then y2 has a square root
return euler == 1;
}
/**
* @notice Modular exponentiation helper
* @param base The base
* @param exponent The exponent
* @param modulus The modulus
* @return result base^exponent mod modulus
*/
function expPod(uint256 base, uint256 exponent, uint256 modulus) internal pure returns (uint256 result) {
if (base >= modulus) revert InvalidBase(base, modulus);
result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = mulmod(result, base, modulus);
}
exponent = exponent >> 1;
base = mulmod(base, base, modulus);
}
}
/**
* @notice Extract x-only public key from point
* @param x The x-coordinate
* @param y The y-coordinate
* @return The 32-byte x-only public key
*/
function toXOnly(uint256 x, uint256 y) internal pure returns (bytes32) {
// Unused y parameter - included for API clarity
y; // silence compiler warning
return bytes32(x);
}
// ============ Taproot Output Key Computation ============
/**
* @notice Compute Taproot output key P from internal key Q and merkle root
* @param internalPubKey The 32-byte x-only internal public key Q
* @param merkleRoot The merkle root h (empty bytes for key-path only, 32 bytes for script-path)
* @return outputKey The 32-byte x-only output public key P
* @return outputKeyYIsOdd True if the output key's y-coordinate is odd
* @dev Formula: P = Q + int(hash_TapTweak(Q || h)) * G
* @dev Reference: BIP341 "Constructing and spending Taproot outputs"
* @dev Per BIP-341: For key-path only (no scripts), pass empty bytes. For script-path, pass 32-byte merkle root.
*/
function computeOutputKey(bytes32 internalPubKey, bytes memory merkleRoot)
internal
pure
returns (bytes32 outputKey, bool outputKeyYIsOdd)
{
// 1. Lift internal key Q to curve point
(uint256 qx, uint256 qy) = liftX(internalPubKey);
// 2. Compute tweak t = int(hash_TapTweak(Q || h)) mod n
// Note: Following btcd implementation which automatically
// performs modulo N reduction rather than failing on overflow.
bytes32 tweakHash = tapTweakHash(internalPubKey, merkleRoot);
uint256 t = uint256(tweakHash) % TaprootConstants.NN;
// 3. Compute t*G (scalar multiplication of generator by tweak)
(uint256 tGx, uint256 tGy) =
EllipticCurve.ecMul(t, TaprootConstants.GX, TaprootConstants.GY, TaprootConstants.AA, TaprootConstants.PP);
// 4. Compute P = Q + t*G (point addition)
(uint256 px, uint256 py) = EllipticCurve.ecAdd(qx, qy, tGx, tGy, TaprootConstants.AA, TaprootConstants.PP);
// Verify result is valid point
if (px == 0 && py == 0) {
revert InvalidPoint(px, py);
}
// 5. Return x-only representation of P and its y-coordinate parity
return (toXOnly(px, py), !hasEvenY(py));
}
/**
* @notice Verify a Taproot output key matches expected internal key and merkle root
* @param outputKey The claimed x-only output key
* @param internalPubKey The internal public key
* @param merkleRoot The merkle root (empty bytes for key-path only, 32 bytes for script-path)
* @return True if outputKey == computeOutputKey(internalPubKey, merkleRoot)
*/
function verifyOutputKey(bytes32 outputKey, bytes32 internalPubKey, bytes memory merkleRoot)
internal
pure
returns (bool)
{
(bytes32 computed,) = computeOutputKey(internalPubKey, merkleRoot);
return outputKey == computed;
}
// ============ Taproot Leaf Commitment Verification ============
/**
* @notice Verify that a script is committed in a Taproot output via control block
* @param controlBlock The control block containing: leafVersion, parity, internalKey, merkleProof
* @param witnessProgram The 32-byte output key from the scriptPubKey (P)
* @param script The script to verify
* @return True if script is committed in the Taproot output
* @dev This is the core Taproot verification matching Bitcoin's txscript.VerifyTaprootLeafCommitment
* @dev Control block format: [leafVersion + parity (1 byte)] [internalKey (32 bytes)] [merkleProof (0 or more 32-byte hashes)]
* @dev Reference: https://github.com/btcsuite/btcd/blob/v0.24.2/txscript/taproot.go#L363
*/
function verifyTaprootLeafCommitment(bytes memory controlBlock, bytes32 witnessProgram, bytes memory script)
internal
pure
returns (bool)
{
// 1. Parse control block
if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
if ((controlBlock.length - 33) % 32 != 0) {
revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
}
uint8 leafVersionAndParity = uint8(controlBlock[0]);
uint8 leafVersion = leafVersionAndParity & LEAF_VERSION_MASK; // Mask out parity bit
uint8 outputKeyParity = leafVersionAndParity & PARITY_MASK;
bytes32 internalKey;
assembly {
internalKey := mload(add(controlBlock, 33)) // Skip length (32) + first byte (1)
}
// 2. Compute leaf hash
bytes32 leafHash = tapLeafHash(leafVersion, script);
// 3. Compute merkle root by processing the merkle proof
bytes32 merkleRoot = leafHash;
uint256 proofLength = (controlBlock.length - 33) >> 5;
for (uint256 i = 0; i < proofLength; i++) {
bytes32 proofElement;
assembly {
// Read proof element at offset: 32 (length) + 1 (version/parity) + 32 (internalKey) + i*32
proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
}
merkleRoot = tapBranchHash(merkleRoot, proofElement);
}
// 4. Compute expected output key P = Q + hash(Q || merkleRoot) * G
(bytes32 expectedOutputKey, bool computedYIsOdd) = computeOutputKey(internalKey, abi.encodePacked(merkleRoot));
// 5. Verify witness program matches expected output key (x-coordinate)
if (witnessProgram != expectedOutputKey) {
return false;
}
// 6. Verify the parity of the y-coordinate matches the control block
// Per BIP341 and Bitcoin consensus rules
bool expectedYIsOdd = (outputKeyParity == 1);
if (computedYIsOdd != expectedYIsOdd) {
return false;
}
return true;
}
/**
* @notice Parse control block into components
* @param controlBlock The control block bytes
* @return leafVersion The leaf version (0xC0 for Tapscript v0)
* @return outputKeyParity The parity bit of the output key
* @return internalKey The 32-byte internal public key
* @return merkleProof Array of 32-byte merkle proof hashes
*/
function parseControlBlock(bytes memory controlBlock)
internal
pure
returns (uint8 leafVersion, uint8 outputKeyParity, bytes32 internalKey, bytes32[] memory merkleProof)
{
if (controlBlock.length < 33) revert InvalidControlBlock(controlBlock.length, controlBlock.length);
if ((controlBlock.length - 33) % 32 != 0) {
revert InvalidControlBlock(controlBlock.length, (controlBlock.length - 33) % 32);
}
uint8 leafVersionAndParity = uint8(controlBlock[0]);
leafVersion = leafVersionAndParity & LEAF_VERSION_MASK;
outputKeyParity = leafVersionAndParity & PARITY_MASK;
assembly {
internalKey := mload(add(controlBlock, 33))
}
uint256 proofLength = (controlBlock.length - 33) >> 5;
merkleProof = new bytes32[](proofLength);
for (uint256 i = 0; i < proofLength; i++) {
assembly {
let proofElement := mload(add(controlBlock, add(65, mul(i, 32))))
mstore(add(add(merkleProof, 32), mul(i, 32)), proofElement)
}
}
return (leafVersion, outputKeyParity, internalKey, merkleProof);
}
/**
* @notice Build control block from components
* @param leafVersion The leaf version (0xC0 for Tapscript v0)
* @param outputKeyParity The parity bit (0 or 1)
* @param internalKey The internal public key
* @param merkleProof Array of merkle proof hashes
* @return The encoded control block
*/
function buildControlBlock(
uint8 leafVersion,
uint8 outputKeyParity,
bytes32 internalKey,
bytes32[] memory merkleProof
) internal pure returns (bytes memory) {
uint8 leafVersionAndParity = leafVersion | (outputKeyParity & PARITY_MASK);
bytes memory controlBlock = abi.encodePacked(leafVersionAndParity, internalKey);
for (uint256 i = 0; i < merkleProof.length; i++) {
controlBlock = abi.encodePacked(controlBlock, merkleProof[i]);
}
return controlBlock;
}
}
src/protocol/lib/taproot/TaprootConstants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/**
* @title TaprootConstants
* @notice Constants for BIP341 Taproot verification
* @dev Provides internal key Q, curve parameters, and BIP340 tagged hash tags
*/
library TaprootConstants {
// ============ Internal Key Q ============
// The x-only internal public key (32 bytes) used for all vaults
// BIP341 recommends using a nothing-up-my-sleeve (NUMS) point to disable keypath spending
// This is the recommended unspendable key from BIP341:
// lift_x(0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0)
bytes32 constant INTERNAL_KEY_Q = 0x50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0;
// ============ Secp256k1 Curve Parameters ============
// Generator point coordinates
uint256 constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Curve equation: y^2 = x^3 + ax + b
uint256 constant AA = 0; // a coefficient
uint256 constant BB = 7; // b coefficient
// Prime field modulus
uint256 constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant PP_S1D2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFE17;
// Curve order (for scalar operations)
uint256 constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
// ============ BIP340/341/342 Tagged Hash Tags ============
// BIP340 tag for Taproot tweaking (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPTWEAK = bytes("TapTweak");
// BIP341 tag for leaf hashing (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPLEAF = bytes("TapLeaf");
// BIP341 tag for branch hashing (raw UTF-8 bytes, not padded)
bytes constant TAG_TAPBRANCH = bytes("TapBranch");
// BIP340 tag for signature challenges (for future use)
bytes constant TAG_TAPBIP0340CHALLENGE = bytes("BIP0340/challenge");
// ============ Tapscript Constants ============
// Leaf version for Tapscript v0 (BIP342)
uint8 constant TAPSCRIPT_LEAF_VERSION = 0xC0;
// Taproot witness version
uint8 constant TAPROOT_WITNESS_VERSION = 0x01;
// Taproot output key size (x-only pubkey)
uint8 constant TAPROOT_PUBKEY_SIZE = 32;
}
src/protocol/lib/types/BTCVaultRegistryTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/// @title BTCVaultRegistryTypes
/// @notice Protocol-owned BTC vault registry types used by BTCVaultRegistry and protocol callers
library BTCVaultRegistryTypes {
/// @notice Vault provider registration data stored by the protocol
struct VaultProvider {
bytes32 btcPubKey;
address applicationEntryPoint;
uint16 commissionBps;
}
/// @notice One versioned operation-BTC-key entry: the x-only key and the registry epoch
/// at which it became current. v0 is the registration key (not stored here).
struct OpBtcKeyVersion {
bytes32 key;
uint64 epoch;
}
/// @notice One versioned operation-ETH-key entry: the relay/ACK address and its epoch.
/// v0 = adminEthAddress (derived, not stored here).
struct OpEthKeyVersion {
address key;
uint64 epoch;
}
/// @notice One versioned payout-script entry: the scriptPubKey bytes and its epoch.
/// v0 = BIP-86 P2TR of op-key v0 (derived, not stored here); v1 = required registration payout.
struct PayoutScriptVersion {
bytes script;
uint64 epoch;
}
/// @notice Protocol-only vault metadata stored alongside the shared basic vault info
/// @dev Append-only: when adding fields for an upgradeable deployment, add them
/// after `claimExpiredUntil` so existing per-vault rows decode unchanged.
struct BTCVaultProtocolInfo {
bytes depositorSignedPeginTx;
uint16 universalChallengersVersion;
uint16 appVaultKeepersVersion;
uint16 offchainParamsVersion;
uint256 verifiedAt;
bytes32 depositorWotsPkHash;
bytes32 hashlock;
uint8 htlcVout;
bytes depositorPopSignature;
bytes32 prePeginTxHash;
uint16 vaultProviderCommissionBps;
uint256 claimExpiredUntil;
// RFC 004: appended at the end to preserve storage layout for any future upgrade
// of an already-deployed BTCVaultRegistry.
uint16 vaultCoreVersion;
// per-pegin operation-key epochs the vault bonds against. Appended after
// `vaultCoreVersion` so existing rows decode unchanged; all three pack into one slot.
uint64 vpKeyEpoch;
uint64 appKeeperKeyEpoch;
uint64 ucKeyEpoch;
}
/// @notice ACK submission payload for batch ACK processing
struct ACKSubmission {
bytes32 vaultId;
bytes signature;
}
/// @notice Batched pegin request payload for a shared depositor and vault provider
struct BatchPeginRequest {
bytes32 depositorBtcPubKey;
bytes btcPopSignature;
bytes unsignedPrePeginTx;
bytes depositorSignedPeginTx;
bytes32 hashlock;
uint8 htlcVout;
uint32 referralCode;
bytes depositorPayoutBtcAddress;
bytes32 depositorWotsPkHash;
}
}
src/protocol/lib/types/Constants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Constants {
/// @notice Bitcoin dust threshold - minimum value for a standard output (546 satoshis)
/// @dev Outputs below this threshold are considered "dust" and rejected by Bitcoin network
uint64 constant BTC_DUST_THRESHOLD = 546;
/// @notice Maximum byte length for a depositor BTC payout address (scriptPubKey)
/// @dev Standard scriptPubKey types are at most 34 bytes; 128 bytes provides headroom for future types
uint256 constant MAX_PAYOUT_ADDRESS_LENGTH = 128;
/// @notice Minimum vault provider commission in basis points (1 = 0.01%)
/// @dev Hardcoded floor so off-chain payout construction never handles a zero commission output
uint16 constant MIN_VP_COMMISSION_BPS = 1;
}
src/protocol/lib/types/Errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Errors {
// =============================================================================
// COMMON VALIDATION ERRORS
// =============================================================================
/// @notice Error thrown when zero address is provided where not allowed
error ZeroAddress();
/// @notice Error thrown when caller is not authorized
error Unauthorized();
/// @notice Error thrown when invalid amount is provided
error InvalidAmount();
/// @notice A circuit version's approved verifier/checkpoint cannot be replaced
error ProverInfoAlreadyRegistered(uint16 circuitVersion);
/// @notice Offchain parameter updates require the selected circuit's approved verifier/checkpoint
error ProverInfoNotRegistered(uint16 circuitVersion);
/// @notice Error thrown when transfer of funds fails
error TransferFailed();
// =============================================================================
// ACCESS CONTROL ERRORS
// =============================================================================
/// @notice Error thrown when caller is not the application entry point
error OnlyApplicationEntryPoint();
// =============================================================================
// MARKET/VAULT ERRORS
// =============================================================================
/// @notice Error thrown when vault is not found or invalid
error InvalidVault();
// =============================================================================
// PROVIDER/LIQUIDATOR ERRORS
// =============================================================================
/// @notice Error thrown when provider ETH address is already registered
error EthKeyAlreadyRegistered();
/// @notice Error thrown when invalid BTC public key is provided
error InvalidBTCPublicKey();
/// @notice Error thrown when depositor WOTS public key hash is missing (bytes32(0))
error InvalidDepositorWotsPkHash();
/// @notice Error thrown when a depositor reuses a WOTS public key hash across pegin requests
error DepositorWotsPkHashAlreadyUsed();
/// @notice Error thrown when BTC Proof of Possession signature is invalid
error InvalidBTCProofOfPossession();
/// @notice Error thrown when the operation-ETH-key self proof of possession is invalid
error InvalidEthProofOfPossession();
/// @notice Error thrown when a BTC public key is already registered
error BtcKeyAlreadyRegistered();
/// @notice Error thrown when incorrect registration fee amount is provided
error InvalidRegistrationFee();
/// @notice Error thrown when vault provider commission is below the hardcoded minimum
/// @param provided The commission provided in basis points
/// @param minimum The minimum required commission in basis points
error CommissionBelowMinimum(uint16 provided, uint16 minimum);
/// @notice Error thrown when vault provider commission exceeds the protocol maximum
/// @param provided The commission provided in basis points
/// @param maximum The maximum allowed commission in basis points
error CommissionAboveMaximum(uint16 provided, uint16 maximum);
/// @notice Error thrown when vault provider commission update is a no-op
error CommissionUnchanged();
/// @notice Error thrown when the live vault provider commission exceeds the
/// maximum the depositor was willing to accept at peg-in submission time.
/// @param maxAcceptable The depositor-supplied upper bound in basis points
/// @param actual The current on-chain VP commission in basis points
error VaultProviderCommissionExceeded(uint16 maxAcceptable, uint16 actual);
/// @notice Error thrown when vault provider is not registered
error VaultProviderNotRegistered();
// =============================================================================
// APPLICATION ERRORS
// =============================================================================
/// @notice Error thrown when application is already registered
error ApplicationAlreadyRegistered();
/// @notice Error thrown when application is not registered
error ApplicationNotRegistered();
/// @notice Error thrown when application is not in Active status (unregistered or paused)
error ApplicationNotActive();
/// @notice Error thrown when application has invalid status for the requested operation
error InvalidApplicationStatus();
/// @notice Error thrown when vault keepers array is empty
error EmptyVaultKeepers();
// =============================================================================
// PEGIN/PEGOUT ERRORS
// =============================================================================
/// @notice Error thrown when invalid transaction data is provided
error InvalidTransaction();
/// @notice Error thrown when depositor payout BTC address is empty
error EmptyPayoutAddress();
/// @notice Error thrown when depositor payout BTC address exceeds maximum allowed length
error PayoutAddressTooLong();
/// @notice Error thrown when vault with same transaction hash already exists
error VaultAlreadyExists();
/// @notice Error thrown when vault fee is already escrowed for a vault
error VaultFeeAlreadyEscrowed();
/// @notice Error thrown when there are no escrowed fees to distribute or forfeit for a vault
error NoEscrowedFees();
/// @notice Error thrown when pegin request not found
error BTCVaultNotFound();
/// @notice Error thrown when pegin request has invalid BTC vault status
error InvalidBTCVaultStatus();
/// @notice Error thrown when attempting to expire a vault whose timeout has not elapsed
error PeginNotExpired();
/// @notice Error thrown when invalid providers or liquidators list
error InvalidParticipantsList();
/// @notice Error thrown when a participant list contains duplicate ETH addresses or BTC public keys
error DuplicateParticipant();
/// @notice Error thrown when an ETH address or BTC public key appears in multiple participant roles
error ParticipantRoleOverlap();
/// @notice Error thrown when caller is not authorized for ACK
error NotAuthorizedToACK();
/// @notice Error thrown when vault keeper is not authorized for a protocol operation
error UnauthorizedVaultKeeper();
/// @notice Error thrown when a blocklisted vault keeper attempts redemption
error BlocklistedVaultKeeper();
/// @notice Error thrown when pegin transaction has expired
error PeginTransactionExpired();
/// @notice Error thrown when a pre-pegin output (txHash + vout) is already claimed by another vault
error PrePeginOutputAlreadyUsed();
/// @notice Error thrown when a signed pegin transaction is already claimed by another vault
error PeginTransactionAlreadyUsed();
/// @notice Error thrown when pegin fee does not match required amount
error InvalidPeginFee(uint256 provided, uint256 required);
// =============================================================================
// BTC VERIFICATION ERRORS
// =============================================================================
/// @notice Error thrown when amount is below minimum threshold
error AmountBelowMinimumThreshold(uint256 actual, uint256 minimum);
/// @notice Error thrown when invalid output index provided
error InvalidOutputIndex(uint256 provided, uint256 maxValid);
/// @notice Error thrown when Pre-PegIn transaction has too many HTLC outputs
error TooManyHtlcOutputs(uint256 outputCount, uint256 maxAllowed);
/// @notice Error thrown when Pre-PegIn transaction has too many funding inputs
error TooManyFundingInputs(uint256 inputCount, uint256 maxAllowed);
/// @notice Error thrown when vault BTC amount is below minimum threshold
/// @param actual The actual vault amount in satoshis
/// @param minimum The minimum required amount in satoshis
error VaultBelowMinimum(uint256 actual, uint256 minimum);
/// @notice Error thrown when vault BTC amount exceeds maximum threshold
/// @param actual The actual vault amount in satoshis
/// @param maximum The maximum allowed amount in satoshis
error VaultAboveMaximum(uint256 actual, uint256 maximum);
// =============================================================================
// PARAMS ERRORS
// =============================================================================
/// @notice Error thrown when a parameter value of zero is provided where not allowed
error ZeroValue();
/// @notice Error thrown when attempting to overwrite an existing version
error VersionAlreadyExists();
/// @notice Error thrown when security council configuration is invalid
error InvalidSecurityCouncilConfig();
/// @notice Error thrown when no universal challengers are configured
error NoUniversalChallengersConfigured();
/// @notice Error thrown when no application vault keepers are configured
error NoAppVaultKeepersConfigured();
/// @notice Error thrown when an operation-key version counter would overflow uint16
error OperationKeyVersionOverflow();
// =============================================================================
// APPLICATION CAP ERRORS
// =============================================================================
/// @notice Error thrown when activating a vault would exceed application BTC caps
error CapExceeded();
/// @notice Error thrown when a pegin submission would exceed the global live-vault cap
error LiveVaultCapExceeded();
/// @notice Error thrown when the live-vault release delay exceeds its protocol maximum
/// @param requested The requested release delay in Ethereum blocks
/// @param maximum The maximum permitted release delay in Ethereum blocks
error LiveVaultReleaseDelayTooLong(uint256 requested, uint256 maximum);
/// @notice Error thrown when lowering the live-vault release delay with queued releases
error LiveVaultReleaseDelayDecreaseBlocked();
/// @notice Error thrown when a depositor is not allow-listed for a gated application
error DepositNotAllowed();
/// @notice Error thrown when setting depositor allowances while the gate is disabled
error AllowListDisabled();
/// @notice Error thrown when the destination application declines a batch of pegin requests for
/// the given receiver, e.g. because the resulting position would breach the
/// application's size boundaries
error PositionSizesRejectedByApplication();
/// @notice Error thrown when maxPegInAmount is less than minimumPegInAmount
/// @param max The configured maximum peg-in amount
/// @param min The configured minimum peg-in amount
error MaxPegInBelowMinPegIn(uint256 max, uint256 min);
/// @notice Error thrown when initial array size exceeds the maximum limit
/// @param actual The actual array size
/// @param maximum The maximum size allowed
error ArrayExceedsMaxSize(uint256 actual, uint256 maximum);
// =============================================================================
// ATOMIC SWAP ERRORS
// =============================================================================
/// @notice Error thrown when `activateVaultWithSecret` would push the application past its BTC cap
/// @dev Raised when `CapPolicy.incrementUsage` returns false. The vault stays `Verified`; the depositor
/// recovers through `activateVaultWithSecretAndRedeem`.
error ActivationCapExceeded();
/// @notice Error thrown when hashlock is zero
error InvalidHashlock();
/// @notice Error thrown when hashlock is already used by another vault
error DuplicateHashlock();
/// @notice Error thrown when SHA256(secret) does not match the hashlock
error InvalidSecret();
/// @notice Error thrown when ACK is submitted before all pegin input signatures are posted
error PeginSignaturesIncomplete();
/// @notice Error thrown when a pegin input signature is not 64 bytes (Schnorr)
error InvalidSignatureLength();
/// @notice Error thrown when a pegin input signature slot has already been written
error PeginInputSignatureAlreadySubmitted();
/// @notice Error thrown when atomic swap activation deadline has passed
error ActivationDeadlineExpired();
/// @notice Error thrown when the protocol state resolved at submit differs from what the depositor built against
/// @dev Both values are `PeginLogic._peginFingerprint` outputs: the one the depositor built from
/// public state and the one the registry resolves at inclusion. A mismatch means a participant rotated an
/// operation key, a roster changed, or the offchain-params / vault-core version moved between
/// the moment the depositor resolved that state and the inclusion of `submitPeginRequest`, so
/// the Pre-PegIn commits to bytes this vault would not bond to. Reverting keeps the depositor
/// from funding a vault every daemon would reject. The seven components each have their own
/// public getter, so a caller can diff them to find which axis moved.
error PeginFingerprintChanged(bytes32 expected, bytes32 actual);
/// @notice Error thrown when application activation is attempted before the observation window has elapsed
/// @dev Cutoff: block.number < verifiedAt + peginActivationDelay. Applies to `activateVaultWithSecret` only;
/// `activateVaultWithSecretAndRedeem` is unaffected because it mints no vaultBTC.
error ActivationDelayNotElapsed();
/// @notice Error thrown when claimExpiredVault is called past the post-expiry grace window
/// @dev Cutoff: block.number > (block.number at reportExpired) + expiredPegInGraceBlocks
error PostExpiryGraceWindowElapsed();
/// @notice Error thrown when the Bitcoin refund window does not safely outlast the Ethereum activation window
/// @param tRefund The configured Bitcoin refund window in Bitcoin blocks
/// @param pegInActivationTimeout The configured activation window in Ethereum blocks
error UnsafePeginTimingConfiguration(uint32 tRefund, uint64 pegInActivationTimeout);
// =============================================================================
// TIMELOCK VALIDATION ERRORS
// =============================================================================
/// @notice Error thrown when initializing the timelock with a delay that exceedes the Standard Governance Delay (5 days)
error InvalidDelay();
/// @notice Error thrown when initializing the timelock with short delay arrays of different lengths
error InvalidShortDelayArrays();
}
src/utility/TBVAccessControlUpg.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import "../../lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol";
import "./types/Errors.sol";
abstract contract TBVAccessControlUpg is AccessControlUpgradeable {
modifier onlyAdmin() {
require(hasRole(_ADMIN_ROLE(), msg.sender), Errors.TBV_Unauthorized());
_;
}
function _ADMIN_ROLE() internal pure virtual returns (bytes32);
function _PAUSE_GUARDIAN_ROLE() internal pure virtual returns (bytes32);
function _FREEZE_GUARDIAN_ROLE() internal pure virtual returns (bytes32);
function __TBVAccessControlUpg_init(address _initialAdmin) internal onlyInitializing {
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, _initialAdmin);
_grantRole(_ADMIN_ROLE(), _initialAdmin);
_setRoleAdmin(_PAUSE_GUARDIAN_ROLE(), _ADMIN_ROLE());
_setRoleAdmin(_FREEZE_GUARDIAN_ROLE(), _ADMIN_ROLE());
}
}
src/utility/TBVPausableUpg.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {Initializable} from "../../lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {ITBVPausable} from "../interfaces/ITBVPausable.sol";
import {Errors} from "./types/Errors.sol";
/**
* @notice Cases to notice:
* - If the contract is paused, freeze role could not change it to freeze state
* - Unpause should be equivalently sensitive compared to pause
*/
abstract contract TBVPausableUpg is Initializable, ITBVPausable {
event Paused(address indexed pauser);
event Frozen(address indexed freezer);
event Unpaused(address indexed pauser);
event Unfrozen(address indexed unfreezer);
PauseState public pauseState;
uint256[50] private __gap;
function __TBVPausableUpg_init() internal onlyInitializing {
pauseState = PauseState.Frozen;
}
modifier whenNotFrozen() {
_whenNotFrozen();
_;
}
modifier whenNotPaused() {
_whenNotPaused();
_;
}
function _whenNotFrozen() internal view {
PauseState currentState = pauseState;
if (currentState == PauseState.Frozen) revert Errors.TBV_Frozen();
if (currentState == PauseState.Paused) revert Errors.TBV_Paused();
}
function _whenNotPaused() internal view {
if (pauseState == PauseState.Paused) revert Errors.TBV_Paused();
}
function unpause() external virtual allowedToUnpause {
PauseState currentState = pauseState;
if (currentState == PauseState.Frozen) revert Errors.TBV_CannotUnpauseWhileFrozen();
if (currentState != PauseState.Paused) revert Errors.TBV_NotPaused();
pauseState = PauseState.None;
emit Unpaused(msg.sender);
}
function freeze() external virtual allowedToFreeze {
PauseState currentState = pauseState;
if (currentState == PauseState.Frozen) revert Errors.TBV_AlreadyFrozen();
if (currentState == PauseState.Paused) revert Errors.TBV_AlreadyPaused();
pauseState = PauseState.Frozen;
emit Frozen(msg.sender);
}
function unfreeze() external virtual allowedToUnfreeze {
PauseState currentState = pauseState;
if (currentState == PauseState.Paused) revert Errors.TBV_CannotUnfreezeWhilePaused();
if (currentState != PauseState.Frozen) revert Errors.TBV_NotFrozen();
pauseState = PauseState.None;
emit Unfrozen(msg.sender);
}
function pause() external virtual allowedToPause {
PauseState currentState = pauseState;
if (currentState == PauseState.Paused) revert Errors.TBV_AlreadyPaused();
pauseState = PauseState.Paused;
emit Paused(msg.sender);
}
modifier allowedToFreeze() virtual;
modifier allowedToPause() virtual;
modifier allowedToUnpause() virtual;
modifier allowedToUnfreeze() virtual;
}
src/utility/TBVTemplateUpg.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {TBVAccessControlUpg} from "./TBVAccessControlUpg.sol";
import {TBVPausableUpg} from "./TBVPausableUpg.sol";
import {UUPSUpgradeable} from "../../lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol";
import {Errors} from "./types/Errors.sol";
/// @title TBVTemplateUpg
/// @notice Shared governance base: access control + pausability + UUPS upgradeability.
/// Protocol and application contracts inherit a thin role-ID layer on top of this.
abstract contract TBVTemplateUpg is TBVAccessControlUpg, TBVPausableUpg, UUPSUpgradeable {
modifier allowedToFreeze() virtual override {
// freeze: ADMIN or FREEZE_GUARDIAN
require(
hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_FREEZE_GUARDIAN_ROLE(), msg.sender),
Errors.TBV_Unauthorized()
);
_;
}
modifier allowedToPause() virtual override {
// pause: ADMIN or PAUSE_GUARDIAN
require(
hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
);
_;
}
modifier allowedToUnpause() virtual override {
// unpause: ADMIN or PAUSE_GUARDIAN
require(
hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
);
_;
}
modifier allowedToUnfreeze() virtual override {
// unfreeze: ADMIN or PAUSE_GUARDIAN
require(
hasRole(_ADMIN_ROLE(), msg.sender) || hasRole(_PAUSE_GUARDIAN_ROLE(), msg.sender), Errors.TBV_Unauthorized()
);
_;
}
/// @notice Authorize contract upgrade — only ADMIN
function _authorizeUpgrade(address newImplementation) internal override onlyAdmin {}
function __TBVTemplateUpg_init(address _initialAdmin) internal onlyInitializing {
__TBVAccessControlUpg_init(_initialAdmin);
__TBVPausableUpg_init();
}
uint256[50] private __gap;
}
src/utility/types/Errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Errors {
// =============================================================================
// COMMON VALIDATION ERRORS
// =============================================================================
/// @notice Error thrown when zero address is provided where not allowed
error ZeroAddress();
/// @notice Error thrown when caller is not authorized
error Unauthorized();
// =============================================================================
// TBV COMMON ERRORS
// =============================================================================
/// @notice Error thrown when the contract is full-paused
error TBV_Paused();
/// @notice Error thrown when the contract is frozen
error TBV_Frozen();
/// @notice Error thrown when attempting to unpause a contract that is not full-paused
error TBV_NotPaused();
/// @notice Error thrown when attempting to unfreeze a contract that is not frozen
error TBV_NotFrozen();
/// @notice Error thrown when attempting to full-pause a contract that is already full-paused
error TBV_AlreadyPaused();
/// @notice Error thrown when attempting to freeze a contract that is already frozen
error TBV_AlreadyFrozen();
/// @notice Error thrown when attempting to unfreeze while the contract is paused
error TBV_CannotUnfreezeWhilePaused();
/// @notice Error thrown when attempting to unpause while the contract is frozen
error TBV_CannotUnpauseWhileFrozen();
/// @notice Error thrown when caller does not have the required TBV role
error TBV_Unauthorized();
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
":@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
":aave-v4/=lib/aave-v4/src/",
":elliptic-curve-solidity/=lib/elliptic-curve-solidity/",
":erc4626-tests/=lib/aave-v4/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
":src/access/=lib/aave-v4/src/access/",
":src/config-engine/=lib/aave-v4/src/config-engine/",
":src/dependencies/=lib/aave-v4/src/dependencies/",
":src/deployments/=lib/aave-v4/src/deployments/",
":src/hub/=lib/aave-v4/src/hub/",
":src/interfaces/IExtSload.sol=lib/aave-v4/src/interfaces/IExtSload.sol",
":src/interfaces/IIntentConsumer.sol=lib/aave-v4/src/interfaces/IIntentConsumer.sol",
":src/interfaces/IMulticall.sol=lib/aave-v4/src/interfaces/IMulticall.sol",
":src/interfaces/INoncesKeyed.sol=lib/aave-v4/src/interfaces/INoncesKeyed.sol",
":src/interfaces/IRescuable.sol=lib/aave-v4/src/interfaces/IRescuable.sol",
":src/libraries/=lib/aave-v4/src/libraries/",
":src/position-manager/=lib/aave-v4/src/position-manager/",
":src/spoke/=lib/aave-v4/src/spoke/",
":src/utils/=lib/aave-v4/src/utils/",
":vault-contracts/=src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.