@keep-network/tbtc-v2 0.1.1-dev.49 → 0.1.1-dev.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/artifacts/Bank.json +3 -3
- package/artifacts/Bridge.json +201 -114
- package/artifacts/Deposit.json +7 -7
- package/artifacts/EcdsaDkgValidator.json +1 -1
- package/artifacts/EcdsaInactivity.json +1 -1
- package/artifacts/Fraud.json +13 -12
- package/artifacts/KeepRegistry.json +1 -1
- package/artifacts/KeepStake.json +2 -2
- package/artifacts/KeepToken.json +2 -2
- package/artifacts/KeepTokenStaking.json +1 -1
- package/artifacts/MovingFunds.json +32 -9
- package/artifacts/NuCypherStakingEscrow.json +1 -1
- package/artifacts/NuCypherToken.json +2 -2
- package/artifacts/RandomBeaconStub.json +1 -1
- package/artifacts/Redemption.json +9 -9
- package/artifacts/ReimbursementPool.json +2 -2
- package/artifacts/Relay.json +9 -9
- package/artifacts/SortitionPool.json +2 -2
- package/artifacts/Sweep.json +7 -7
- package/artifacts/T.json +2 -2
- package/artifacts/TBTC.json +3 -3
- package/artifacts/TBTCToken.json +3 -3
- package/artifacts/TokenStaking.json +1 -1
- package/artifacts/TokenholderGovernor.json +9 -9
- package/artifacts/TokenholderTimelock.json +8 -8
- package/artifacts/VendingMachine.json +10 -10
- package/artifacts/VendingMachineKeep.json +1 -1
- package/artifacts/VendingMachineNuCypher.json +1 -1
- package/artifacts/WalletRegistry.json +2 -2
- package/artifacts/WalletRegistryGovernance.json +2 -2
- package/artifacts/Wallets.json +7 -7
- package/artifacts/solcInputs/{8c8e22c3576c135e48bf2abb6045923d.json → c0a2aa3c07bd118332a0dc765c7f6da0.json} +4 -4
- package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
- package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
- package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
- package/build/contracts/bridge/Bridge.sol/Bridge.json +115 -38
- package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
- package/build/contracts/bridge/BridgeState.sol/BridgeState.json +10 -4
- package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
- package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
- package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
- package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
- package/build/contracts/bridge/Fraud.sol/Fraud.json +2 -2
- package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
- package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
- package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +15 -2
- package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/OutboundTx.json +2 -2
- package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/Redemption.json +2 -2
- package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +1 -1
- package/build/contracts/bridge/Sweep.sol/Sweep.json +2 -2
- package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
- package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
- package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
- package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
- package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
- package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
- package/contracts/bridge/Bridge.sol +68 -11
- package/contracts/bridge/BridgeState.sol +28 -6
- package/contracts/bridge/Fraud.sol +21 -5
- package/contracts/bridge/MovingFunds.sol +45 -0
- package/export.json +88 -6
- package/package.json +1 -1
|
@@ -128,7 +128,7 @@
|
|
|
128
128
|
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nlibrary EcdsaLib {\n using BytesLib for bytes;\n\n /// @notice Converts public key X and Y coordinates (32-byte each) to a\n /// compressed public key (33-byte). Compressed public key is X\n /// coordinate prefixed with `02` or `03` based on the Y coordinate parity.\n /// It is expected that the uncompressed public key is stripped\n /// (i.e. it is not prefixed with `04`).\n /// @param x Wallet's public key's X coordinate.\n /// @param y Wallet's public key's Y coordinate.\n /// @return Compressed public key (33-byte), prefixed with `02` or `03`.\n function compressPublicKey(bytes32 x, bytes32 y)\n internal\n pure\n returns (bytes memory)\n {\n bytes1 prefix;\n if (uint256(y) % 2 == 0) {\n prefix = hex\"02\";\n } else {\n prefix = hex\"03\";\n }\n\n return bytes.concat(prefix, x);\n }\n}\n"
|
|
129
129
|
},
|
|
130
130
|
"contracts/bridge/BridgeState.sol": {
|
|
131
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n // TODO: Make parameters governable\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint256 txProofDifficultyFactor;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted or not.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint256 redemptionTimeout;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`. The\n // `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request. Timed out requests are stored in this mapping to\n // avoid slashing the wallets multiple times for the same timeout.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping basing on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint256 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 fraudNotifierRewardMultiplier;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation or closing.\n uint64 walletMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation.\n uint64 walletMaxBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n );\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero\n /// - Deposit treasury fee divisor must be greater than zero\n /// - Deposit transaction max fee must be greater than zero\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositTreasuryFeeDivisor > 0,\n \"Deposit treasury fee divisor must be greater than zero\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than zero\n /// - Redemption treasury fee divisor must be greater than zero\n /// - Redemption transaction max fee must be greater than zero\n /// - Redemption timeout must be greater than zero\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout\n ) internal {\n require(\n _redemptionDustThreshold > 0,\n \"Redemption dust threshold must be greater than zero\"\n );\n\n require(\n _redemptionTreasuryFeeDivisor > 0,\n \"Redemption treasury fee divisor must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero\n /// - Moving funds timeout must be greater than zero\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint32 _movingFundsTimeout\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > 0,\n \"Moving funds timeout must be greater than zero\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsTimeout = _movingFundsTimeout;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsTimeout\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested\n /// @param _walletMinBtcBalance New value of the wallet minimum BTC balance\n /// in satoshi, used to decide about wallet creation or closing\n /// @param _walletMaxBtcBalance New value of the wallet maximum BTC balance\n /// in satoshi, used to decide about wallet creation\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance\n /// - Wallet maximum BTC transfer must be greater than zero\n /// - Wallet closing period must be greater than zero\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletMinBtcBalance,\n uint64 _walletMaxBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletMinBtcBalance > 0,\n \"Wallet minimum BTC balance must be greater than zero\"\n );\n require(\n _walletMaxBtcBalance > _walletMinBtcBalance,\n \"Wallet maximum BTC balance must be greater than the minimum\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletMinBtcBalance = _walletMinBtcBalance;\n self.walletMaxBtcBalance = _walletMaxBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletMinBtcBalance,\n _walletMaxBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100]\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit\n /// @dev Requirements:\n /// - Fraud notifier reward multiplier must be in the range [0, 100]\n /// - Fraud challenge defeat timeout must be greater than 0\n function updateFraudParameters(\n Storage storage self,\n uint256 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier,\n uint256 _fraudChallengeDefeatTimeout,\n uint256 _fraudChallengeDepositAmount\n ) internal {\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n\n emit FraudParametersUpdated(\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier,\n _fraudChallengeDefeatTimeout,\n _fraudChallengeDepositAmount\n );\n }\n}\n"
|
|
131
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n // TODO: Make parameters governable\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint256 txProofDifficultyFactor;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted or not.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The minimal satoshi amount that makes sense to be transferred during\n // the moving funds process. Moving funds wallets having their BTC\n // balance below that value can begin closing immediately as\n // transferring such a low value may not be possible due to\n // BTC network fees.\n uint64 movingFundsDustThreshold;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint256 redemptionTimeout;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(walletPubKeyHash | redeemerOutputScript)`. The\n // `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request. Timed out requests are stored in this mapping to\n // avoid slashing the wallets multiple times for the same timeout.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping basing on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint96 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 fraudNotifierRewardMultiplier;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation or closing.\n uint64 walletMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation.\n uint64 walletMaxBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout,\n uint64 movingFundsDustThreshold\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n );\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero\n /// - Deposit treasury fee divisor must be greater than zero\n /// - Deposit transaction max fee must be greater than zero\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositTreasuryFeeDivisor > 0,\n \"Deposit treasury fee divisor must be greater than zero\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than zero\n /// - Redemption treasury fee divisor must be greater than zero\n /// - Redemption transaction max fee must be greater than zero\n /// - Redemption timeout must be greater than zero\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout\n ) internal {\n require(\n _redemptionDustThreshold > 0,\n \"Redemption dust threshold must be greater than zero\"\n );\n\n require(\n _redemptionTreasuryFeeDivisor > 0,\n \"Redemption treasury fee divisor must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param _movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n // be transferred during the moving funds process. Moving funds\n // wallets having their BTC balance below that value can begin\n // closing immediately as transferring such a low value may not be\n // possible due to BTC network fees.\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero\n /// - Moving funds timeout must be greater than zero\n /// - Moving funds dust threshold must be greater than zero\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint32 _movingFundsTimeout,\n uint64 _movingFundsDustThreshold\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > 0,\n \"Moving funds timeout must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0,\n \"Moving funds dust threshold must be greater than zero\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsTimeout = _movingFundsTimeout;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsTimeout,\n _movingFundsDustThreshold\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested\n /// @param _walletMinBtcBalance New value of the wallet minimum BTC balance\n /// in satoshi, used to decide about wallet creation or closing\n /// @param _walletMaxBtcBalance New value of the wallet maximum BTC balance\n /// in satoshi, used to decide about wallet creation\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance\n /// - Wallet maximum BTC transfer must be greater than zero\n /// - Wallet closing period must be greater than zero\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletMinBtcBalance,\n uint64 _walletMaxBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletMinBtcBalance > 0,\n \"Wallet minimum BTC balance must be greater than zero\"\n );\n require(\n _walletMaxBtcBalance > _walletMinBtcBalance,\n \"Wallet maximum BTC balance must be greater than the minimum\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletMinBtcBalance = _walletMinBtcBalance;\n self.walletMaxBtcBalance = _walletMaxBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletMinBtcBalance,\n _walletMaxBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100]\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit\n /// @dev Requirements:\n /// - Fraud notifier reward multiplier must be in the range [0, 100]\n /// - Fraud challenge defeat timeout must be greater than 0\n function updateFraudParameters(\n Storage storage self,\n uint96 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier,\n uint256 _fraudChallengeDefeatTimeout,\n uint256 _fraudChallengeDepositAmount\n ) internal {\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n\n emit FraudParametersUpdated(\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier,\n _fraudChallengeDefeatTimeout,\n _fraudChallengeDepositAmount\n );\n }\n}\n"
|
|
132
132
|
},
|
|
133
133
|
"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": {
|
|
134
134
|
"content": "pragma solidity ^0.8.4;\n\n/*\n\nhttps://github.com/GNSPS/solidity-bytes-utils/\n\nThis is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <https://unlicense.org>\n*/\n\n\n/** @title BytesLib **/\n/** @author https://github.com/GNSPS **/\n\nlibrary BytesLib {\n function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) {\n if (_length == 0) {\n return hex\"\";\n }\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n // Alloc bytes array with additional 32 bytes afterspace and assign it's size\n res := mload(0x40)\n mstore(0x40, add(add(res, 64), _length))\n mstore(res, _length)\n\n // Compute distance between source and destination pointers\n let diff := sub(res, add(_bytes, _start))\n\n for {\n let src := add(add(_bytes, 32), _start)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n } {\n mstore(add(src, diff), mload(src))\n }\n }\n }\n\n /// @notice Take a slice of the byte array, overwriting the destination.\n /// The length of the slice will equal the length of the destination array.\n /// @dev Make sure the destination array has afterspace if required.\n /// @param _bytes The source array\n /// @param _dest The destination array.\n /// @param _start The location to start in the source array.\n function sliceInPlace(\n bytes memory _bytes,\n bytes memory _dest,\n uint _start\n ) internal pure {\n uint _length = _dest.length;\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n for {\n let src := add(add(_bytes, 32), _start)\n let res := add(_dest, 32)\n let end := add(src, _length)\n } lt(src, end) {\n src := add(src, 32)\n res := add(res, 32)\n } {\n mstore(res, mload(src))\n }\n }\n }\n\n // Static slice functions, no bounds checking\n /// @notice take a 32-byte slice from the specified position\n function slice32(bytes memory _bytes, uint _start) internal pure returns (bytes32 res) {\n assembly {\n res := mload(add(add(_bytes, 32), _start))\n }\n }\n\n /// @notice take a 20-byte slice from the specified position\n function slice20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {\n return bytes20(slice32(_bytes, _start));\n }\n\n /// @notice take a 8-byte slice from the specified position\n function slice8(bytes memory _bytes, uint _start) internal pure returns (bytes8) {\n return bytes8(slice32(_bytes, _start));\n }\n\n /// @notice take a 4-byte slice from the specified position\n function slice4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {\n return bytes4(slice32(_bytes, _start));\n }\n\n /// @notice take a 3-byte slice from the specified position\n function slice3(bytes memory _bytes, uint _start) internal pure returns (bytes3) {\n return bytes3(slice32(_bytes, _start));\n }\n\n /// @notice take a 2-byte slice from the specified position\n function slice2(bytes memory _bytes, uint _start) internal pure returns (bytes2) {\n return bytes2(slice32(_bytes, _start));\n }\n\n function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {\n uint _totalLen = _start + 20;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Address conversion out of bounds.\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {\n uint _totalLen = _start + 32;\n require(_totalLen > _start && _bytes.length >= _totalLen, \"Uint conversion out of bounds.\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function toBytes32(bytes memory _source) pure internal returns (bytes32 result) {\n if (_source.length == 0) {\n return 0x0;\n }\n\n assembly {\n result := mload(add(_source, 32))\n }\n }\n\n function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) {\n uint _end = _start + _length;\n require(_end > _start && _bytes.length >= _end, \"Slice out of bounds\");\n\n assembly {\n result := keccak256(add(add(_bytes, 32), _start), _length)\n }\n }\n}\n"
|
|
@@ -152,7 +152,7 @@
|
|
|
152
152
|
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @notice Aggregates functions common to the redemption transaction proof\n/// validation and to the moving funds transaction proof validation.\nlibrary OutboundTx {\n using BTCUtils for bytes;\n\n /// @notice Checks whether an outbound Bitcoin transaction performed from\n /// the given wallet has an input vector that contains a single\n /// input referring to the wallet's main UTXO. Marks that main UTXO\n /// as correctly spent if the validation succeeds. Reverts otherwise.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the outbound transaction.\n function processWalletOutboundTxInput(\n BridgeState.Storage storage self,\n bytes memory walletOutboundTxInputVector,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) internal {\n // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Assert that the single outbound transaction input actually\n // refers to the wallet's main UTXO.\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex\n ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);\n require(\n mainUtxo.txHash == outpointTxHash &&\n mainUtxo.txOutputIndex == outpointIndex,\n \"Outbound transaction input must point to the wallet's main UTXO\"\n );\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)\n )\n )\n ] = true;\n }\n\n /// @notice Parses the input vector of an outbound Bitcoin transaction\n /// performed from the given wallet. It extracts the single input\n /// then the transaction hash and output index from its outpoint.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the input's outpoint.\n function parseWalletOutboundTxInput(\n bytes memory walletOutboundTxInputVector\n ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation.\n // See `BitcoinTx.inputVector` docs for more details.\n (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();\n require(\n inputsCount == 1,\n \"Outbound transaction must have a single input\"\n );\n\n bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);\n\n outpointTxHash = input.extractInputTxIdLE();\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(input.extractTxIndexLE())\n );\n\n // There is only one input in the transaction. Input has an outpoint\n // field that is a reference to the transaction being spent (see\n // `BitcoinTx` docs). The outpoint contains the hash of the transaction\n // to spend (`outpointTxHash`) and the index of the specific output\n // from that transaction (`outpointIndex`).\n return (outpointTxHash, outpointIndex);\n }\n}\n\n/// @title Bridge redemption\n/// @notice The library handles the logic for redeeming Bitcoin balances from\n/// the Bridge.\n/// @dev To initiate a redemption, a user with a Bank balance supplies\n/// a Bitcoin address. Then, the system calculates the redemption fee, and\n/// releases balance to the provided Bitcoin address. Just like in case of\n/// sweeps of revealed deposits, redemption requests are processed in\n/// batches and require SPV proof to be submitted to the Bridge.\nlibrary Redemption {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n }\n\n /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n }\n\n /// @notice Represents temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n }\n\n event RedemptionRequested(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript,\n address redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// - `redeemerOutputScript` must be a proper Bitcoin script\n /// - `redeemerOutputScript` cannot have wallet PKH as payload\n /// - `amount` must be above or equal the `redemptionDustThreshold`\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time\n /// - Wallet must have enough Bitcoin balance to proceed the request\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // TODO: Confirm if `walletPubKeyHash` should be validated by checking\n // if it is the oldest one who can handle the request. This will\n // be suggested by the dApp but may not be respected by users who\n // interact directly with the contract. Do we need to enforce it\n // here? One option is not to enforce it, to save on gas, but if\n // we see this rule is not respected, upgrade Bridge contract to\n // require it.\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= self.redemptionDustThreshold,\n \"Redemption amount too small\"\n );\n\n // The redemption key is built on top of the wallet public key hash\n // and redeemer output script pair. That means there can be only one\n // request asking for redemption from the given wallet to the given\n // BTC script at the same time.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n\n // Check if given redemption key is not used by a pending redemption.\n // There is no need to check for existence in `timedOutRedemptions`\n // since the wallet's state is changed to other than Live after\n // first time out is reported so making new requests is not possible.\n // slither-disable-next-line incorrect-equality\n require(\n self.pendingRedemptions[redemptionKey].requestedAt == 0,\n \"There is a pending redemption request from this wallet to the same address\"\n );\n\n // No need to check whether `amount - treasuryFee - txMaxFee > 0`\n // since the `redemptionDustThreshold` should force that condition\n // to be always true.\n uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0\n ? amount / self.redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = self.redemptionTxMaxFee;\n\n // The main wallet UTXO's value doesn't include all pending redemptions.\n // To determine if the requested redemption can be performed by the\n // wallet we need to subtract the total value of all pending redemptions\n // from that wallet's main UTXO value. Given that the treasury fee is\n // not redeemed from the wallet, we are subtracting it.\n wallet.pendingRedemptionsValue += amount - treasuryFee;\n require(\n mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,\n \"Insufficient wallet funds\"\n );\n\n self.pendingRedemptions[redemptionKey] = RedemptionRequest(\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(msg.sender, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data\n /// @param redemptionProof Bitcoin redemption proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance.\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 redemptionTxHash = self.validateProof(\n redemptionTx,\n redemptionProof\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\n self,\n redemptionTx.outputVector,\n walletPubKeyHash\n );\n\n if (outputsInfo.changeValue > 0) {\n // If the change value is grater than zero, it means the change\n // output exists and can be used as new wallet's main UTXO.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(\n redemptionTxHash,\n outputsInfo.changeIndex,\n outputsInfo.changeValue\n )\n );\n } else {\n // If the change value is zero, it means the change output doesn't\n // exists and no funds left on the wallet. Delete the main UTXO\n // for that wallet to represent that state in a proper way.\n delete wallet.mainUtxoHash;\n }\n\n wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;\n\n emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);\n\n self.bank.decreaseBalance(outputsInfo.totalBurnableValue);\n self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);\n }\n\n /// @notice Processes the Bitcoin redemption transaction output vector.\n /// It extracts each output and tries to identify it as a pending\n /// redemption request, reported timed out request, or change.\n /// Reverts if one of the outputs cannot be recognized properly.\n /// This function also marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @return info Outcomes of the processing.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash\n ) internal returns (RedemptionTxOutputsInfo memory info) {\n // Determining the total number of redemption transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = redemptionTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH\n // scripts that can be used to lock the change. This is done upfront to\n // save on gas. Both scripts have a strict format defined by Bitcoin.\n //\n // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 walletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", walletPubKeyHash, hex\"88ac\")\n );\n // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 walletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", walletPubKeyHash)\n );\n\n return\n processRedemptionTxOutputs(\n self,\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\n // Helper flag indicating whether there was at least one redemption\n // output present (redemption must be either pending or reported as\n // timed out).\n bool redemptionPresent = false;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n self,\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n redemptionPresent = true;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n redemptionPresent,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing them from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed\n /// @param outputValue Value of the output being processed\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {\n // If we entered here, that means the output was identified\n // as a pending redemption request.\n RedemptionRequest storage request = self.pendingRedemptions[\n redemptionKey\n ];\n // Compute the request's redeemable amount as the requested\n // amount reduced by the treasury fee. The request's\n // minimal amount is then the redeemable amount reduced by\n // the maximum transaction fee.\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n // Output value must fit between the request's redeemable\n // and minimal amounts to be deemed valid.\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the pending request\"\n );\n // Add the redeemable amount to the total burnable value\n // the Bridge will use to decrease its balance in the Bank.\n burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete self.pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = self.timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n Redemption.RedemptionRequest memory request = self.pendingRedemptions[\n redemptionKey\n ];\n\n require(request.requestedAt > 0, \"Redemption request does not exist\");\n require(\n /* solhint-disable-next-line not-rely-on-time */\n request.requestedAt + self.redemptionTimeout < block.timestamp,\n \"Redemption request has not timed out\"\n );\n\n // Update the wallet's pending redemptions value\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n // TODO: Allow the wallets in `Closing` state when the state is added\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"The wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n self.timedOutRedemptions[redemptionKey] = request;\n delete self.pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Propagate timeout consequences to the wallet\n self.notifyWalletTimedOutRedemption(walletPubKeyHash);\n }\n // slither-disable-next-line reentrancy-events\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n self.bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n}\n"
|
|
153
153
|
},
|
|
154
154
|
"contracts/bridge/Fraud.sol": {
|
|
155
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {CheckBitcoinSigs} from \"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge fraud\n/// @notice The library handles the logic for challenging Bridge wallets that\n/// committed fraud.\n/// @dev Anyone can submit a fraud challenge indicating that a UTXO being under\n/// the wallet control was unlocked by the wallet but was not used\n/// according to the protocol rules. That means the wallet signed\n/// a transaction input pointing to that UTXO and there is a unique\n/// sighash and signature pair associated with that input.\n///\n/// In order to defeat the challenge, the same wallet public key and\n/// signature must be provided as were used to calculate the sighash during\n/// the challenge. The wallet provides the preimage which produces sighash\n/// used to generate the ECDSA signature that is the subject of the fraud\n/// claim. The fraud challenge defeat attempt will only succeed if the\n/// inputs in the preimage are considered honestly spent by the wallet.\n/// Therefore the transaction spending the UTXO must be proven in the\n/// Bridge before a challenge defeat is called.\nlibrary Fraud {\n using Wallets for BridgeState.Storage;\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n }\n\n event FraudChallengeSubmitted(\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPubKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPubKeyHash,\n bytes32 sighash\n );\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPublicKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.fraudChallengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Closing,\n \"Wallet must be in Live or MovingFunds or Closing state\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n require(challenge.reportedAt == 0, \"Fraud challenge already exists\");\n\n challenge.challenger = msg.sender;\n challenge.depositAmount = msg.value;\n /* solhint-disable-next-line not-rely-on-time */\n challenge.reportedAt = uint32(block.timestamp);\n challenge.resolved = false;\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge\n function defeatFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n // Ensure SIGHASH_ALL type was used during signing, which is represented\n // by type value `1`.\n require(extractSighashType(preimage) == 1, \"Wrong sighash type\");\n\n uint256 utxoKey = witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 || self.spentMainUTXOs[utxoKey],\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel,arbitrary-send\n self.treasury.call{gas: 100000, value: challenge.depositAmount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after a\n /// fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state\n /// - The `walletPublicKey` and `sighash` must identify an open fraud\n /// challenge\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.fraudChallengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n challenge.resolved = true;\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel\n challenge.challenger.call{gas: 100000, value: challenge.depositAmount}(\n \"\"\n );\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n Wallets.WalletState walletState = self\n .registeredWallets[walletPubKeyHash]\n .state;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Closing\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n // TODO: Perform slashing of the wallet operators, reward the\n // challenger, and add unit tests for that.\n } else if (walletState == Wallets.WalletState.Terminated) {\n // This is a special case when the wallet was already terminated\n // due to a previous deliberate protocol violation. In that\n // case, this function should be still callable for other fraud\n // challenges timeouts in order to let the challenger unlock its\n // ETH deposit back. However, the wallet termination logic is\n // not called and the challenger is not rewarded.\n } else {\n revert(\n \"Wallet must be in Live or MovingFunds or Closing or Terminated state\"\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Extracts the UTXO keys from the given preimage used during\n /// signing of a witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // witness input:\n // - transaction version (4 bytes)\n // - hash of previous outpoints of all inputs (32 bytes)\n // - hash of sequences of all inputs (32 bytes)\n // - outpoint (hash + index) of the input being signed (36 bytes)\n // - the unlocking script of the input (variable length)\n // - value of the outpoint (8 bytes)\n // - sequence of the input being signed (4 bytes)\n // - hash of all outputs (32 bytes)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See Bitcoin's BIP-143 for reference:\n // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.\n\n // The outpoint (hash and index) is located at the constant offset of\n // 68 (4 + 32 + 32).\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(68);\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(68))\n );\n\n return\n uint256(keccak256(abi.encodePacked(outpointTxHash, outpointIndex)));\n }\n\n /// @notice Extracts the UTXO key from the given preimage used during\n /// signing of a non-witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromNonWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // non-witness input:\n // - transaction version (4 bytes)\n // - number of inputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - for each input\n // - outpoint (hash and index) (36 bytes)\n // - unlocking script for the input being signed (variable length)\n // or `00` for all other inputs (1 byte)\n // - input sequence (4 bytes)\n // - number of outputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - outputs (variable length)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See example for reference:\n // https://en.bitcoin.it/wiki/OP_CHECKSIG#Code_samples_and_raw_dumps.\n\n // The input data begins at the constant offset of 4 (the first 4 bytes\n // are for the transaction version).\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = preimage\n .parseVarIntAt(4);\n\n // To determine the first input starting index, we must jump 4 bytes\n // over the transaction version length and the compactSize uint which\n // prepends the input vector. One byte must be added because\n // `BtcUtils.parseVarInt` does not include compactSize uint tag in the\n // returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 4 + 1 + inputsCompactSizeUintLength;\n\n for (uint256 i = 0; i < inputsCount; i++) {\n uint256 inputLength = preimage.determineInputLengthAt(\n inputStartingIndex\n );\n\n (, uint256 scriptSigLength) = preimage.extractScriptSigLenAt(\n inputStartingIndex\n );\n\n if (scriptSigLength > 0) {\n // The input this preimage was generated for was found.\n // All the other inputs in the preimage are marked with a null\n // scriptSig (\"00\") which has length of 1.\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(\n inputStartingIndex\n );\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(inputStartingIndex))\n );\n\n utxoKey = uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n );\n\n break;\n }\n\n inputStartingIndex += inputLength;\n }\n\n return utxoKey;\n }\n\n /// @notice Extracts the sighash type from the given preimage.\n /// @param preimage Serialized subset of the transaction. See BIP-143 for\n /// reference\n /// @dev Sighash type is stored as the last 4 bytes in the preimage (little\n /// endian).\n /// @return sighashType Sighash type as a 32-bit integer.\n function extractSighashType(bytes calldata preimage)\n internal\n pure\n returns (uint32 sighashType)\n {\n bytes4 sighashTypeBytes = preimage.slice4(preimage.length - 4);\n uint32 sighashTypeLE = uint32(sighashTypeBytes);\n return sighashTypeLE.reverseUint32();\n }\n}\n"
|
|
155
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {CheckBitcoinSigs} from \"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge fraud\n/// @notice The library handles the logic for challenging Bridge wallets that\n/// committed fraud.\n/// @dev Anyone can submit a fraud challenge indicating that a UTXO being under\n/// the wallet control was unlocked by the wallet but was not used\n/// according to the protocol rules. That means the wallet signed\n/// a transaction input pointing to that UTXO and there is a unique\n/// sighash and signature pair associated with that input.\n///\n/// In order to defeat the challenge, the same wallet public key and\n/// signature must be provided as were used to calculate the sighash during\n/// the challenge. The wallet provides the preimage which produces sighash\n/// used to generate the ECDSA signature that is the subject of the fraud\n/// claim. The fraud challenge defeat attempt will only succeed if the\n/// inputs in the preimage are considered honestly spent by the wallet.\n/// Therefore the transaction spending the UTXO must be proven in the\n/// Bridge before a challenge defeat is called.\nlibrary Fraud {\n using Wallets for BridgeState.Storage;\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n }\n\n event FraudChallengeSubmitted(\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPubKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPubKeyHash,\n bytes32 sighash\n );\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPublicKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.fraudChallengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Closing,\n \"Wallet must be in Live or MovingFunds or Closing state\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n require(challenge.reportedAt == 0, \"Fraud challenge already exists\");\n\n challenge.challenger = msg.sender;\n challenge.depositAmount = msg.value;\n /* solhint-disable-next-line not-rely-on-time */\n challenge.reportedAt = uint32(block.timestamp);\n challenge.resolved = false;\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge\n function defeatFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n // Ensure SIGHASH_ALL type was used during signing, which is represented\n // by type value `1`.\n require(extractSighashType(preimage) == 1, \"Wrong sighash type\");\n\n uint256 utxoKey = witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 || self.spentMainUTXOs[utxoKey],\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel,arbitrary-send\n self.treasury.call{gas: 100000, value: challenge.depositAmount}(\"\");\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after a\n /// fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state\n /// - The `walletPublicKey` and `sighash` must identify an open fraud\n /// challenge\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes32 sighash\n ) external {\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.fraudChallenges[challengeKey];\n\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.fraudChallengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n challenge.resolved = true;\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls,unchecked-lowlevel\n challenge.challenger.call{gas: 100000, value: challenge.depositAmount}(\n \"\"\n );\n /* solhint-enable avoid-low-level-calls */\n\n bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(\n walletPublicKey.slice32(0),\n walletPublicKey.slice32(32)\n );\n bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Closing\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.fraudSlashingAmount,\n self.fraudNotifierRewardMultiplier,\n challenge.challenger,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n } else if (walletState == Wallets.WalletState.Terminated) {\n // This is a special case when the wallet was already terminated\n // due to a previous deliberate protocol violation. In that\n // case, this function should be still callable for other fraud\n // challenges timeouts in order to let the challenger unlock its\n // ETH deposit back. However, the wallet termination logic is\n // not called and the challenger is not rewarded.\n } else {\n revert(\n \"Wallet must be in Live or MovingFunds or Closing or Terminated state\"\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Extracts the UTXO keys from the given preimage used during\n /// signing of a witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // witness input:\n // - transaction version (4 bytes)\n // - hash of previous outpoints of all inputs (32 bytes)\n // - hash of sequences of all inputs (32 bytes)\n // - outpoint (hash + index) of the input being signed (36 bytes)\n // - the unlocking script of the input (variable length)\n // - value of the outpoint (8 bytes)\n // - sequence of the input being signed (4 bytes)\n // - hash of all outputs (32 bytes)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See Bitcoin's BIP-143 for reference:\n // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki.\n\n // The outpoint (hash and index) is located at the constant offset of\n // 68 (4 + 32 + 32).\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(68);\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(68))\n );\n\n return\n uint256(keccak256(abi.encodePacked(outpointTxHash, outpointIndex)));\n }\n\n /// @notice Extracts the UTXO key from the given preimage used during\n /// signing of a non-witness input.\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @return utxoKey UTXO key that identifies spent input.\n function extractUtxoKeyFromNonWitnessPreimage(bytes calldata preimage)\n internal\n pure\n returns (uint256 utxoKey)\n {\n // The expected structure of the preimage created during signing of a\n // non-witness input:\n // - transaction version (4 bytes)\n // - number of inputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - for each input\n // - outpoint (hash and index) (36 bytes)\n // - unlocking script for the input being signed (variable length)\n // or `00` for all other inputs (1 byte)\n // - input sequence (4 bytes)\n // - number of outputs written as compactSize uint (1 byte, 3 bytes,\n // 5 bytes or 9 bytes)\n // - outputs (variable length)\n // - transaction locktime (4 bytes)\n // - sighash type (4 bytes)\n\n // See example for reference:\n // https://en.bitcoin.it/wiki/OP_CHECKSIG#Code_samples_and_raw_dumps.\n\n // The input data begins at the constant offset of 4 (the first 4 bytes\n // are for the transaction version).\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = preimage\n .parseVarIntAt(4);\n\n // To determine the first input starting index, we must jump 4 bytes\n // over the transaction version length and the compactSize uint which\n // prepends the input vector. One byte must be added because\n // `BtcUtils.parseVarInt` does not include compactSize uint tag in the\n // returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 4 + 1 + inputsCompactSizeUintLength;\n\n for (uint256 i = 0; i < inputsCount; i++) {\n uint256 inputLength = preimage.determineInputLengthAt(\n inputStartingIndex\n );\n\n (, uint256 scriptSigLength) = preimage.extractScriptSigLenAt(\n inputStartingIndex\n );\n\n if (scriptSigLength > 0) {\n // The input this preimage was generated for was found.\n // All the other inputs in the preimage are marked with a null\n // scriptSig (\"00\") which has length of 1.\n bytes32 outpointTxHash = preimage.extractInputTxIdLeAt(\n inputStartingIndex\n );\n uint32 outpointIndex = BTCUtils.reverseUint32(\n uint32(preimage.extractTxIndexLeAt(inputStartingIndex))\n );\n\n utxoKey = uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n );\n\n break;\n }\n\n inputStartingIndex += inputLength;\n }\n\n return utxoKey;\n }\n\n /// @notice Extracts the sighash type from the given preimage.\n /// @param preimage Serialized subset of the transaction. See BIP-143 for\n /// reference\n /// @dev Sighash type is stored as the last 4 bytes in the preimage (little\n /// endian).\n /// @return sighashType Sighash type as a 32-bit integer.\n function extractSighashType(bytes calldata preimage)\n internal\n pure\n returns (uint32 sighashType)\n {\n bytes4 sighashTypeBytes = preimage.slice4(preimage.length - 4);\n uint32 sighashTypeLE = uint32(sighashTypeBytes);\n return sighashTypeLE.reverseUint32();\n }\n}\n"
|
|
156
156
|
},
|
|
157
157
|
"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol": {
|
|
158
158
|
"content": "pragma solidity ^0.8.4;\n\n/** @title CheckBitcoinSigs */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary CheckBitcoinSigs {\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n\n /// @notice Derives an Ethereum Account address from a pubkey\n /// @dev The address is the last 20 bytes of the keccak256 of the address\n /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array\n /// @return The account address\n function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) {\n require(_pubkey.length == 64, \"Pubkey must be 64-byte raw, uncompressed key.\");\n\n // keccak hash of uncompressed unprefixed pubkey\n bytes32 _digest = keccak256(_pubkey);\n return address(uint160(uint256(_digest)));\n }\n\n /// @notice Calculates the p2wpkh output script of a pubkey\n /// @dev Compresses keys to 33 bytes as required by Bitcoin\n /// @param _pubkey The public key, compressed or uncompressed\n /// @return The p2wkph output script\n function p2wpkhFromPubkey(bytes memory _pubkey) internal view returns (bytes memory) {\n bytes memory _compressedPubkey;\n uint8 _prefix;\n\n if (_pubkey.length == 64) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(0));\n } else if (_pubkey.length == 65) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(1));\n } else {\n _compressedPubkey = _pubkey;\n }\n\n require(_compressedPubkey.length == 33, \"Witness PKH requires compressed keys\");\n\n bytes20 _pubkeyHash = _compressedPubkey.hash160View();\n return abi.encodePacked(hex\"0014\", _pubkeyHash);\n }\n\n /// @notice checks a signed message's validity under a pubkey\n /// @dev does this using ecrecover because Ethereum has no soul\n /// @param _pubkey the public key to check (64 bytes)\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkSig(\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal pure returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n address _expected = accountFromPubkey(_pubkey);\n address _actual = ecrecover(_digest, _v, _r, _s);\n return _actual == _expected;\n }\n\n /// @notice checks a signed message against a bitcoin p2wpkh output script\n /// @dev does this my verifying the p2wpkh matches an ethereum account\n /// @param _p2wpkhOutputScript the bitcoin output script\n /// @param _pubkey the uncompressed, unprefixed public key to check\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkBitcoinSig(\n bytes memory _p2wpkhOutputScript,\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal view returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n\n bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer?\n if (!_isExpectedSigner) {return false;}\n\n bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s);\n return _sigResult;\n }\n\n /// @notice checks if a message is the sha256 preimage of a digest\n /// @dev this is NOT the hash256! this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isSha256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return sha256(_candidate) == _digest;\n }\n\n /// @notice checks if a message is the keccak256 preimage of a digest\n /// @dev this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isKeccak256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return keccak256(_candidate) == _digest;\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputScript the length-prefixed output script\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhSpendSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes memory _outputScript // lenght-prefixed output script\n ) internal view returns (bytes32) {\n // Fixes elements to easily make a 1-in 1-out sighash digest\n // Does not support timelocks\n // bytes memory _scriptCode = abi.encodePacked(\n // hex\"1976a914\", // length, dup, hash160, pkh_length\n // _inputPKH,\n // hex\"88ac\"); // equal, checksig\n\n bytes32 _hashOutputs = abi.encodePacked(\n _outputValue, // 8-byte LE\n _outputScript).hash256View();\n\n bytes memory _sighashPreimage = abi.encodePacked(\n hex\"01000000\", // version\n _outpoint.hash256View(), // hashPrevouts\n hex\"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9\", // hashSequence(00000000)\n _outpoint, // outpoint\n // p2wpkh script code\n hex\"1976a914\", // length, dup, hash160, pkh_length\n _inputPKH,\n hex\"88ac\", // equal, checksig\n // end script code\n _inputValue, // value of the input in 8-byte LE\n hex\"00000000\", // input nSequence\n _hashOutputs, // hash of the single output\n hex\"00000000\", // nLockTime\n hex\"01000000\" // SIGHASH_ALL\n );\n return _sighashPreimage.hash256View();\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhToWpkhSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhSpendSighash(\n _outpoint,\n _inputPKH,\n _inputValue,\n _outputValue,\n abi.encodePacked(\n hex\"160014\", // wpkh tag\n _outputPKH)\n );\n }\n\n /// @notice Preserved for API compatibility with older version\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function oneInputOneOutputSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH);\n }\n\n}\n"
|
|
@@ -161,7 +161,7 @@
|
|
|
161
161
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/Wallets.sol\";\n\ncontract BridgeStub is Bridge {\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _walletRegistry,\n uint256 _txProofDifficultyFactor\n )\n Bridge(\n _bank,\n _relay,\n _treasury,\n _walletRegistry,\n _txProofDifficultyFactor\n )\n {}\n\n function setSweptDeposits(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.deposits[utxoKey].sweptAt = 1641650400;\n }\n }\n\n function setSpentMainUtxos(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.spentMainUTXOs[utxoKey] = true;\n }\n }\n\n function setActiveWallet(bytes20 activeWalletPubKeyHash) external {\n self.activeWalletPubKeyHash = activeWalletPubKeyHash;\n }\n\n function setWalletMainUtxo(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n self.registeredWallets[walletPubKeyHash].mainUtxoHash = keccak256(\n abi.encodePacked(\n utxo.txHash,\n utxo.txOutputIndex,\n utxo.txOutputValue\n )\n );\n }\n\n function unsetWalletMainUtxo(bytes20 walletPubKeyHash) external {\n delete self.registeredWallets[walletPubKeyHash].mainUtxoHash;\n }\n\n function setWallet(bytes20 walletPubKeyHash, Wallets.Wallet calldata wallet)\n external\n {\n self.registeredWallets[walletPubKeyHash] = wallet;\n\n if (wallet.state == Wallets.WalletState.Live) {\n self.liveWalletsCount++;\n }\n }\n\n function setDepositDustThreshold(uint64 _depositDustThreshold) external {\n self.depositDustThreshold = _depositDustThreshold;\n }\n\n function setDepositTxMaxFee(uint64 _depositTxMaxFee) external {\n self.depositTxMaxFee = _depositTxMaxFee;\n }\n\n function setRedemptionDustThreshold(uint64 _redemptionDustThreshold)\n external\n {\n self.redemptionDustThreshold = _redemptionDustThreshold;\n }\n\n function setRedemptionTreasuryFeeDivisor(\n uint64 _redemptionTreasuryFeeDivisor\n ) external {\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n }\n\n function setMovingFundsTxMaxTotalFee(uint64 _movingFundsTxMaxTotalFee)\n external\n {\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n }\n}\n"
|
|
162
162
|
},
|
|
163
163
|
"contracts/bridge/Bridge.sol": {
|
|
164
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\n\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./Sweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\n///\n/// TODO: Revisit all events and look which parameters should be indexed.\n/// TODO: Align the convention around `param` and `dev` endings. They should\n/// not have a punctuation mark.\ncontract Bridge is Governable, EcdsaWalletOwner {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using Sweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript,\n address redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 walletPubKeyHash);\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPubKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n );\n\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 10000; // 10000 satoshi\n self.redemptionTimeout = 172800; // 48 hours\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsTimeout = 7 days;\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudChallengeDepositAmount = 2 ether;\n self.walletCreationPeriod = 1 weeks;\n self.walletMinBtcBalance = 1e8; // 1 BTC\n self.walletMaxBtcBalance = 10e8; // 10 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`\n /// @param reveal Deposit reveal data, see `RevealInfo struct\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet\n /// - `reveal.vault` must be 0x0 or point to a trusted vault\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// - `redeemerOutputScript` must be a proper Bitcoin script\n /// - `redeemerOutputScript` cannot have wallet PKH as payload\n /// - `amount` must be above or equal the `redemptionDustThreshold`\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time\n /// - Wallet must have enough Bitcoin balance to proceed the request\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data\n /// @param redemptionProof Bitcoin redemption proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance.\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(walletPubKeyHash, redeemerOutputScript);\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state\n /// - The source wallet must not have pending redemption requests\n /// - The source wallet must not have submitted its commitment already\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain.\n /// - Source wallet BTC balance must be greater than zero\n /// - At least one Live wallet must exist in the system\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`\n /// - Each target wallet must be not equal to the source wallet\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates.\n /// - Each target wallet must be in Live state\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The moving funds timeout must be actually exceeded\n function notifyMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored.\n /// - Wallet creation must not be in progress\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time\n /// - The active wallet BTC balance is above the maximum threshold\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Given wallet data must not belong to an already registered wallet\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate\n /// @param publicKeyY Wallet's public key's Y coordinate\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Wallet must be in Live state\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero.\n /// - Wallet must be in Live state\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the Closing state\n /// - The wallet closing period must have elapsed\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n ///@param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, sighash, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - `walletPublicKey`and `sighash` must identify an open fraud\n /// challenge\n /// - the amount of time indicated by `challengeDefeatTimeout` must\n /// pass after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n self.notifyFraudChallengeDefeatTimeout(walletPublicKey, sighash);\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost.\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault\n /// @param isTrusted flag indicating whether the vault is trusted or not\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero\n /// - Deposit treasury fee divisor must be greater than zero\n /// - Deposit transaction max fee must be greater than zero\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than zero\n /// - Redemption treasury fee divisor must be greater than zero\n /// - Redemption transaction max fee must be greater than zero\n /// - Redemption timeout must be greater than zero\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero\n /// - Moving funds timeout must be greater than zero\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsTimeout\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested\n /// @param walletMinBtcBalance New value of the wallet minimum BTC balance\n /// in satoshi, used to decide about wallet creation or closing\n /// @param walletMaxBtcBalance New value of the wallet maximum BTC balance\n /// in satoshi, used to decide about wallet creation\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance\n /// - Wallet maximum BTC transfer must be greater than zero\n /// - Wallet closing period must be greater than zero\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletMinBtcBalance,\n walletMaxBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100]\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit\n /// @dev Requirements:\n /// - Fraud notifier reward multiplier must be in the range [0, 100]\n /// - Fraud challenge defeat timeout must be greater than 0\n function updateFraudParameters(\n uint256 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier,\n fraudChallengeDefeatTimeout,\n fraudChallengeDepositAmount\n );\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked TBTC is\n /// returned to the redeemer in full amount.\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n function movingFundsParameters()\n external\n view\n returns (uint64 movingFundsTxMaxTotalFee, uint32 movingFundsTimeout)\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsTimeout = self.movingFundsTimeout;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletMinBtcBalance The minimum BTC threshold in satoshi that is\n /// used to decide about wallet creation or closing.\n /// @return walletMaxBtcBalance The maximum BTC threshold in satoshi that is\n /// used to decide about wallet creation.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletMinBtcBalance = self.walletMinBtcBalance;\n walletMaxBtcBalance = self.walletMaxBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n function fraudParameters()\n external\n view\n returns (\n uint256 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n )\n {\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
|
|
164
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\n\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./Sweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\n///\n/// TODO: Revisit all events and look which parameters should be indexed.\n/// TODO: Align the convention around `param` and `dev` endings. They should\n/// not have a punctuation mark.\ncontract Bridge is Governable, EcdsaWalletOwner {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using Sweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript,\n address redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPubKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout,\n uint64 movingFundsDustThreshold\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n );\n\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 10000; // 10000 satoshi\n self.redemptionTimeout = 172800; // 48 hours\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsTimeout = 7 days;\n self.movingFundsDustThreshold = 20000; // 20000 satoshi\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudChallengeDepositAmount = 2 ether;\n self.walletCreationPeriod = 1 weeks;\n self.walletMinBtcBalance = 1e8; // 1 BTC\n self.walletMaxBtcBalance = 10e8; // 10 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`\n /// @param reveal Deposit reveal data, see `RevealInfo struct\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet\n /// - `reveal.vault` must be 0x0 or point to a trusted vault\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// - `redeemerOutputScript` must be a proper Bitcoin script\n /// - `redeemerOutputScript` cannot have wallet PKH as payload\n /// - `amount` must be above or equal the `redemptionDustThreshold`\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time\n /// - Wallet must have enough Bitcoin balance to proceed the request\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data\n /// @param redemptionProof Bitcoin redemption proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance.\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(walletPubKeyHash, redeemerOutputScript);\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state\n /// - The source wallet must not have pending redemption requests\n /// - The source wallet must not have submitted its commitment already\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain.\n /// - Source wallet BTC balance must be greater than zero\n /// - At least one Live wallet must exist in the system\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`\n /// - Each target wallet must be not equal to the source wallet\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates.\n /// - Each target wallet must be in Live state\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The moving funds timeout must be actually exceeded\n function notifyMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored.\n /// - The wallet BTC balance must be below the moving funds threshold\n function notifyMovingFundsBelowDust(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.notifyMovingFundsBelowDust(walletPubKeyHash, mainUtxo);\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored.\n /// - Wallet creation must not be in progress\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time\n /// - The active wallet BTC balance is above the maximum threshold\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Given wallet data must not belong to an already registered wallet\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate\n /// @param publicKeyY Wallet's public key's Y coordinate\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Wallet must be in Live state\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero.\n /// - Wallet must be in Live state\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the Closing state\n /// - The wallet closing period must have elapsed\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n ///@param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, sighash, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state\n /// - The `walletPublicKey` and `sighash` must identify an open fraud\n /// challenge\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes32 sighash\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n sighash\n );\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost.\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault\n /// @param isTrusted flag indicating whether the vault is trusted or not\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero\n /// - Deposit treasury fee divisor must be greater than zero\n /// - Deposit transaction max fee must be greater than zero\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than zero\n /// - Redemption treasury fee divisor must be greater than zero\n /// - Redemption transaction max fee must be greater than zero\n /// - Redemption timeout must be greater than zero\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n // be transferred during the moving funds process. Moving funds\n // wallets having their BTC balance below that value can begin\n // closing immediately as transferring such a low value may not be\n // possible due to BTC network fees.\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero\n /// - Moving funds timeout must be greater than zero\n /// - Moving funds dust threshold must be greater than zero\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout,\n uint64 movingFundsDustThreshold\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsTimeout,\n movingFundsDustThreshold\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested\n /// @param walletMinBtcBalance New value of the wallet minimum BTC balance\n /// in satoshi, used to decide about wallet creation or closing\n /// @param walletMaxBtcBalance New value of the wallet maximum BTC balance\n /// in satoshi, used to decide about wallet creation\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges\n /// @dev Requirements:\n /// - Wallet minimum BTC balance must be greater than zero\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance\n /// - Wallet maximum BTC transfer must be greater than zero\n /// - Wallet closing period must be greater than zero\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletMinBtcBalance,\n walletMaxBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100]\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit\n /// @dev Requirements:\n /// - Fraud notifier reward multiplier must be in the range [0, 100]\n /// - Fraud challenge defeat timeout must be greater than 0\n function updateFraudParameters(\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier,\n fraudChallengeDefeatTimeout,\n fraudChallengeDepositAmount\n );\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked TBTC is\n /// returned to the redeemer in full amount.\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n /// @return movingFundsDustThreshold The minimal satoshi amount that makes\n // sense to be transferred during the moving funds process. Moving\n // funds wallets having their BTC balance below that value can\n // begin closing immediately as transferring such a low value may\n // not be possible due to BTC network fees.\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint32 movingFundsTimeout,\n uint64 movingFundsDustThreshold\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletMinBtcBalance The minimum BTC threshold in satoshi that is\n /// used to decide about wallet creation or closing.\n /// @return walletMaxBtcBalance The maximum BTC threshold in satoshi that is\n /// used to decide about wallet creation.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletMinBtcBalance,\n uint64 walletMaxBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletMinBtcBalance = self.walletMinBtcBalance;\n walletMaxBtcBalance = self.walletMaxBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n function fraudParameters()\n external\n view\n returns (\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier,\n uint256 fraudChallengeDefeatTimeout,\n uint256 fraudChallengeDepositAmount\n )\n {\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
|
|
165
165
|
},
|
|
166
166
|
"@keep-network/random-beacon/contracts/Governable.sol": {
|
|
167
167
|
"content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\n/// @notice Governable contract.\n/// @dev A constructor is not defined, which makes the contract compatible with\n/// upgradable proxies. This requires calling explicitly `_transferGovernance`\n/// function in a child contract.\nabstract contract Governable {\n // Governance of the contract\n // The variable should be initialized by the implementing contract.\n // slither-disable-next-line uninitialized-state\n address public governance;\n\n event GovernanceTransferred(address oldGovernance, address newGovernance);\n\n modifier onlyGovernance() virtual {\n require(governance == msg.sender, \"Caller is not the governance\");\n _;\n }\n\n /// @notice Transfers governance of the contract to `newGovernance`.\n function transferGovernance(address newGovernance)\n external\n virtual\n onlyGovernance\n {\n require(\n newGovernance != address(0),\n \"New governance is the zero address\"\n );\n _transferGovernance(newGovernance);\n }\n\n function _transferGovernance(address newGovernance) internal virtual {\n address oldGovernance = governance;\n governance = newGovernance;\n emit GovernanceTransferred(oldGovernance, newGovernance);\n }\n}\n"
|
|
@@ -173,7 +173,7 @@
|
|
|
173
173
|
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bridge deposit sweep\n/// @notice The library handles the logic for sweeping transactions revealed to\n/// the Bridge\n/// @dev Bridge active wallet periodically signs a transaction that unlocks all\n/// of the valid, revealed deposits above the dust threshold, combines them\n/// into a single UTXO with the existing main wallet UTXO, and relocks\n/// those transactions without a 30-day refund clause to the same wallet.\n/// This has two main effects: it consolidates the UTXO set and it disables\n/// the refund. Balances of depositors in the Bank are increased when the\n/// SPV sweep proof is submitted to the Bridge.\nlibrary Sweep {\n using BridgeState for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct SweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n }\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processSweepTxOutput(sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = sweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n // Update depositors balances in the Bank.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\n\n // TODO: Handle deposits having `vault` set.\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state.\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processSweepTxOutput(bytes memory sweepTxOutputVector)\n internal\n pure\n returns (bytes20 walletPubKeyHash, uint64 value)\n {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n value = output.extractValue();\n bytes memory walletPubKeyHashBytes = output.extractHash();\n // The sweep transaction output should always be P2PKH or P2WPKH.\n // In both cases, the wallet public key hash should be 20 bytes length.\n require(\n walletPubKeyHashBytes.length == 20,\n \"Wallet public key hash should have 20 bytes\"\n );\n /* solhint-disable-next-line no-inline-assembly */\n assembly {\n walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))\n }\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @param sweepTxInputVector Bitcoin sweep transaction input vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before\n /// it is passed here\n /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO\n /// exists for the given the wallet, this parameter's fields should\n /// be zeroed to bypass the main UTXO validation\n /// @return info Outcomes of the processing.\n function processSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo\n ) internal returns (SweepTxInputsInfo memory info) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (\n uint256 inputsCompactSizeUintLength,\n uint256 inputsCount\n ) = sweepTxInputVector.parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n info.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n info.depositedAmounts = new uint256[](info.depositors.length);\n info.treasuryFees = new uint256[](info.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);\n\n Deposit.DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n if (processedDepositsCount == info.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n info.depositors[processedDepositsCount] = deposit.depositor;\n info.depositedAmounts[processedDepositsCount] = deposit.amount;\n info.inputsTotalValue += info.depositedAmounts[\n processedDepositsCount\n ];\n info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n mainUtxo.txHash == outpointTxHash\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n info.inputsTotalValue += mainUtxo.txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return info;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector\n /// @param inputStartingIndex Index the given input starts at\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function sweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
|
|
174
174
|
},
|
|
175
175
|
"contracts/bridge/MovingFunds.sol": {
|
|
176
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Redemption.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Moving Bridge wallet funds\n/// @notice The library handles the logic for moving Bitcoin between Bridge\n/// wallets.\n/// @dev A wallet that failed a heartbeat, did not process requested redemption\n/// on time, or qualifies to be closed, begins the procedure of moving\n/// funds to other wallets in the Bridge. The wallet needs to commit to\n/// which other Live wallets it is moving the funds to and then, provide an\n/// SPV proof of moving funds to the previously committed wallets.\nlibrary MovingFunds {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n event MovingFundsCommitmentSubmitted(\n bytes20 walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 walletPubKeyHash);\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state\n /// - The source wallet must not have pending redemption requests\n /// - The source wallet must not have submitted its commitment already\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain.\n /// - Source wallet BTC balance must be greater than zero\n /// - At least one Live wallet must exist in the system\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`\n /// - Each target wallet must be not equal to the source wallet\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates.\n /// - Each target wallet must be in Live state\n function submitMovingFundsCommitment(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Source wallet must be in MovingFunds state\"\n );\n\n require(\n wallet.pendingRedemptionsValue == 0,\n \"Source wallet must handle all pending redemptions first\"\n );\n\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(\n self.ecdsaWalletRegistry.isWalletMember(\n wallet.ecdsaWalletID,\n walletMembersIDs,\n msg.sender,\n walletMemberIndex\n ),\n \"Caller is not a member of the source wallet\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n walletMainUtxo\n );\n\n require(walletBtcBalance > 0, \"Wallet BTC balance is zero\");\n\n uint256 expectedTargetWalletsCount = Math.min(\n self.liveWalletsCount,\n Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)\n );\n\n // This requirement fails only when `liveWalletsCount` is zero. In\n // that case, the system cannot accept the commitment and must provide\n // new wallets first.\n //\n // TODO: Expose separate function to reset the moving funds timeout\n // if no Live wallets exist in the system.\n require(expectedTargetWalletsCount > 0, \"No target wallets available\");\n\n require(\n targetWallets.length == expectedTargetWalletsCount,\n \"Submitted target wallets count is other than expected\"\n );\n\n uint160 lastProcessedTargetWallet = 0;\n\n for (uint256 i = 0; i < targetWallets.length; i++) {\n bytes20 targetWallet = targetWallets[i];\n\n require(\n targetWallet != walletPubKeyHash,\n \"Submitted target wallet cannot be equal to the source wallet\"\n );\n\n require(\n uint160(targetWallet) > lastProcessedTargetWallet,\n \"Submitted target wallet breaks the expected order\"\n );\n\n require(\n self.registeredWallets[targetWallet].state ==\n Wallets.WalletState.Live,\n \"Submitted target wallet must be in Live state\"\n );\n\n lastProcessedTargetWallet = uint160(targetWallet);\n }\n\n wallet.movingFundsTargetWalletsCommitmentHash = keccak256(\n abi.encodePacked(targetWallets)\n );\n\n emit MovingFundsCommitmentSubmitted(\n walletPubKeyHash,\n targetWallets,\n msg.sender\n );\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 movingFundsTxHash = self.validateProof(\n movingFundsTx,\n movingFundsProof\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n self.movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);\n // slither-disable-next-line reentrancy-events\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc.\n /// - Each output must refer to a 20-byte public key hash.\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)\n internal\n pure\n returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)\n {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n uint256 outputLength = movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n // Extract the output script payload.\n bytes memory targetWalletPubKeyHashBytes = output.extractHash();\n // Output script payload must refer to a known wallet public key\n // hash which is always 20-byte.\n require(\n targetWalletPubKeyHashBytes.length == 20,\n \"Target wallet public key hash must have 20 bytes\"\n );\n\n bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes\n .slice20(0);\n\n // The next step is making sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 targetWalletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(\n hex\"1976a914\",\n targetWalletPubKeyHash,\n hex\"88ac\"\n )\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 targetWalletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", targetWalletPubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == targetWalletP2PKHScriptKeccak ||\n outputScriptKeccak == targetWalletP2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[i] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[i] = output.extractValue();\n outputsTotalValue += outputsValues[i];\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The moving funds timeout must be actually exceeded\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt + self.movingFundsTimeout,\n \"Moving funds has not timed out yet\"\n );\n\n self.terminateWallet(walletPubKeyHash);\n\n // TODO: Perform slashing of wallet operators, reward the notifier\n // using seized amount, and add unit tests for that.\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsTimedOut(walletPubKeyHash);\n }\n}\n"
|
|
176
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Redemption.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Moving Bridge wallet funds\n/// @notice The library handles the logic for moving Bitcoin between Bridge\n/// wallets.\n/// @dev A wallet that failed a heartbeat, did not process requested redemption\n/// on time, or qualifies to be closed, begins the procedure of moving\n/// funds to other wallets in the Bridge. The wallet needs to commit to\n/// which other Live wallets it is moving the funds to and then, provide an\n/// SPV proof of moving funds to the previously committed wallets.\nlibrary MovingFunds {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n event MovingFundsCommitmentSubmitted(\n bytes20 walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state\n /// - The source wallet must not have pending redemption requests\n /// - The source wallet must not have submitted its commitment already\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain.\n /// - Source wallet BTC balance must be greater than zero\n /// - At least one Live wallet must exist in the system\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`\n /// - Each target wallet must be not equal to the source wallet\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates.\n /// - Each target wallet must be in Live state\n function submitMovingFundsCommitment(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Source wallet must be in MovingFunds state\"\n );\n\n require(\n wallet.pendingRedemptionsValue == 0,\n \"Source wallet must handle all pending redemptions first\"\n );\n\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(\n self.ecdsaWalletRegistry.isWalletMember(\n wallet.ecdsaWalletID,\n walletMembersIDs,\n msg.sender,\n walletMemberIndex\n ),\n \"Caller is not a member of the source wallet\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n walletMainUtxo\n );\n\n require(walletBtcBalance > 0, \"Wallet BTC balance is zero\");\n\n uint256 expectedTargetWalletsCount = Math.min(\n self.liveWalletsCount,\n Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)\n );\n\n // This requirement fails only when `liveWalletsCount` is zero. In\n // that case, the system cannot accept the commitment and must provide\n // new wallets first.\n //\n // TODO: Expose separate function to reset the moving funds timeout\n // if no Live wallets exist in the system.\n require(expectedTargetWalletsCount > 0, \"No target wallets available\");\n\n require(\n targetWallets.length == expectedTargetWalletsCount,\n \"Submitted target wallets count is other than expected\"\n );\n\n uint160 lastProcessedTargetWallet = 0;\n\n for (uint256 i = 0; i < targetWallets.length; i++) {\n bytes20 targetWallet = targetWallets[i];\n\n require(\n targetWallet != walletPubKeyHash,\n \"Submitted target wallet cannot be equal to the source wallet\"\n );\n\n require(\n uint160(targetWallet) > lastProcessedTargetWallet,\n \"Submitted target wallet breaks the expected order\"\n );\n\n require(\n self.registeredWallets[targetWallet].state ==\n Wallets.WalletState.Live,\n \"Submitted target wallet must be in Live state\"\n );\n\n lastProcessedTargetWallet = uint160(targetWallet);\n }\n\n wallet.movingFundsTargetWalletsCommitmentHash = keccak256(\n abi.encodePacked(targetWallets)\n );\n\n emit MovingFundsCommitmentSubmitted(\n walletPubKeyHash,\n targetWallets,\n msg.sender\n );\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 movingFundsTxHash = self.validateProof(\n movingFundsTx,\n movingFundsProof\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n self.movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);\n // slither-disable-next-line reentrancy-events\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc.\n /// - Each output must refer to a 20-byte public key hash.\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)\n internal\n pure\n returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)\n {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n uint256 outputLength = movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n // Extract the output script payload.\n bytes memory targetWalletPubKeyHashBytes = output.extractHash();\n // Output script payload must refer to a known wallet public key\n // hash which is always 20-byte.\n require(\n targetWalletPubKeyHashBytes.length == 20,\n \"Target wallet public key hash must have 20 bytes\"\n );\n\n bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes\n .slice20(0);\n\n // The next step is making sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 targetWalletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(\n hex\"1976a914\",\n targetWalletPubKeyHash,\n hex\"88ac\"\n )\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 targetWalletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", targetWalletPubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == targetWalletP2PKHScriptKeccak ||\n outputScriptKeccak == targetWalletP2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[i] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[i] = output.extractValue();\n outputsTotalValue += outputsValues[i];\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The moving funds timeout must be actually exceeded\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt + self.movingFundsTimeout,\n \"Moving funds has not timed out yet\"\n );\n\n self.terminateWallet(walletPubKeyHash);\n\n // TODO: Perform slashing of wallet operators, reward the notifier\n // using seized amount, and add unit tests for that.\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsTimedOut(walletPubKeyHash);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored.\n /// - The wallet BTC balance must be below the moving funds threshold\n function notifyMovingFundsBelowDust(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.MovingFunds,\n \"ECDSA wallet must be in MovingFunds state\"\n );\n\n uint64 walletBtcBalance = self.getWalletBtcBalance(\n walletPubKeyHash,\n mainUtxo\n );\n\n require(\n walletBtcBalance < self.movingFundsDustThreshold,\n \"Wallet BTC balance must be below the moving funds dust threshold\"\n );\n\n self.beginWalletClosing(walletPubKeyHash);\n\n // slither-disable-next-line reentrancy-events\n emit MovingFundsBelowDustReported(walletPubKeyHash);\n }\n}\n"
|
|
177
177
|
},
|
|
178
178
|
"contracts/test/TestRelay.sol": {
|
|
179
179
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/Bridge.sol\";\n\ncontract TestRelay is IRelay {\n uint256 private currentEpochDifficulty;\n uint256 private prevEpochDifficulty;\n\n function setCurrentEpochDifficulty(uint256 _difficulty) external {\n currentEpochDifficulty = _difficulty;\n }\n\n function setPrevEpochDifficulty(uint256 _difficulty) external {\n prevEpochDifficulty = _difficulty;\n }\n\n function getCurrentEpochDifficulty()\n external\n view\n override\n returns (uint256)\n {\n return currentEpochDifficulty;\n }\n\n function getPrevEpochDifficulty() external view override returns (uint256) {\n return prevEpochDifficulty;\n }\n}\n"
|