Verified contractExactBUSL-1.1
PeginSignatureLogic
Address0xe5f76f0fe4b4ba0b3179c7093f129ec5df9e72f7
- 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,863
- Creation transaction
- 0x04bb4f0a85…faac0d5412
7 files
- src/protocol/lib/PeginSignatureLogic.solmain16.5 KB
- src/interfaces/IApplicationRegistry.sol15.34 KB
- src/lib/BTCVaultTypes.sol2.18 KB
- src/protocol/interfaces/IProtocolParams.sol15.65 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/PeginSignatureLogic.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 {Errors} from "./types/Errors.sol";
import {Events} from "./types/Events.sol";
/// @title PeginSignatureLogic
/// @notice Pegin input-signature collection logic, 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 and
/// signature storage passed by reference; emitted events therefore log with the registry as
/// emitter and `msg.sender` is the original caller. The registry's three signature mappings
/// are passed individually (not bundled) so the registry's UUPS storage layout is unchanged.
/// The VP op-BTC key bonded to a vault's `vpKeyEpoch` is resolved by the registry and passed in
/// as a value (`vpBondedOpBtcKey`), since the VP key history lives on the registry.
library PeginSignatureLogic {
/// @notice Registry dependencies + the bonded VP slot key bundled to stay under the stack limit
struct Refs {
IApplicationRegistry applicationRegistry;
IProtocolParams protocolParams;
bytes32 vpBondedOpBtcKey;
}
/// @notice Submit a pegin input signature as the vault provider into the VP-batch slot
/// @dev The sender gate is the VP op-ETH key bonded to the vault's `vpKeyEpoch` (v0 = the VP
/// admin), resolved by the registry, so the relay daemon signs with its operation key and
/// the admin can stay cold.
function submitAsVP(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
IApplicationRegistry applicationRegistry,
address vpBondedOpEthKey,
bytes32 vpBondedOpBtcKey,
bytes32 vaultId,
bytes calldata signature
) external {
_validateVaultForSignature(vBasic, applicationRegistry);
if (vpBondedOpEthKey != msg.sender) revert Errors.Unauthorized();
_writeVPSlot(
vpPeginInputSignatures, individualPeginInputSignatures, coverageCounts, vaultId, vpBondedOpBtcKey, signature
);
}
/// @notice Submit a pegin input signature as a vault keeper into its own individual slot
function submitAsVK(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
IApplicationRegistry applicationRegistry,
bytes32 vaultId,
bytes32 btcPubKey,
bytes calldata signature
) external {
_validateVaultForSignature(vBasic, applicationRegistry);
if (!_isAuthorizedVk(applicationRegistry, vBasic, vProtocol, msg.sender, btcPubKey)) {
revert Errors.Unauthorized();
}
_storeIndividualSignature(
vpPeginInputSignatures, individualPeginInputSignatures, coverageCounts, vaultId, btcPubKey, signature
);
}
/// @notice Submit a pegin input signature as a universal challenger into its own individual slot
function submitAsUC(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
IApplicationRegistry applicationRegistry,
IProtocolParams protocolParams,
bytes32 vaultId,
bytes32 btcPubKey,
bytes calldata signature
) external {
_validateVaultForSignature(vBasic, applicationRegistry);
if (!_isAuthorizedUc(protocolParams, vProtocol, msg.sender, btcPubKey)) revert Errors.Unauthorized();
_storeIndividualSignature(
vpPeginInputSignatures, individualPeginInputSignatures, coverageCounts, vaultId, btcPubKey, signature
);
}
/// @notice Batch submit pegin input signatures for a vault as the VP
/// @dev The sender gate is the VP op-ETH key bonded to the vault's `vpKeyEpoch` (v0 = the VP
/// admin), resolved by the registry — same gate as `submitAsVP`.
function submitBatch(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
Refs memory refs,
address vpBondedOpEthKey,
bytes32 vaultId,
bytes32[] calldata btcPubKeys,
bytes[] calldata signatures
) external {
if (btcPubKeys.length != signatures.length) revert Errors.InvalidAmount();
if (btcPubKeys.length == 0) revert Errors.InvalidAmount();
_validateVaultForSignature(vBasic, refs.applicationRegistry);
if (vpBondedOpEthKey != msg.sender) revert Errors.Unauthorized();
bytes32[] memory expectedKeys = _buildExpectedSignatureKeys(vBasic, vProtocol, refs);
if (btcPubKeys.length > expectedKeys.length) revert Errors.InvalidAmount();
uint256 coverageCountBefore = coverageCounts[vaultId];
for (uint256 i = 0; i < btcPubKeys.length; i++) {
bytes32 key = btcPubKeys[i];
if (!_isExpectedKey(expectedKeys, key)) revert Errors.Unauthorized();
_writeVPSlot(
vpPeginInputSignatures, individualPeginInputSignatures, coverageCounts, vaultId, key, signatures[i]
);
}
if (coverageCountBefore < expectedKeys.length && coverageCounts[vaultId] == expectedKeys.length) {
emit Events.PeginInputSignaturesBatchPosted(vaultId, vBasic.vaultProvider);
}
}
/// @notice Get the current pegin input signature for each expected vault participant
function getForVault(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
Refs memory refs,
bytes32 vaultId
)
external
view
returns (bytes32[] memory btcPubKeys, bytes[] memory vpBatchSignatures, bytes[] memory individualSignatures)
{
if (vBasic.depositor == address(0)) revert Errors.BTCVaultNotFound();
btcPubKeys = _buildExpectedSignatureKeys(vBasic, vProtocol, refs);
vpBatchSignatures = new bytes[](btcPubKeys.length);
individualSignatures = new bytes[](btcPubKeys.length);
for (uint256 i = 0; i < btcPubKeys.length; i++) {
bytes32 key = btcPubKeys[i];
vpBatchSignatures[i] = vpPeginInputSignatures[vaultId][key];
individualSignatures[i] = individualPeginInputSignatures[vaultId][key];
}
}
/// @notice Build the expected BTC public keys for pegin input signatures: [VP, VK..., UC...]
/// @dev Excludes depositor — their signature is already in depositorSignedPeginTx. Each slot key is
/// the participant's op-BTC key bonded to the vault's epoch (v0 = roster genesis key): the VP
/// slot via `vpKeyEpoch` (resolved by the registry into `refs.vpBondedOpBtcKey`), each AVK via
/// `appKeeperKeyEpoch`, each UC via `ucKeyEpoch`. The roster (which admins serve) stays frozen
/// at the membership version; only the per-member key resolves against the bonded epoch.
function _buildExpectedSignatureKeys(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
Refs memory refs
) private view returns (bytes32[] memory keys) {
BTCVaultTypes.AddressBTCKeyPair[] memory ucs =
refs.protocolParams.getUniversalChallengersByVersion(vProtocol.universalChallengersVersion);
BTCVaultTypes.AddressBTCKeyPair[] memory vks = refs.applicationRegistry
.getVaultKeepersByVersion(vBasic.applicationEntryPoint, vProtocol.appVaultKeepersVersion);
keys = new bytes32[](1 + vks.length + ucs.length);
keys[0] = refs.vpBondedOpBtcKey;
uint256 idx = 1;
for (uint256 i = 0; i < vks.length; i++) {
keys[idx++] = refs.applicationRegistry
.getOperationBtcKeyAtEpochOrGenesis(
vBasic.applicationEntryPoint, vks[i].ethAddress, vProtocol.appKeeperKeyEpoch, vks[i].btcPubKey
);
}
for (uint256 i = 0; i < ucs.length; i++) {
keys[idx++] = refs.protocolParams
.getOperationBtcKeyAtEpochOrGenesis(ucs[i].ethAddress, vProtocol.ucKeyEpoch, ucs[i].btcPubKey);
}
}
/// @notice Validate a vault is Pending and its application Active before accepting a signature
function _validateVaultForSignature(
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
IApplicationRegistry applicationRegistry
) private view {
if (vBasic.depositor == address(0)) {
revert Errors.BTCVaultNotFound();
}
if (vBasic.status != BTCVaultTypes.BTCVaultStatus.Pending) revert Errors.InvalidBTCVaultStatus();
if (
applicationRegistry.getApplicationStatus(vBasic.applicationEntryPoint)
!= IApplicationRegistry.ApplicationStatus.Active
) {
revert Errors.ApplicationNotActive();
}
}
/// @notice Store an individually submitted pegin input signature into the slot's owner key
/// @dev Writes the individual slot exactly once; coexists with any prior VP-batch signature.
function _storeIndividualSignature(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(
bytes32 => mapping(bytes32 => bytes)
) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
bytes32 vaultId,
bytes32 btcPubKey,
bytes calldata signature
) private {
if (signature.length != 64) revert Errors.InvalidSignatureLength();
if (individualPeginInputSignatures[vaultId][btcPubKey].length != 0) {
revert Errors.PeginInputSignatureAlreadySubmitted();
}
if (vpPeginInputSignatures[vaultId][btcPubKey].length == 0) {
++coverageCounts[vaultId];
}
individualPeginInputSignatures[vaultId][btcPubKey] = signature;
emit Events.PeginInputSignaturePosted(vaultId, btcPubKey, msg.sender, signature);
}
/// @notice Write a VP-sourced signature into the VP-batch slot
/// @dev Reverts if the VP-batch slot is already filled. Coexists with any individual signature
/// submitted by the slot's owner key — both are kept for the off-chain daemon.
function _writeVPSlot(
mapping(bytes32 => mapping(bytes32 => bytes)) storage vpPeginInputSignatures,
mapping(bytes32 => mapping(bytes32 => bytes)) storage individualPeginInputSignatures,
mapping(bytes32 => uint256) storage coverageCounts,
bytes32 vaultId,
bytes32 btcPubKey,
bytes calldata signature
) private {
if (signature.length != 64) revert Errors.InvalidSignatureLength();
if (vpPeginInputSignatures[vaultId][btcPubKey].length != 0) {
revert Errors.PeginInputSignatureAlreadySubmitted();
}
if (individualPeginInputSignatures[vaultId][btcPubKey].length == 0) {
++coverageCounts[vaultId];
}
vpPeginInputSignatures[vaultId][btcPubKey] = signature;
emit Events.PeginInputSignaturePosted(vaultId, btcPubKey, msg.sender, signature);
}
/// @notice True if `signer` is an app vault keeper's op-ETH key bonded at the vault's
/// `appKeeperKeyEpoch` (v0 = the keeper admin) and `btcPubKey` is that keeper's op-BTC
/// key bonded at the same epoch (v0 = roster genesis key)
/// @dev The roster (which admins serve) comes from the frozen membership version; both per-member
/// keys resolve against the bonded epoch, so a keeper relaying with its rotated keys is
/// accepted and one presenting stale keys is not. Matches on the op-BTC key first: op-BTC
/// keys are unique across the roster, so the first entry whose bonded op-BTC equals
/// `btcPubKey` is the only possible match — the op-ETH key is then resolved once and the
/// loop returns, so no entry needs both keys resolved (unlike an op-ETH-first scan, where
/// op-ETH non-uniqueness would force resolving op-BTC on every op-ETH collision).
function _isAuthorizedVk(
IApplicationRegistry applicationRegistry,
BTCVaultTypes.BTCVaultBasicInfo storage vBasic,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
address signer,
bytes32 btcPubKey
) private view returns (bool) {
BTCVaultTypes.AddressBTCKeyPair[] memory keepers = applicationRegistry.getVaultKeepersByVersion(
vBasic.applicationEntryPoint, vProtocol.appVaultKeepersVersion
);
for (uint256 i = 0; i < keepers.length; i++) {
bytes32 bonded = applicationRegistry.getOperationBtcKeyAtEpochOrGenesis(
vBasic.applicationEntryPoint, keepers[i].ethAddress, vProtocol.appKeeperKeyEpoch, keepers[i].btcPubKey
);
if (bonded != btcPubKey) continue;
// op-BTC uniqueness: this is the only entry that can hold `btcPubKey`, so authorize iff
// its bonded op-ETH key is the signer, then return.
return applicationRegistry.getOperationEthKeyAtEpoch(
vBasic.applicationEntryPoint, keepers[i].ethAddress, vProtocol.appKeeperKeyEpoch
) == signer;
}
return false;
}
/// @notice True if `signer` is a universal challenger's op-ETH key bonded at the vault's
/// `ucKeyEpoch` (v0 = the challenger admin) and `btcPubKey` is that challenger's op-BTC
/// key bonded at the same epoch (v0 = roster genesis key)
/// @dev Matches on the op-BTC key first for the same reason as `_isAuthorizedVk`: UC op-BTC keys
/// are unique across the roster, so the first op-BTC match is the only candidate and the
/// loop resolves op-ETH once and returns.
function _isAuthorizedUc(
IProtocolParams protocolParams,
BTCVaultRegistryTypes.BTCVaultProtocolInfo storage vProtocol,
address signer,
bytes32 btcPubKey
) private view returns (bool) {
BTCVaultTypes.AddressBTCKeyPair[] memory challengers =
protocolParams.getUniversalChallengersByVersion(vProtocol.universalChallengersVersion);
for (uint256 i = 0; i < challengers.length; i++) {
bytes32 bonded = protocolParams.getOperationBtcKeyAtEpochOrGenesis(
challengers[i].ethAddress, vProtocol.ucKeyEpoch, challengers[i].btcPubKey
);
if (bonded != btcPubKey) continue;
// op-BTC uniqueness: this is the only entry that can hold `btcPubKey`.
return protocolParams.getOperationEthKeyAtEpoch(challengers[i].ethAddress, vProtocol.ucKeyEpoch) == signer;
}
return false;
}
/// @notice Linear membership check against an expected-key list
function _isExpectedKey(bytes32[] memory expectedKeys, bytes32 key) private pure returns (bool) {
for (uint256 i = 0; i < expectedKeys.length; i++) {
if (expectedKeys[i] == key) return true;
}
return false;
}
}
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/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/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.