Verified contractExactBUSL-1.1
RedeemLogic
Address0xc295d3393ae6e803121cc36291371a22d4d04ee9
- 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,865
- Creation transaction
- 0x27bc2bc230…d4e0d6d543
11 files
- src/protocol/lib/RedeemLogic.solmain6.35 KB
- src/interfaces/IApplicationRegistry.sol15.34 KB
- src/lib/BTCVaultTypes.sol2.18 KB
- src/protocol/interfaces/ICapPolicy.sol8.83 KB
- src/protocol/interfaces/IProtocolParams.sol15.65 KB
- src/protocol/lib/helpers/BTCUtils.sol19.92 KB
- src/protocol/lib/helpers/CompactSize.sol8.52 KB
- src/protocol/lib/helpers/OpCodes.sol1.5 KB
- src/protocol/lib/types/BTCVaultRegistryTypes.sol2.94 KB
- src/protocol/lib/types/Errors.sol15.33 KB
- src/protocol/lib/types/Events.sol9.98 KB
src/protocol/lib/RedeemLogic.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {BTCVaultTypes} from "../../lib/BTCVaultTypes.sol";
import {BTCVaultRegistryTypes} from "./types/BTCVaultRegistryTypes.sol";
import {IApplicationRegistry} from "../../interfaces/IApplicationRegistry.sol";
import {IProtocolParams} from "../interfaces/IProtocolParams.sol";
import {ICapPolicy} from "../interfaces/ICapPolicy.sol";
import {BTCUtils} from "./helpers/BTCUtils.sol";
import {Errors} from "./types/Errors.sol";
import {Events} from "./types/Events.sol";
/// @title RedeemLogic
/// @notice Vault redemption logic (depositor / AVK / fresh-activation paths), extracted from
/// BTCVaultRegistry to keep the registry under the EIP-170 runtime size limit.
/// @dev External (DELEGATECALL-linked) functions operate directly on the registry's vault storage
/// passed by reference; `msg.sender` is the original caller, so the application-entry-point and
/// cap-policy authorization semantics are unchanged. The VP op-BTC key bonded to a vault's
/// `vpKeyEpoch` is resolved by the registry and passed in as `vaultProviderKey`.
library RedeemLogic {
/// @notice Registry dependencies bundled to stay under the stack-slot limit
struct Deps {
IApplicationRegistry applicationRegistry;
IProtocolParams protocolParams;
ICapPolicy capPolicy;
}
/// @notice Redeem a vault for the depositor; emits VaultClaimableBy for the VP and the depositor
function redeemForDepositor(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
Deps memory deps,
bytes32 vaultProviderKey,
bytes32 vaultId
) external {
_validateRedeemVault(vBasic, deps.applicationRegistry);
_executeRedeemVault(vBasic, deps.capPolicy, vaultId);
bytes32 peginTxHash = BTCUtils.hashBtcTx(vProtocol.depositorSignedPeginTx);
_emitVaultClaimableBy(vProtocol, deps.protocolParams, vaultId, peginTxHash, vaultProviderKey);
_emitVaultClaimableBy(vProtocol, deps.protocolParams, vaultId, peginTxHash, vBasic.depositorBtcPubKey);
}
/// @notice Redeem a vault for an application vault keeper; emits VaultClaimableBy for the keeper only
function redeemForAVK(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
Deps memory deps,
bytes32 vaultKeeperKey,
bytes32 vaultId
) external {
if (vaultKeeperKey == bytes32(0)) revert Errors.InvalidBTCPublicKey();
_validateRedeemVault(vBasic, deps.applicationRegistry);
deps.applicationRegistry
.assertVaultKeeperCanRedeem(
msg.sender, vaultKeeperKey, vProtocol.appVaultKeepersVersion, vProtocol.appKeeperKeyEpoch
);
_executeRedeemVault(vBasic, deps.capPolicy, vaultId);
bytes32 peginTxHash = BTCUtils.hashBtcTx(vProtocol.depositorSignedPeginTx);
_emitVaultClaimableBy(vProtocol, deps.protocolParams, vaultId, peginTxHash, vaultKeeperKey);
}
/// @notice Redeem a freshly activated (Active) vault for the depositor without an application callback
/// @dev No application cap-usage mutation (the vault never entered application tracking);
/// schedules the vault's global live-vault slot release and emits VaultClaimableBy for
/// the VP and the depositor BTC keys.
function redeemFreshlyActivatedForDepositor(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
IProtocolParams protocolParams,
ICapPolicy capPolicy,
bytes32 vaultProviderKey,
bytes32 vaultId
) external {
vBasic.status = BTCVaultTypes.BTCVaultStatus.Redeemed;
capPolicy.scheduleLiveVaultRelease(vaultId);
bytes32 peginTxHash = BTCUtils.hashBtcTx(vProtocol.depositorSignedPeginTx);
_emitVaultClaimableBy(vProtocol, protocolParams, vaultId, peginTxHash, vaultProviderKey);
_emitVaultClaimableBy(vProtocol, protocolParams, vaultId, peginTxHash, vBasic.depositorBtcPubKey);
}
/// @notice Validate the vault is application-owned redeemable: caller is its entry point, app Active, status Active
function _validateRedeemVault(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
IApplicationRegistry applicationRegistry
) private view {
if (vBasic.depositor == address(0)) {
revert Errors.BTCVaultNotFound();
}
if (msg.sender != vBasic.applicationEntryPoint) {
revert Errors.OnlyApplicationEntryPoint();
}
if (
applicationRegistry.getApplicationStatus(vBasic.applicationEntryPoint)
!= IApplicationRegistry.ApplicationStatus.Active
) {
revert Errors.ApplicationNotActive();
}
if (vBasic.status != BTCVaultTypes.BTCVaultStatus.Active) {
revert Errors.InvalidBTCVaultStatus();
}
}
/// @notice Mark Redeemed, decrement the application cap usage for the redeeming entry point,
/// and schedule the global live-vault slot release
function _executeRedeemVault(BTCVaultTypes.BTCVaultBasicInfo storage vBasic, ICapPolicy capPolicy, bytes32 vaultId)
private
{
vBasic.status = BTCVaultTypes.BTCVaultStatus.Redeemed;
capPolicy.decrementUsage(msg.sender, vBasic.depositor, vBasic.amount);
capPolicy.scheduleLiveVaultRelease(vaultId);
}
/// @notice Emit `VaultClaimableBy` carrying the full 5-axis ProtocolSnapshot stamped on the vault (RFC 004)
function _emitVaultClaimableBy(
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
IProtocolParams protocolParams,
bytes32 vaultId,
bytes32 peginTxHash,
bytes32 claimerPK
) private {
uint16 opv = vProtocol.offchainParamsVersion;
emit Events.VaultClaimableBy(
vaultId,
peginTxHash,
claimerPK,
vProtocol.vaultCoreVersion,
protocolParams.getOffchainParamsByVersion(opv).proverCircuitVersion,
opv,
vProtocol.universalChallengersVersion,
vProtocol.appVaultKeepersVersion
);
}
}
src/interfaces/IApplicationRegistry.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import {BTCVaultTypes} from "../lib/BTCVaultTypes.sol";
/// @title IApplicationRegistry
/// @notice Interface for the ApplicationRegistry contract
/// @dev Manages application registration and vault keepers versioning
interface IApplicationRegistry {
/// @notice Application status enum
enum ApplicationStatus {
None, // = 0 (default, unregistered)
Active, // = 1 (application is active and can be used)
Paused // = 2 (application is paused, all lifecycle operations are blocked)
}
/// @notice Structure representing a registered application
struct ApplicationInfo {
string name; // Application name
address entryPoint; // application entry point smart contract address
uint16 currentVaultKeepersVersion; // Active version of application-elected vault keepers
ApplicationStatus status; // Application status
}
// ========== Events ==========
/// @notice Emitted when an application is registered
event ApplicationRegistered(address indexed applicationEntryPoint, string name);
/// @notice Emitted when an application's status changes
event ApplicationStatusChanged(
address indexed appEntryPoint, ApplicationStatus oldStatus, ApplicationStatus newStatus
);
/// @notice Event emitted when application vault keepers are updated
/// @param appEntryPoint The application entry point address
/// @param appVaultKeepersVersion New application vault keepers version
/// @param appVaultKeepers Full array of current application vault keepers
event AppVaultKeepersUpdated(
address indexed appEntryPoint, uint16 appVaultKeepersVersion, BTCVaultTypes.AddressBTCKeyPair[] appVaultKeepers
);
/// @notice Event emitted when a vault keeper blocklist status changes
/// @param appEntryPoint The application entry point address
/// @param vaultKeeper The vault keeper Ethereum address
/// @param isBlocklisted Whether the vault keeper is now blocklisted
event VaultKeeperBlocklistUpdated(address indexed appEntryPoint, address indexed vaultKeeper, bool isBlocklisted);
/// @notice Emitted when a vault keeper appends a new operation BTC key version
event OperationBtcKeyVersionAdded(
address indexed appEntryPoint,
address indexed keeperAdmin,
uint16 indexed version,
bytes32 opBtcKey,
uint64 epoch
);
/// @notice Emitted when a vault keeper appends a new operation ETH key version
event OperationEthKeyVersionAdded(
address indexed appEntryPoint,
address indexed keeperAdmin,
uint16 indexed version,
address opEthKey,
uint64 epoch
);
/// @notice Emitted when a vault keeper appends a new payout script version
event PayoutScriptVersionAdded(
address indexed appEntryPoint,
address indexed keeperAdmin,
uint16 indexed version,
bytes payoutScript,
uint64 epoch
);
// ========== Application Management Functions ==========
/// @notice Register a new application with initial vault keepers
/// @param name The application name
/// @param appEntryPoint The application entry point smart contract address
/// @param appVaultKeepers The initial vault keepers for this application (version 1)
/// @dev Can only be called by APP_ADMIN_ROLE
/// @dev Application is registered with status Active and version 1
function registerApplication(
string memory name,
address appEntryPoint,
BTCVaultTypes.VaultKeeperRegistration[] memory appVaultKeepers
) external;
/// @notice Pause an application
/// @param appEntryPoint The application entry point address
/// @dev Can only be called by APP_ADMIN_ROLE
function pauseApplication(address appEntryPoint) external;
/// @notice Activate a paused application
/// @param appEntryPoint The application entry point address
/// @dev Can only be called by APP_ADMIN_ROLE
function activateApplication(address appEntryPoint) external;
/// @notice Set a new version of vault keepers for an application
/// @param appEntryPoint The application entry point address
/// @param vaultKeepers Array of vault keepers for this version
/// @dev Once a version is set, it cannot be modified (immutable)
/// @dev This function increments by one the current vault keepers version for the application
/// @dev Empty vault keepers lists are not allowed
/// @dev Can only be called by APP_ADMIN_ROLE
/// @dev A removed keeper may be re-listed with a PoP-verified operation-ETH replacement;
/// omitting it preserves the keeper's latest operation-ETH key
function addVaultKeepersVersion(address appEntryPoint, BTCVaultTypes.VaultKeeperRegistration[] memory vaultKeepers)
external;
/// @notice Set blocklist status for a vault keeper address for an application
/// @param appEntryPoint The application entry point address
/// @param vaultKeeper The vault keeper Ethereum address
/// @param isBlocklisted Whether the vault keeper should be blocklisted
function setVaultKeeperBlocklist(address appEntryPoint, address vaultKeeper, bool isBlocklisted) external;
// ========== View Functions ==========
/// @notice Get the current status of an application
/// @param appEntryPoint The application entry point address
/// @return The application's current status
function getApplicationStatus(address appEntryPoint) external view returns (ApplicationStatus);
/// @notice Get application info
/// @param appEntryPoint The application entry point address
/// @return info The ApplicationInfo struct
function getApplicationInfo(address appEntryPoint) external view returns (ApplicationInfo memory info);
/// @notice Get vault keepers for a specific roster version
/// @param appEntryPoint The application entry point address
/// @param versionNumber The version number
/// @return Array of vault keepers for the specified version
/// @dev The version axis is roster membership, not key rotation; each pair's `btcPubKey` is
/// the keeper's genesis roster key. Resolve keys per keeper via
/// `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `appKeeperKeyEpochCurrent`).
function getVaultKeepersByVersion(address appEntryPoint, uint16 versionNumber)
external
view
returns (BTCVaultTypes.AddressBTCKeyPair[] memory);
/// @notice Get the current active vault keepers for an application
/// @param appEntryPoint The application entry point address
/// @return Array of current vault keepers
/// @dev Current in roster membership only; each pair's `btcPubKey` is the keeper's genesis
/// roster key. Resolve keys per keeper via
/// `getOperationBtcKeyAtEpochOrGenesis` (current epoch = `appKeeperKeyEpochCurrent`).
function getCurrentVaultKeepers(address appEntryPoint)
external
view
returns (BTCVaultTypes.AddressBTCKeyPair[] memory);
/// @notice Get the current vault keepers version for an application
/// @param appEntryPoint The application entry point address
/// @return The current version number
function getCurrentVaultKeepersVersion(address appEntryPoint) external view returns (uint16);
/// @notice Check if an address is a registered vault keeper for an application (current version)
/// @param appEntryPoint The application entry point address
/// @param account The address to check
/// @return True if the account is a registered vault keeper
function isVaultKeeper(address appEntryPoint, address account) external view returns (bool);
/// @notice Check if an address is a registered vault keeper for a specific version
/// @param appEntryPoint The application entry point address
/// @param account The address to check
/// @param version The version number to check against
/// @return True if the account is a registered vault keeper
function isVaultKeeperInVersion(address appEntryPoint, address account, uint16 version) external view returns (bool);
/// @notice Get the BTC public key for a specific vault keeper
/// @param appEntryPoint The application entry point address
/// @param vaultKeeper The vault keeper's Ethereum address
/// @return The BTC public key registered for this vault keeper
function getVaultKeeperBTCKey(address appEntryPoint, address vaultKeeper) external view returns (bytes32);
/// @notice Get the BTC public key for a specific vault keeper in a specific version
/// @param appEntryPoint The application entry point address
/// @param vaultKeeper The vault keeper's Ethereum address
/// @param version The version number to check against
/// @return The BTC public key registered for this vault keeper
function getVaultKeeperBTCKeyInVersion(address appEntryPoint, address vaultKeeper, uint16 version)
external
view
returns (bytes32);
/// @notice Get the vault keeper Ethereum address for a BTC public key
/// @param appEntryPoint The application entry point address
/// @param btcPubKey The vault keeper BTC public key
/// @return The vault keeper Ethereum address bound to this BTC key
function getVaultKeeperEthAddressByBtcKey(address appEntryPoint, bytes32 btcPubKey) external view returns (address);
/// @notice Check if a BTC public key is a registered vault keeper in a specific version
/// @param appEntryPoint The application entry point address
/// @param btcPubKey The BTC public key to check
/// @param version The version number to check against
/// @return True if the BTC public key is registered as a vault keeper
function isVaultKeeperByBtcKeyInVersion(address appEntryPoint, bytes32 btcPubKey, uint16 version)
external
view
returns (bool);
/// @notice Check if a vault keeper address is blocklisted for an application
/// @param appEntryPoint The application entry point address
/// @param account The vault keeper Ethereum address
/// @return True if the vault keeper is blocklisted
function isBlocklistedVaultKeeper(address appEntryPoint, address account) external view returns (bool);
/// @notice Validate that a vault keeper BTC key can redeem for an application at a bonded version+epoch
/// @param appEntryPoint The application entry point address
/// @param btcPubKey The vault keeper BTC public key
/// @param appVaultKeepersVersion The vault's frozen keeper membership version
/// @param appKeeperKeyEpoch The vault's frozen keeper operation-key epoch
/// @dev Confirms the keeper is a member of the frozen membership version and that the supplied key
/// is the keeper's op-key bonded at `appKeeperKeyEpoch` (genesis = the frozen-version roster key).
/// @dev Reverts with `UnauthorizedVaultKeeper` or `BlocklistedVaultKeeper`
function assertVaultKeeperCanRedeem(
address appEntryPoint,
bytes32 btcPubKey,
uint16 appVaultKeepersVersion,
uint64 appKeeperKeyEpoch
) external view;
// ========== Operation Key / Payout Versioning ==========
/// @notice Current per-app keeper operation-key epoch
function appKeeperKeyEpochCurrent(address appEntryPoint) external view returns (uint64);
/// @notice Append a new keeper operation BTC key version (admin-gated, new-key self-PoP)
function setOperationBtcKey(address appEntryPoint, bytes32 newOpBtcKey, bytes calldata btcPopSignature) external;
/// @notice Append a new keeper operation ETH (relay/ACK) key version (admin-gated, new-key self-PoP)
function setOperationEthKey(address appEntryPoint, address newOpEthKey, bytes calldata ethPopSignature) external;
/// @notice Append a new keeper payout script version (admin-gated, no PoP)
function setPayoutScript(address appEntryPoint, bytes calldata newPayoutScript) external;
/// @notice Latest keeper operation BTC key version (0 = genesis roster key)
function latestOperationBtcKeyVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);
/// @notice Keeper operation BTC key at a specific version (v0 = genesis roster key)
function getOperationBtcKeyByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
external
view
returns (bytes32);
/// @notice Current (latest) keeper operation BTC key
function getCurrentOperationBtcKey(address appEntryPoint, address keeperAdmin) external view returns (bytes32);
/// @notice Latest keeper operation ETH key version (0 = admin default)
function latestOperationEthKeyVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);
/// @notice Keeper operation ETH key at a specific version (v0 = keeperAdmin)
function getOperationEthKeyByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
external
view
returns (address);
/// @notice Current (latest) keeper operation ETH key
function getCurrentOperationEthKey(address appEntryPoint, address keeperAdmin) external view returns (address);
/// @notice Latest keeper payout script version (0 = legacy/default BIP-86)
function latestPayoutScriptVersion(address appEntryPoint, address keeperAdmin) external view returns (uint16);
/// @notice Keeper payout script at a specific version (v0 = BIP-86 of op-key v0)
function getPayoutScriptByVersion(address appEntryPoint, address keeperAdmin, uint16 version)
external
view
returns (bytes memory);
/// @notice Current (latest) keeper payout script (BIP-86 default when none set)
function getCurrentPayoutScript(address appEntryPoint, address keeperAdmin) external view returns (bytes memory);
/// @notice Keeper operation BTC key bonded to a vault's epoch (v0 = genesis roster key)
function getOperationBtcKeyAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
external
view
returns (bytes32);
/// @notice Keeper operation BTC key bonded to a vault's epoch against an explicit roster-version
/// genesis: latest op-key version whose epoch <= bonded epoch, else `rosterGenesisKey`
/// @dev The caller supplies the keeper's key from the vault's FROZEN membership version as the v0
/// genesis. Correct even if the keeper rotated across versions or was later dropped from the roster.
function getOperationBtcKeyAtEpochOrGenesis(
address appEntryPoint,
address keeperAdmin,
uint64 epoch,
bytes32 rosterGenesisKey
) external view returns (bytes32);
/// @notice Keeper operation ETH key bonded to a vault's epoch (v0 = keeperAdmin)
function getOperationEthKeyAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
external
view
returns (address);
/// @notice Keeper payout script bonded to a vault's epoch (v0 = BIP-86 of op-key v0)
function getPayoutScriptAtEpoch(address appEntryPoint, address keeperAdmin, uint64 epoch)
external
view
returns (bytes memory);
}
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/interfaces/ICapPolicy.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
/// @title ICapPolicy
/// @notice Interface for application BTC caps and the global live-vault cap
interface ICapPolicy {
/// @notice Application-specific BTC cap parameters
/// @dev Zero values indicate no cap is enforced
struct ApplicationCapParams {
/// @notice Maximum total BTC that can be locked across all users for this application (in satoshis)
/// @dev Zero value means unlimited
uint256 totalCapBTC;
/// @notice Maximum BTC that can be locked per Ethereum address for this application (in satoshis)
/// @dev Zero value means unlimited
uint256 perAddressCapBTC;
}
/// @notice Global live-vault cap parameters
/// @dev A vault is "live" while it remains eligible for high-priority Bitcoin challenge
/// protection. The cap is protocol-wide, not per-application.
struct LiveVaultCapParams {
/// @notice Maximum number of concurrently live vaults across the whole protocol
/// @dev Zero value disables the admission gate; live-vault tracking still runs
uint256 maxLiveVaults;
/// @notice Delay in ETH blocks between a release trigger and the slot release
uint256 liveVaultReleaseDelay;
}
// ========== Events ==========
/// @notice Emitted when application caps are updated
/// @param appEntryPoint The application entry point address
/// @param totalCapBTC The new total cap (0 = unlimited)
/// @param perAddressCapBTC The new per-address cap (0 = unlimited)
event ApplicationCapsUpdated(address indexed appEntryPoint, uint256 totalCapBTC, uint256 perAddressCapBTC);
/// @notice Emitted when the global live-vault cap parameters are updated
/// @param maxLiveVaults The new live-vault cap (0 = admission gate disabled)
/// @param liveVaultReleaseDelay The new slot-release delay in ETH blocks
event LiveVaultCapParamsUpdated(uint256 maxLiveVaults, uint256 liveVaultReleaseDelay);
/// @notice Emitted when high-priority protection ends for a vault at a known block
/// @param vaultId The vault identifier
/// @param releaseBlock The ETH block at which the vault leaves the protected set
event LiveVaultProtectionReleaseScheduled(bytes32 indexed vaultId, uint256 releaseBlock);
// ========== Configuration Functions ==========
/// @notice Set BTC caps for an application
/// @param appEntryPoint The application entry point address
/// @param caps The cap parameters (totalCapBTC and perAddressCapBTC, 0 = unlimited)
/// @dev Can only be called by admin
function setApplicationCaps(address appEntryPoint, ApplicationCapParams calldata caps) external;
/// @notice Get BTC caps for an application
/// @param appEntryPoint The application entry point address
/// @return caps The cap parameters for the application
function getApplicationCaps(address appEntryPoint) external view returns (ApplicationCapParams memory caps);
// ========== Validation Functions ==========
/// @notice Check if adding vaultAmount would exceed caps
/// @param appEntryPoint The application entry point address
/// @param user The user address
/// @param vaultAmount The amount to add in satoshis
/// @return True if caps would not be exceeded
function checkAvailableCap(address appEntryPoint, address user, uint256 vaultAmount) external view returns (bool);
// ========== Tracking Functions ==========
/// @notice Increment BTC usage tracking when vault is activated
/// @param appEntryPoint The application entry point address
/// @param user The user address
/// @param vaultAmount The amount to increment in satoshis
/// @return success True if caps not exceeded and tracking was updated, false if caps exceeded
/// @dev Only callable by authorized caller (BTCVaultRegistry)
/// @dev When false is returned, caps were exceeded and tracking was NOT updated
/// @dev Tracks usage even when caps are not set (cap == 0)
function incrementUsage(address appEntryPoint, address user, uint256 vaultAmount) external returns (bool success);
/// @notice Decrement BTC usage tracking when vault is redeemed
/// @param appEntryPoint The application entry point address
/// @param user The user address
/// @param vaultAmount The amount to decrement in satoshis
/// @dev Only callable by authorized caller (BTCVaultRegistry)
/// @dev Clamps to zero if accounting is inconsistent
/// @dev Tracks usage even when caps are not set (cap == 0)
function decrementUsage(address appEntryPoint, address user, uint256 vaultAmount) external;
// ========== Query Functions ==========
/// @notice Get total BTC locked in an application
/// @param appEntryPoint The application entry point address
/// @return total Total BTC locked across all users
function getApplicationTotalBTC(address appEntryPoint) external view returns (uint256 total);
/// @notice Get BTC locked by a user in an application
/// @param appEntryPoint The application entry point address
/// @param user The user address
/// @return userTotal Total BTC locked by the user
function getApplicationUserBTC(address appEntryPoint, address user) external view returns (uint256 userTotal);
/// @notice Get available capacity before hitting the application total cap
/// @param appEntryPoint The application entry point address
/// @return remaining Remaining capacity before total cap (type(uint256).max if no cap)
function getAvailableAppCapacity(address appEntryPoint) external view returns (uint256 remaining);
/// @notice Get available capacity before hitting the per-address cap for a user
/// @param appEntryPoint The application entry point address
/// @param user The user address
/// @return remaining Remaining capacity before per-address cap (type(uint256).max if no cap)
function getAvailableUserAppCapacity(address appEntryPoint, address user) external view returns (uint256 remaining);
// ========== Global Live-Vault Cap ==========
/// @notice Set the global live-vault cap parameters
/// @param params The cap parameters (maxLiveVaults = 0 disables the admission gate)
/// @dev Can only be called by admin
/// @dev The release delay cannot exceed the protocol maximum or decrease while releases are queued
function setLiveVaultCapParams(LiveVaultCapParams calldata params) external;
/// @notice Get the global live-vault cap parameters
/// @return params The live-vault cap parameters
function getLiveVaultCapParams() external view returns (LiveVaultCapParams memory params);
/// @notice Reserve a live-vault slot for a new pegin request
/// @dev Only callable by authorized caller (BTCVaultRegistry)
/// @dev Releases one matured queue entry, enforces the admission gate, and increments the
/// live count atomically; reverts with `LiveVaultCapExceeded` when the gate is enabled
/// and no capacity remains. Tracks even when the gate is disabled (maxLiveVaults == 0)
function reserveLiveVault() external;
/// @notice Release a live-vault slot immediately (AckTimeout-expired vaults)
/// @param vaultId The vault identifier
/// @dev Only callable by authorized caller (BTCVaultRegistry)
/// @dev Clamps the live-vault count at zero
function releaseLiveVault(bytes32 vaultId) external;
/// @notice Schedule a live-vault slot release
/// @param vaultId The vault identifier
/// @dev Only callable by authorized caller (BTCVaultRegistry)
/// @dev The slot releases exactly `liveVaultReleaseDelay` blocks after the current block
function scheduleLiveVaultRelease(bytes32 vaultId) external;
/// @notice Release live-vault slots for matured release queue entries
/// @param maxReleases Upper bound on entries to release from the queue
/// @dev Permissionless; no-op when nothing has matured
function releaseSettledVaults(uint256 maxReleases) external;
/// @notice Get the number of vaults currently holding a live-vault slot
/// @return count Reserved slots, including matured releases not yet processed
function getLiveVaultCount() external view returns (uint256 count);
/// @notice Get remaining capacity before hitting the global live-vault cap
/// @return remaining Remaining live-vault slots (type(uint256).max if the gate is disabled)
function getAvailableLiveVaultCapacity() external view returns (uint256 remaining);
/// @notice Get the number of pending entries in the release queue
/// @return pending Entries in the release queue, including matured entries
function getSettlementQueueLength() external view returns (uint256 pending);
}
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/helpers/BTCUtils.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
import "./OpCodes.sol";
import {CompactSize} from "./CompactSize.sol";
/**
* @title BTCUtils
* @notice This library contains functionality to make easier to work with Bitcoin transactions in Solidity.
* @notice This library is based in this document:
* https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format
*/
library BTCUtils {
uint256 private constant HASH160_SIZE = 20;
uint256 private constant SHA256_SIZE = 32;
uint256 private constant TAPROOT_PUBKEY_SIZE = 32;
uint8 private constant OUTPOINT_SIZE = 36;
uint8 private constant OUTPUT_VALUE_SIZE = 8;
uint8 private constant PUBKEY_HASH_START = 3;
bytes1 private constant PUBKEY_HASH_MAINNET_BYTE = 0x00;
bytes1 private constant PUBKEY_HASH_TESTNET_BYTE = 0x6f;
uint8 private constant SCRIPT_HASH_START = 2;
bytes1 private constant SCRIPT_HASH_MAINNET_BYTE = 0x05;
bytes1 private constant SCRIPT_HASH_TESTNET_BYTE = 0xc4;
uint256 private constant BECH32_WORD_SIZE = 5;
uint256 private constant BYTE_SIZE = 8;
bytes1 private constant WITNESS_VERSION_0 = 0x00;
bytes1 private constant WITNESS_VERSION_1 = 0x01;
/**
* @notice This struct contains the information of a tx output separated by fields
* @notice Its just to have a structured representation of the output
*
*/
struct TxRawOutput {
uint64 value;
bytes pkScript;
uint256 scriptSize;
uint256 totalSize;
}
function version() external pure returns (string memory) {
return "0.2.1";
}
/// @notice Read the number of inputs declared by a raw transaction
/// @param rawTx the raw transaction
/// @return The input count decoded from the transaction's CompactSize input counter
/// @dev Reads only the version, the optional SegWit marker/flag and the counter, so the cost is
/// independent of the input count. Callers that must bound a caller-supplied transaction use
/// this instead of `getOutputs`, whose per-input walk is the work being bounded. The length
/// guard covers unvalidated calldata, where a transaction too short to hold the marker would
/// otherwise panic on the index rather than report `BufferTooShort`. It admits every length
/// that can hold both marker bytes, so this function and `getOutputs` always agree on whether
/// a given transaction is SegWit.
function getInputCount(bytes calldata rawTx) public pure returns (uint64) {
uint256 currentPosition = 4;
if (rawTx.length >= 6 && rawTx[4] == 0x00 && rawTx[5] == 0x01) {
// if its segwit, skip marker and flag
currentPosition = 6;
}
uint64 inputCount;
(inputCount,) = CompactSize.decodeCalldata(rawTx, currentPosition);
return inputCount;
}
/// @notice Parse a raw transaction to get an array of its outputs in a structured representation
/// @param rawTx the raw transaction
/// @return An array of `TxRawOutput` with the outputs of the transaction
function getOutputs(bytes calldata rawTx) public pure returns (TxRawOutput[] memory) {
uint256 currentPosition = 4;
if (rawTx[4] == 0x00 && rawTx[5] == 0x01) {
// if its segwit, skip marker and flag
currentPosition = 6;
}
uint64 inputCount;
(inputCount, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);
uint64 scriptLarge;
for (uint64 i = 0; i < inputCount; i++) {
currentPosition += OUTPOINT_SIZE;
(scriptLarge, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);
currentPosition += scriptLarge + 4;
}
uint64 outputCount;
(outputCount, currentPosition) = CompactSize.decodeCalldata(rawTx, currentPosition);
TxRawOutput[] memory result = new TxRawOutput[](outputCount);
for (uint256 i = 0; i < outputCount; i++) {
result[i] = extractRawOutput(currentPosition, rawTx);
currentPosition += result[i].totalSize;
}
return result;
}
function extractRawOutput(uint256 position, bytes calldata rawTx) private pure returns (TxRawOutput memory) {
uint256 startPosition = position;
TxRawOutput memory result = TxRawOutput(0, "", 0, 0);
result.value = CompactSize.readUint64LECalldata(rawTx, position);
position += OUTPUT_VALUE_SIZE;
uint64 scriptLength;
(scriptLength, position) = CompactSize.decodeCalldata(rawTx, position);
result.pkScript = rawTx[position:position + scriptLength];
result.scriptSize = scriptLength;
result.totalSize = position + scriptLength - startPosition;
return result;
}
/// @notice Parse a raw output script whose type is not known by the consumer. The function will
/// return the corresponding address if the type of the script is supported or an error if not.
/// For the addresses that are encoded with base58check the checksum bytes are not included in
/// the resulting byte array
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @param mainnet if the address to generate is from mainnet or testnet
/// @return The address bytes regarless of the output script type
function outputScriptToAddress(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
if (isP2PKHOutput(outputScript)) {
return parsePayToPubKeyHash(outputScript, mainnet);
}
if (isP2SHOutput(outputScript)) {
return parsePayToScriptHash(outputScript, mainnet);
}
if (isP2WPKHOutput(outputScript)) {
return parsePayToWitnessPubKeyHash(outputScript);
}
if (isP2WSHOutput(outputScript)) {
return parsePayToWitnessScriptHash(outputScript);
}
if (isP2TROutput(outputScript)) {
return parsePayToTaproot(outputScript);
}
revert("Unsupported script type");
}
/// @notice Check if a raw output script is a pay-to-public-key-hash output
/// @param pkScript the fragment of the raw transaction containing the raw output script
/// @return Whether the script has a pay-to-public-key-hash output structure or not
function isP2PKHOutput(bytes memory pkScript) public pure returns (bool) {
return pkScript.length == 25
&& bytes25(pkScript) & 0xFFFFFF0000000000000000000000000000000000000000FFFF
== 0x76A914000000000000000000000000000000000000000088AC;
}
/// @notice Check if a raw output script is a pay-to-script-hash output
/// @param pkScript the fragment of the raw transaction containing the raw output script
/// @return Whether the script has a pay-to-script-hash output structure or not
function isP2SHOutput(bytes memory pkScript) public pure returns (bool) {
return pkScript.length == 23
&& bytes23(pkScript) & 0xFFFF0000000000000000000000000000000000000000FF
== 0xA914000000000000000000000000000000000000000087;
}
/// @notice Check if a raw output script is a pay-to-witness-pubkey-hash output
/// @param pkScript the fragment of the raw transaction containing the raw output script
/// @return Whether the script has a pay-to-witness-pubkey-hash output structure or not
function isP2WPKHOutput(bytes memory pkScript) public pure returns (bool) {
return pkScript.length == 22 && bytes2(pkScript) == 0x0014;
}
/// @notice Check if a raw output script is a pay-to-witness-script-hash output
/// @param pkScript the fragment of the raw transaction containing the raw output script
/// @return Whether the script has a pay-to-witness-script-hash output structure or not
function isP2WSHOutput(bytes memory pkScript) public pure returns (bool) {
return pkScript.length == 34 && bytes2(pkScript) == 0x0020;
}
/// @notice Check if a raw output script is a pay-to-taproot output
/// @notice Reference for implementation: https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
/// @param pkScript the fragment of the raw transaction containing the raw output script
/// @return Whether the script has a pay-to-taproot output structure or not
function isP2TROutput(bytes memory pkScript) public pure returns (bool) {
return pkScript.length == 34 && bytes2(pkScript) == 0x5120;
}
/// @notice Parse a raw pay-to-public-key-hash output script to get the corresponding address,
/// the resulting byte array doesn't include the checksum bytes of the base58check encoding at
/// the end
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @param mainnet if the address to generate is from mainnet or testnet
/// @return The address generated using the receiver's public key hash
function parsePayToPubKeyHash(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
require(isP2PKHOutput(outputScript), "Script hasn't the required structure");
bytes memory destinationAddress = new bytes(HASH160_SIZE + 1);
for (uint256 i = PUBKEY_HASH_START; i < HASH160_SIZE + PUBKEY_HASH_START; i++) {
destinationAddress[i - PUBKEY_HASH_START + 1] = outputScript[i];
}
destinationAddress[0] = mainnet ? PUBKEY_HASH_MAINNET_BYTE : PUBKEY_HASH_TESTNET_BYTE;
return destinationAddress;
}
/// @notice Parse a raw pay-to-script-hash output script to get the corresponding address,
/// the resulting byte array doesn't include the checksum bytes of the base58check encoding at
/// the end
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @param mainnet if the address to generate is from mainnet or testnet
/// @return The address generated using the script hash
function parsePayToScriptHash(bytes calldata outputScript, bool mainnet) public pure returns (bytes memory) {
require(isP2SHOutput(outputScript), "Script hasn't the required structure");
bytes memory destinationAddress = new bytes(HASH160_SIZE + 1);
for (uint256 i = SCRIPT_HASH_START; i < HASH160_SIZE + SCRIPT_HASH_START; i++) {
destinationAddress[i - SCRIPT_HASH_START + 1] = outputScript[i];
}
destinationAddress[0] = mainnet ? SCRIPT_HASH_MAINNET_BYTE : SCRIPT_HASH_TESTNET_BYTE;
return destinationAddress;
}
/// @notice Parse a raw pay-to-witness-pubkey-hash output script to get the corresponding address words,
/// the resulting words are only the data part of the bech32 encoding and doesn't include the HRP
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @return The address bech32 words generated using the pubkey hash
function parsePayToWitnessPubKeyHash(bytes calldata outputScript) public pure returns (bytes memory) {
require(isP2WPKHOutput(outputScript), "Script hasn't the required structure");
uint256 length = 1 + total5BitWords(HASH160_SIZE);
bytes memory result = new bytes(length);
result[0] = WITNESS_VERSION_0;
bytes memory words = to5BitWords(outputScript[2:]);
for (uint256 i = 1; i < length; i++) {
result[i] = words[i - 1];
}
return result;
}
/// @notice Parse a raw pay-to-witness-script-hash output script to get the corresponding address words,
/// the resulting words are only the data part of the bech32 encoding and doesn't include the HRP
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @return The address bech32 words generated using the script hash
function parsePayToWitnessScriptHash(bytes calldata outputScript) public pure returns (bytes memory) {
require(isP2WSHOutput(outputScript), "Script hasn't the required structure");
uint256 length = 1 + total5BitWords(SHA256_SIZE);
bytes memory result = new bytes(length);
result[0] = WITNESS_VERSION_0;
bytes memory words = to5BitWords(outputScript[2:]);
for (uint256 i = 1; i < length; i++) {
result[i] = words[i - 1];
}
return result;
}
/// @notice Parse a raw pay-to-taproot output script to get the corresponding address words,
/// the resulting words are only the data part of the bech32m encoding and doesn't include the HRP
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @return The address bech32m words generated using the taproot pubkey hash
function parsePayToTaproot(bytes calldata outputScript) public pure returns (bytes memory) {
require(isP2TROutput(outputScript), "Script hasn't the required structure");
uint256 length = 1 + total5BitWords(TAPROOT_PUBKEY_SIZE);
bytes memory result = new bytes(length);
result[0] = WITNESS_VERSION_1;
bytes memory words = to5BitWords(outputScript[2:]);
for (uint256 i = 1; i < length; i++) {
result[i] = words[i - 1];
}
return result;
}
/// @notice Parse a raw null-data output script to get its content
/// @param outputScript the fragment of the raw transaction containing the raw output script
/// @return The content embedded inside the script
function parseNullDataScript(bytes calldata outputScript) public pure returns (bytes memory) {
require(outputScript.length > 1, "Invalid size");
require(outputScript[0] == OpCodes.OP_RETURN, "Not OP_RETURN");
return outputScript[1:];
}
/// @notice Hash a bitcoin raw transaction to get its txid (reversed double sha256)
/// @param btcTx the transaction to hash (supports both legacy and segwit serialization)
/// @return The transaction id (txid), NOT the witness txid (wtxid)
/// @dev For segwit transactions, strips the marker, flag, and witness data before hashing
/// to compute the correct txid per BIP-141
function hashBtcTx(bytes calldata btcTx) public pure returns (bytes32) {
bytes memory toHash;
// Detect segwit serialization: marker=0x00 flag=0x01 at bytes[4:6]
if (btcTx.length > 6 && btcTx[4] == 0x00 && btcTx[5] == 0x01) {
toHash = _stripWitnessData(btcTx);
} else {
toHash = btcTx;
}
return _reverseBytes32(sha256(abi.encodePacked(sha256(toHash))));
}
/// @dev Reverse the byte order of a 32-byte word in a single pass via masked
/// shifts. Swap adjacent 1, 2, 4, 8, and 16-byte groups (O(log n)).
function _reverseBytes32(bytes32 v) private pure returns (bytes32) {
v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8)
| ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16)
| ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32)
| ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64)
| ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (v >> 128) | (v << 128);
}
/// @notice Strip witness data from a segwit transaction to produce non-witness serialization
/// @param btcTx Segwit-serialized transaction (must have marker=0x00, flag=0x01 at bytes[4:6])
/// @return Non-witness serialization: version | inputs | outputs | locktime
/// @dev Per BIP-141, txid is computed from non-witness serialization
function _stripWitnessData(bytes calldata btcTx) private pure returns (bytes memory) {
// Parse past inputs and outputs to find where witness data begins
uint256 pos = 6; // skip version(4) + marker(1) + flag(1)
// Parse inputs
uint64 inputCount;
(inputCount, pos) = CompactSize.decodeCalldata(btcTx, pos);
for (uint64 i = 0; i < inputCount; i++) {
pos += OUTPOINT_SIZE; // prevout (txid + vout)
uint64 scriptLen;
(scriptLen, pos) = CompactSize.decodeCalldata(btcTx, pos);
pos += scriptLen + 4; // scriptSig + sequence
}
// Parse outputs
uint64 outputCount;
(outputCount, pos) = CompactSize.decodeCalldata(btcTx, pos);
for (uint64 i = 0; i < outputCount; i++) {
pos += OUTPUT_VALUE_SIZE; // value
uint64 scriptLen;
(scriptLen, pos) = CompactSize.decodeCalldata(btcTx, pos);
pos += scriptLen; // scriptPubKey
}
// pos now points to start of witness data; locktime is last 4 bytes.
// Reject txs where witness+locktime don't fit after the parsed body,
// otherwise btcTx[6:pos] and btcTx[length-4:] overlap and the last 4
// bytes of the body get reused as locktime, producing a wrong txid.
if (pos + 4 > btcTx.length) revert CompactSize.BufferTooShort(pos, pos + 4, btcTx.length);
// Construct: version(4) + inputs_and_outputs(btcTx[6:pos]) + locktime(4)
return abi.encodePacked(btcTx[:4], btcTx[6:pos], btcTx[btcTx.length - 4:]);
}
/// @dev Gets the timestamp of a Bitcoin block header
/// @param header The block header
/// @return The timestamp of the block header
function getBtcBlockTimestamp(bytes memory header) public pure returns (uint256) {
// bitcoin header is 80 bytes and timestamp is 4 bytes from byte 68 to byte 71 (both inclusive)
require(header.length == 80, "Invalid header length");
return sliceUint32FromLSB(header, 68);
}
// bytes must have at least 28 bytes before the uint32
function sliceUint32FromLSB(bytes memory bs, uint256 offset) private pure returns (uint32) {
require(bs.length >= offset + 4, "Slicing out of range");
return uint32(uint8(bs[offset])) | (uint32(uint8(bs[offset + 1])) << 8) | (uint32(uint8(bs[offset + 2])) << 16)
| (uint32(uint8(bs[offset + 3])) << 24);
}
/// @notice Referece for implementation: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki
function to5BitWords(bytes memory byteArray) private pure returns (bytes memory) {
uint8 MAX_VALUE = 31;
uint256 currentValue = 0;
uint256 bitCount = 0;
uint8 resultIndex = 0;
bytes memory result = new bytes(total5BitWords(byteArray.length));
for (uint256 i = 0; i < byteArray.length; ++i) {
currentValue = (currentValue << BYTE_SIZE) | uint8(byteArray[i]);
bitCount += BYTE_SIZE;
while (bitCount >= BECH32_WORD_SIZE) {
bitCount -= BECH32_WORD_SIZE;
// this mask ensures that the result will always have 5 bits
result[resultIndex] = bytes1(uint8((currentValue >> bitCount) & MAX_VALUE));
resultIndex++;
}
}
if (bitCount > 0) {
result[resultIndex] = bytes1(uint8((currentValue << (BECH32_WORD_SIZE - bitCount)) & MAX_VALUE));
}
return result;
}
function total5BitWords(uint256 numberOfBytes) private pure returns (uint256) {
uint256 total = (numberOfBytes * BYTE_SIZE) / BECH32_WORD_SIZE;
bool extraWord = (numberOfBytes * BYTE_SIZE) % BECH32_WORD_SIZE == 0;
return total + (extraWord ? 0 : 1);
}
}
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/OpCodes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;
library OpCodes {
// Basic opcodes
bytes1 internal constant OP_0 = 0x00;
bytes1 internal constant OP_1 = 0x51;
// Stack manipulation
bytes1 internal constant OP_DUP = 0x76;
bytes1 internal constant OP_DROP = 0x75;
// Crypto operations
bytes1 internal constant OP_HASH160 = 0xa9;
bytes1 internal constant OP_CHECKSIG = 0xac;
bytes1 internal constant OP_CHECKSIGVERIFY = 0xad;
bytes1 internal constant OP_CHECKSIGADD = 0xba; // BIP342 Tapscript
// Comparison
bytes1 internal constant OP_EQUAL = 0x87;
bytes1 internal constant OP_EQUALVERIFY = 0x88;
// Numeric operations
bytes1 internal constant OP_NUMEQUAL = 0x9c;
bytes1 internal constant OP_NUMEQUALVERIFY = 0x9d;
// Flow control
bytes1 internal constant OP_IF = 0x63;
bytes1 internal constant OP_ELSE = 0x67;
bytes1 internal constant OP_ENDIF = 0x68;
bytes1 internal constant OP_RETURN = 0x6a;
// Locktime
bytes1 internal constant OP_CHECKSEQUENCEVERIFY = 0xb2;
// Push data opcodes
bytes1 internal constant PUSH_20 = 0x14; // 20 bytes
bytes1 internal constant PUSH_32 = 0x20; // 32 bytes
// Push data with length prefix
bytes1 internal constant OP_PUSHDATA1 = 0x4c; // Next byte contains length
bytes1 internal constant OP_PUSHDATA2 = 0x4d; // Next 2 bytes contain length
bytes1 internal constant OP_PUSHDATA4 = 0x4e; // Next 4 bytes contain length
}
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/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/protocol/lib/types/Events.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Events {
// =============================================================================
// REGISTRATION EVENTS
// =============================================================================
/// @notice Event emitted when a vault provider is registered
/// @param provider The provider address
/// @param btcPubKey The provider's x-only BTC public key
/// @param applicationEntryPoint The application this provider is registered for
/// @param commissionBps The provider's peg-out commission in basis points
/// @param payoutScriptPubKey The provider's required payout scriptPubKey, stored as payout v1
event VaultProviderRegistered(
address indexed provider,
bytes32 btcPubKey,
address indexed applicationEntryPoint,
uint16 commissionBps,
bytes payoutScriptPubKey
);
/// @notice Event emitted when a vault provider updates their commission
/// @param provider The provider address
/// @param newCommissionBps The new commission in basis points
event VaultProviderCommissionUpdated(address indexed provider, uint16 newCommissionBps);
// =============================================================================
// APPLICATION EVENTS
// =============================================================================
/// @notice Event emitted when a vault can be claimed (for ZK proof generation)
/// @param vaultId The vault identifier
/// @param peginTxHash The raw Bitcoin peg-in transaction hash
/// @param claimerPK The BTC public key authorized to claim this vault
/// @param vaultCoreVersion Vault Core protocol version stamped on this vault at peg-in (RFC 004)
/// @param proverCircuitVersion Prover circuit version (universal SP1 ELF set) for this vault
/// @param offchainParamsVersion Version of offchain parameters for this vault
/// @param universalChallengersVersion Version of universal challengers for this vault
/// @param appVaultKeepersVersion Version of application vault keepers for this vault
event VaultClaimableBy(
bytes32 indexed vaultId,
bytes32 indexed peginTxHash,
bytes32 indexed claimerPK,
uint16 vaultCoreVersion,
uint16 proverCircuitVersion,
uint16 offchainParamsVersion,
uint16 universalChallengersVersion,
uint16 appVaultKeepersVersion
);
/// @notice Event emitted when an ACK is submitted for a pegin request
event PeginACKSubmitted(bytes32 indexed vaultId, address indexed ackers);
/// @notice Event emitted when a pegin request is verified
event PeginRequestVerified(bytes32 indexed vaultId, address indexed depositor);
/// @notice Event emitted when a pegin request is submitted
/// @param vaultId The vault identifier derived from peginTxHash + depositor
/// @param peginTxHash The raw Bitcoin peg-in transaction hash
/// @param depositor The depositor address
/// @param vaultProvider The vault provider address
/// @param amount The amount of BTC in the vault
/// @param vaultCoreVersion Vault Core protocol version stamped on this vault at peg-in (RFC 004)
/// @param universalChallengersVersion Version of universal challengers for this vault
/// @param appVaultKeepersVersion Version of application vault keepers for this vault
/// @param proverCircuitVersion Version of prover circuit (universal SP1 ELF set) for this vault
/// @param offchainParamsVersion Version of offchain parameters for this vault
/// @param referralCode Referral attribution code (0 if unused)
/// @param depositorPayoutBtcAddress Depositor-specified BTC payout address (scriptPubKey)
/// @param depositorWotsPkHash keccak256(depositorWotsPublicKey) for VP authentication
/// @param hashlock The SHA256 hashlock h
/// @param btcPopSignature Depositor BTC proof of possession (DA only)
/// @param htlcVout Index of the HTLC output in the Pre-PegIn transaction that this PegIn spends
/// @param unsignedPrePeginTx The unsigned pre-pegin transaction (DA only)
/// @param depositorSignedPeginTx The depositor-signed pegin transaction (DA only)
/// @param vpKeyEpoch VP operation-key epoch the vault bonds against
/// @param appKeeperKeyEpoch App-keeper operation-key epoch the vault bonds against
/// @param ucKeyEpoch Universal-challenger operation-key epoch the vault bonds against
/// @param maxAcceptableCommissionBps Depositor-approved upper bound (inclusive) on the VP's
/// commission in basis points, as submitted with the request
event PegInSubmitted(
bytes32 indexed vaultId,
bytes32 indexed peginTxHash,
address indexed depositor,
address vaultProvider,
uint256 amount,
uint16 vaultCoreVersion,
uint16 universalChallengersVersion,
uint16 appVaultKeepersVersion,
uint16 proverCircuitVersion,
uint16 offchainParamsVersion,
uint32 referralCode,
bytes depositorPayoutBtcAddress,
bytes32 depositorWotsPkHash,
bytes32 hashlock,
bytes btcPopSignature,
uint8 htlcVout,
bytes unsignedPrePeginTx,
bytes depositorSignedPeginTx,
uint64 vpKeyEpoch,
uint64 appKeeperKeyEpoch,
uint64 ucKeyEpoch,
uint16 maxAcceptableCommissionBps
);
/// @notice Non-indexed data payload of `PegInSubmitted`
/// @dev Member order/types mirror the non-indexed `PegInSubmitted` parameters exactly, so
/// `abi.encode` of this struct equals the event's data section.
struct PegInSubmittedData {
address vaultProvider;
uint256 amount;
uint16 vaultCoreVersion;
uint16 universalChallengersVersion;
uint16 appVaultKeepersVersion;
uint16 proverCircuitVersion;
uint16 offchainParamsVersion;
uint32 referralCode;
bytes depositorPayoutBtcAddress;
bytes32 depositorWotsPkHash;
bytes32 hashlock;
bytes btcPopSignature;
uint8 htlcVout;
bytes unsignedPrePeginTx;
bytes depositorSignedPeginTx;
uint64 vpKeyEpoch;
uint64 appKeeperKeyEpoch;
uint64 ucKeyEpoch;
uint16 maxAcceptableCommissionBps;
}
/// @notice Emit `PegInSubmitted` from its three indexed topics and a non-indexed data struct
/// @dev Emits via `abi.encode(data)` + `log4` instead of a 19-argument stack tuple (--ir-minimum
/// stack); topics and data are byte-identical to a direct `emit PegInSubmitted(...)`.
/// @param vaultId Indexed topic 1
/// @param peginTxHash Indexed topic 2
/// @param depositor Indexed topic 3
/// @param data The 19 non-indexed event fields
function emitPegInSubmitted(bytes32 vaultId, bytes32 peginTxHash, address depositor, PegInSubmittedData memory data)
internal
{
bytes memory encoded = abi.encode(data);
bytes32 topic0 = PegInSubmitted.selector;
bytes32 depositorTopic = bytes32(uint256(uint160(depositor)));
// Only reads within the allocated `encoded` array, so the IR pipeline may keep
// its stack-to-memory escape enabled for enclosing functions (--ir-minimum stack).
assembly ("memory-safe") {
// `abi.encode(data)` lays out [len][offset=0x20][tuple...]; the event data section is the
// inline tuple, which starts at encoded+0x40 and has length len-0x20.
let len := mload(encoded)
log4(add(encoded, 0x40), sub(len, 0x20), topic0, vaultId, peginTxHash, depositorTopic)
}
}
/// @notice Event emitted when a vault is activated via secret reveal
/// @param vaultId The vault identifier
/// @param depositor The depositor address
/// @param secret The 32-byte preimage satisfying SHA256(secret) == hashlock
event PeginActivated(bytes32 indexed vaultId, address indexed depositor, bytes32 secret);
/// @notice Event emitted when an `Expired` vault is redeemed via `claimExpiredVault`
/// @dev Off-chain workers consume this event to extract the preimage and construct the
/// BTC-side Claim transaction, mirroring how `PeginActivated` exposes the secret on
/// the standard activation path. Emitted before the two `VaultClaimableBy` events so
/// consumers can stage state before the authorization signal.
/// @param vaultId The vault identifier
/// @param depositor The depositor address recorded at submission time
/// @param secret The 32-byte preimage satisfying SHA256(secret) == hashlock
event ExpiredVaultClaimed(bytes32 indexed vaultId, address indexed depositor, bytes32 secret);
/// @notice Event emitted when a pegin input signature is posted for a specific BTC public key
/// @param vaultId The vault identifier
/// @param btcPubKey The BTC public key this signature is bound to
/// @param submitter The party that submitted the signature candidate
/// @param signature The pegin input signature bytes
event PeginInputSignaturePosted(
bytes32 indexed vaultId, bytes32 indexed btcPubKey, address indexed submitter, bytes signature
);
/// @notice Event emitted when the vault provider posts a pegin input signature batch
/// @param vaultId The vault identifier
/// @param vaultProvider The vault provider who submitted the batch
event PeginInputSignaturesBatchPosted(bytes32 indexed vaultId, address indexed vaultProvider);
/// @notice Reason why a pegin was expired
enum ExpirationReason {
AckTimeout,
ActivationTimeout
}
/// @notice Event emitted when a pegin transaction has expired
event PeginExpired(
bytes32 indexed vaultId, address indexed depositor, address indexed vaultProvider, ExpirationReason reason
);
}
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.