@keep-network/tbtc-v2 0.1.1-dev.74 → 0.1.1-dev.75

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.
Files changed (69) hide show
  1. package/artifacts/Bank.json +3 -3
  2. package/artifacts/Bridge.json +14 -1
  3. package/artifacts/DefaultProxyAdmin.json +2 -2
  4. package/artifacts/Deposit.json +7 -7
  5. package/artifacts/DepositSweep.json +7 -7
  6. package/artifacts/EcdsaDkgValidator.json +2 -2
  7. package/artifacts/EcdsaInactivity.json +1 -1
  8. package/artifacts/Fraud.json +7 -7
  9. package/artifacts/KeepRegistry.json +1 -1
  10. package/artifacts/KeepStake.json +2 -2
  11. package/artifacts/KeepToken.json +2 -2
  12. package/artifacts/KeepTokenStaking.json +1 -1
  13. package/artifacts/MovingFunds.json +10 -10
  14. package/artifacts/NuCypherStakingEscrow.json +1 -1
  15. package/artifacts/NuCypherToken.json +2 -2
  16. package/artifacts/RandomBeaconStub.json +1 -1
  17. package/artifacts/Redemption.json +9 -9
  18. package/artifacts/ReimbursementPool.json +2 -2
  19. package/artifacts/Relay.json +9 -9
  20. package/artifacts/SortitionPool.json +3 -3
  21. package/artifacts/T.json +2 -2
  22. package/artifacts/TBTC.json +3 -3
  23. package/artifacts/TBTCToken.json +3 -3
  24. package/artifacts/TokenStaking.json +1 -1
  25. package/artifacts/TokenholderGovernor.json +9 -9
  26. package/artifacts/TokenholderTimelock.json +8 -8
  27. package/artifacts/VendingMachine.json +10 -10
  28. package/artifacts/VendingMachineKeep.json +1 -1
  29. package/artifacts/VendingMachineNuCypher.json +1 -1
  30. package/artifacts/WalletRegistry.json +6 -6
  31. package/artifacts/WalletRegistry_Implementation.json +1 -1
  32. package/artifacts/WalletRegistry_Proxy.json +6 -6
  33. package/artifacts/Wallets.json +7 -7
  34. package/artifacts/solcInputs/{3d39c8183330efd748c005f3c281bf2c.json → 49c80d59bf0ae61f27a8bb5db19af68a.json} +3 -3
  35. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  36. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  37. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  38. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  39. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  40. package/build/contracts/bridge/Bridge.sol/Bridge.json +58 -42
  41. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  42. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +8 -2
  43. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  44. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  45. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +1 -1
  46. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +2 -2
  47. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  48. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
  49. package/build/contracts/bridge/Fraud.sol/Fraud.json +2 -2
  50. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +1 -1
  51. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
  52. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
  53. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +2 -2
  54. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
  55. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +2 -2
  56. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
  57. package/build/contracts/bridge/Redemption.sol/Redemption.json +2 -2
  58. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  59. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  60. package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
  61. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  62. package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +1 -1
  63. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  64. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  65. package/contracts/bridge/Bridge.sol +30 -6
  66. package/contracts/bridge/BridgeState.sol +33 -7
  67. package/contracts/bridge/MovingFunds.sol +10 -1
  68. package/export.json +13 -0
  69. package/package.json +1 -1
@@ -170,7 +170,7 @@
170
170
  "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"
171
171
  },
172
172
  "contracts/bridge/BridgeState.sol": {
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 {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\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\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 // 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. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\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 amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint256 movingFundsTimeoutNotifierRewardMultiplier;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\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 // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\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 // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint256 redemptionTimeoutNotifierRewardMultiplier;\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 ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\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 // 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. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\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 // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\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 uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\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 /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\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 /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint256 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\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 require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\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 _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 /// @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 _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout must be greater than zero,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint256 _movingFundsTimeoutNotifierRewardMultiplier,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint256 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeout > 0,\n \"Moving funds timeout must be greater than zero\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\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 _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\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 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletClosureMinBtcBalance > 0,\n \"Wallet closure minimum BTC balance must be greater than zero\"\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.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\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 /// @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 _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 /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint256 _fraudChallengeDepositAmount,\n uint256 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n}\n"
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 {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\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\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 // 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. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\n // Time after which the moving funds timeout can be reset in case the\n // target wallet commitment cannot be submitted due to a lack of live\n // wallets in the system. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state or from the moment the timeout was reset the last time.\n // Value in seconds. This value should be lower than the value\n // of the `movingFundsTimeout`.\n uint32 movingFundsTimeoutResetDelay;\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 amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint256 movingFundsTimeoutNotifierRewardMultiplier;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // if per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\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 // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\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 // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint256 redemptionTimeoutNotifierRewardMultiplier;\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 ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint256 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint256 fraudChallengeDefeatTimeout;\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 // 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. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\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 // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\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 uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\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 /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\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 /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint256 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint256 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\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 require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\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 _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 /// @param _movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\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 _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeoutResetDelay,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint256 _movingFundsTimeoutNotifierRewardMultiplier,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint256 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeoutResetDelay > 0,\n \"Moving funds timeout reset delay must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > _movingFundsTimeoutResetDelay,\n \"Moving funds timeout must be greater than its reset delay\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeoutResetDelay = _movingFundsTimeoutResetDelay;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeoutResetDelay,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\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 _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\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 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletClosureMinBtcBalance > 0,\n \"Wallet closure minimum BTC balance must be greater than zero\"\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.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\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 /// @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 _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 /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint256 _fraudChallengeDepositAmount,\n uint256 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint256 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n}\n"
174
174
  },
175
175
  "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol": {
176
176
  "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"
@@ -197,7 +197,7 @@
197
197
  "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 \"./Heartbeat.sol\";\nimport \"./MovingFunds.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.\n///\n/// The fraud challenge defeat attempt will succeed if the inputs in the\n/// preimage are considered honestly spent by the wallet. Therefore the\n/// transaction spending the UTXO must be proven in the Bridge before\n/// a challenge defeat is called.\n///\n/// Another option is when a malicious wallet member used a signed heartbeat\n/// message periodically produced by the wallet off-chain to challenge the\n/// wallet for a fraud. Anyone from the wallet can defeat the challenge by\n/// proving the sighash and signature were produced for a heartbeat message\n/// following a strict format.\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 // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n // Sighash calculated as a Bitcoin's hash256 (double sha2) of:\n // - a preimage of a transaction spending UTXO according to the protocol\n // rules OR\n // - a valid heartbeat message produced by the wallet off-chain.\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\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 /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\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 // To prevent ECDSA signature forgery `sighash` must be calculated\n // inside the function and not passed as a function parameter.\n // Signature forgery could result in a wrongful fraud accusation\n // against a wallet.\n bytes32 sighash = sha256(preimageSha256);\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 ||\n self.spentMainUTXOs[utxoKey] ||\n self.movedFundsSweepRequests[utxoKey].state ==\n MovingFunds.MovedFundsSweepRequestState.Processed,\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\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 heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes),\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n bytes32 sighash = heartbeatMessage.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 require(\n Heartbeat.isValidHeartbeatMessage(heartbeatMessage),\n \"Not a valid heartbeat message\"\n );\n\n resolveFraudChallenge(self, walletPublicKey, challenge, sighash);\n }\n\n /// @notice Called only for successfully defeated fraud challenges.\n /// The fraud challenge is marked as resolved and the amount of\n /// ether deposited by the challenger is sent to the treasury.\n /// @dev Requirements:\n /// - Must be called only for successfully defeated fraud challenges.\n function resolveFraudChallenge(\n BridgeState.Storage storage self,\n bytes calldata walletPublicKey,\n FraudChallenge storage challenge,\n bytes32 sighash\n ) internal {\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\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\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud 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 of the `WalletRegistry` contract,\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 bytes memory preimageSha256\n ) external {\n bytes32 sighash = sha256(preimageSha256);\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\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"
198
198
  },
199
199
  "contracts/bridge/MovingFunds.sol": {
200
- "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.\n/// Once the proof is submitted, all target wallets are supposed to\n/// sweep the received UTXOs with their own main UTXOs in order to\n/// update their BTC balances.\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 /// @notice Represents temporary information needed during the processing\n /// of the moving funds Bitcoin transaction outputs. This structure\n /// is an internal one and should not be exported outside of the\n /// moving funds transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct MovingFundsTxOutputsProcessingInfo {\n // 32-byte hash of the moving funds Bitcoin transaction.\n bytes32 movingFundsTxHash;\n // Output vector of the moving funds Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVout` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes movingFundsTxOutputVector;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents moved funds sweep request state.\n enum MovedFundsSweepRequestState {\n /// @dev The request is unknown to the Bridge.\n Unknown,\n /// @dev Request is pending and can become either processed or timed out.\n Pending,\n /// @dev Request was processed by the target wallet.\n Processed,\n /// @dev Request was not processed in the given time window and\n /// the timeout was reported.\n TimedOut\n }\n\n /// @notice Represents a moved funds sweep request. The request is\n /// registered in `submitMovingFundsProof` where we know funds\n /// have been moved to the target wallet and the only step left is\n /// to have the target wallet sweep them.\n struct MovedFundsSweepRequest {\n // 20-byte public key hash of the wallet supposed to sweep the UTXO\n // representing the received funds with their own main UTXO\n bytes20 walletPubKeyHash;\n // Value of the received funds.\n uint64 value;\n // UNIX timestamp the request was created at.\n uint32 createdAt;\n // The current state of the request.\n MovedFundsSweepRequestState state;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\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 pending moved funds sweep 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.pendingMovedFundsSweepRequestsCount == 0,\n \"Source wallet must handle all pending moved funds sweep requests 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. However, the wallet supposed to submit the\n // commitment can keep resetting the moving funds timeout until then.\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 Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero.\n function resetMovingFundsTimeout(\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 // If the moving funds wallet already submitted their target wallets\n // commitment, there is no point to reset the timeout since the\n // wallet can make the BTC transaction and submit the proof.\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(self.liveWalletsCount == 0, \"Live wallets count must be zero\");\n\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit MovingFundsTimeoutReset(walletPubKeyHash);\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(\n self,\n MovingFundsTxOutputsProcessingInfo(\n movingFundsTxHash,\n movingFundsTx.outputVector\n )\n );\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 processInfo Processing info containing the moving funds tx\n /// hash and output vector.\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(\n BridgeState.Storage storage self,\n MovingFundsTxOutputsProcessingInfo memory processInfo\n ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {\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 ) = processInfo.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. Note that the `outputIndex` must be\n // `uint32` to build proper `movedFundsSweepRequests` keys.\n for (\n uint32 outputIndex = 0;\n outputIndex < outputsCount;\n outputIndex++\n ) {\n uint256 outputLength = processInfo\n .movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = processInfo.movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);\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[outputIndex] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[outputIndex] = output.extractValue();\n outputsTotalValue += outputsValues[outputIndex];\n\n // Register a moved funds sweep request that must be handled\n // by the target wallet. The target wallet must sweep the\n // received funds with their own main UTXO in order to update\n // their BTC balance. Worth noting there is no need to check\n // if the sweep request already exists in the system because\n // the moving funds wallet is moved to the Closing state after\n // submitting the moving funds proof so there is no possibility\n // to submit the proof again and register the sweep request twice.\n self.movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n processInfo.movingFundsTxHash,\n outputIndex\n )\n )\n )\n ] = MovedFundsSweepRequest(\n targetWalletPubKeyHash,\n outputsValues[outputIndex],\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovedFundsSweepRequestState.Pending\n );\n // We added a new moved funds sweep request for the target wallet\n // so we must increment their request counter.\n self\n .registeredWallets[targetWalletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\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 /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\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 of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\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 self.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\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 /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\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\n /// the first input pointing to a wallet's sweep Pending request and,\n /// optionally, the second input pointing to the wallet's main UTXO,\n /// if the sweeping wallet has a main UTXO set. There should be only\n /// one output locking funds on the sweeping wallet 20-byte public\n /// key hash,\n /// - `sweepProof` 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 sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\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 (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo,\n walletPubKeyHash\n );\n\n require(\n sweepTxInputsTotalValue - sweepTxOutputValue <=\n self.movedFundsSweepTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n // Use the sweep transaction output as the new sweeping wallet's main UTXO.\n // Transaction output index is always 0 as sweep transaction always\n // contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction output vector\n /// by 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 moved funds sweep transaction output\n /// 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 moved funds sweep transaction output value.\n /// @dev Requirements:\n /// - Output vector must contain only one output,\n /// - The single output must be of P2PKH or P2WPKH type and lock the\n /// funds on a 20-byte public key hash.\n function processMovedFundsSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\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 performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Moved funds sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\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 /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\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 resolveMovedFundsSweepingWallet(\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 moved funds sweep transaction input vector.\n /// It extracts the first input and tries to match it with one of\n /// the moved funds sweep requests targeting the sweeping wallet.\n /// If the sweep request is an existing Pending request, this\n /// function marks it as Processed. If the sweeping wallet has a\n /// main UTXO, this function extracts the second input, makes sure\n /// it refers to the wallet main UTXO, and marks that main UTXO as\n /// correctly spent.\n /// @param sweepTxInputVector Bitcoin moved funds 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 sweeping 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 /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet.\n /// @return inputsTotalValue Total inputs value sum.\n /// @dev Requirements:\n /// - The input vector must consist of one mandatory and one optional\n /// input,\n /// - The mandatory input must be the first input in the vector,\n /// - The mandatory input must point to a Pending moved funds sweep\n /// request that is targeted to the sweeping wallet,\n /// - The optional output must be the second input in the vector,\n /// - The optional input is required if the sweeping wallet has a\n /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,\n /// that input must point the the sweeping wallet main UTXO.\n function processMovedFundsSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo,\n bytes20 walletPubKeyHash\n ) internal returns (uint256 inputsTotalValue) {\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 performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.inputVector` docs for 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 // We always expect the first input to be the swept UTXO. Additionally,\n // if the sweeping wallet has a main UTXO, that main UTXO should be\n // pointed by the second input.\n require(\n inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),\n \"Moved funds sweep transaction must have a proper inputs count\"\n );\n\n // Parse the first input and extract its outpoint tx hash and index.\n (\n bytes32 firstInputOutpointTxHash,\n uint32 firstInputOutpointIndex,\n uint256 firstInputLength\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex\n );\n\n // Build the request key and fetch the corresponding moved funds sweep\n // request from contract storage.\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n firstInputOutpointTxHash,\n firstInputOutpointIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n // We must check if the wallet extracted from the moved funds sweep\n // transaction output is truly the owner of the sweep request connected\n // with the swept UTXO. This is needed to prevent a case when a wallet\n // handles its own sweep request but locks the funds on another\n // wallet public key hash.\n require(\n sweepRequest.walletPubKeyHash == walletPubKeyHash,\n \"Sweep request belongs to another wallet\"\n );\n // If the validation passed, the sweep request must be marked as\n // processed and its value should be counted into the total inputs\n // value sum.\n sweepRequest.state = MovedFundsSweepRequestState.Processed;\n inputsTotalValue += sweepRequest.value;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n\n // If the main UTXO for the sweeping wallet exists, it must be processed.\n if (mainUtxo.txHash != bytes32(0)) {\n // The second input is supposed to point to that sweeping wallet\n // main UTXO. We need to parse that input.\n (\n bytes32 secondInputOutpointTxHash,\n uint32 secondInputOutpointIndex,\n\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex + firstInputLength\n );\n // Make sure the second input refers to the sweeping wallet main UTXO.\n require(\n mainUtxo.txHash == secondInputOutpointTxHash &&\n mainUtxo.txOutputIndex == secondInputOutpointIndex,\n \"Second input must point to the wallet's main UTXO\"\n );\n\n // If the validation passed, count the main UTXO value into the\n // total inputs value sum.\n inputsTotalValue += mainUtxo.txOutputValue;\n\n // Main UTXO used as an input, mark it as spent. This is needed\n // to defend against fraud challenges referring to this main UTXO.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(\n secondInputOutpointTxHash,\n secondInputOutpointIndex\n )\n )\n )\n ] = true;\n }\n\n return inputsTotalValue;\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 parseMovedFundsSweepTxInputAt(\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 Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,,\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 of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n BridgeState.Storage storage self,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n movingFundsTxHash,\n movingFundsTxOutputIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n sweepRequest.createdAt + self.movedFundsSweepTimeout,\n \"Sweep request has not timed out yet\"\n );\n\n bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n Wallets.WalletState walletState = wallet.state;\n\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Terminated,\n \"ECDSA wallet must be in Live or MovingFunds or Terminated state\"\n );\n\n sweepRequest.state = MovedFundsSweepRequestState.TimedOut;\n wallet.pendingMovedFundsSweepRequestsCount--;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
200
+ "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.\n/// Once the proof is submitted, all target wallets are supposed to\n/// sweep the received UTXOs with their own main UTXOs in order to\n/// update their BTC balances.\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 /// @notice Represents temporary information needed during the processing\n /// of the moving funds Bitcoin transaction outputs. This structure\n /// is an internal one and should not be exported outside of the\n /// moving funds transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct MovingFundsTxOutputsProcessingInfo {\n // 32-byte hash of the moving funds Bitcoin transaction.\n bytes32 movingFundsTxHash;\n // Output vector of the moving funds Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVout` function before being used\n // during the processing. The validation is usually done as part\n // of the `BitcoinTx.validateProof` call that checks the SPV proof.\n bytes movingFundsTxOutputVector;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's memory argument.\n }\n\n /// @notice Represents moved funds sweep request state.\n enum MovedFundsSweepRequestState {\n /// @dev The request is unknown to the Bridge.\n Unknown,\n /// @dev Request is pending and can become either processed or timed out.\n Pending,\n /// @dev Request was processed by the target wallet.\n Processed,\n /// @dev Request was not processed in the given time window and\n /// the timeout was reported.\n TimedOut\n }\n\n /// @notice Represents a moved funds sweep request. The request is\n /// registered in `submitMovingFundsProof` where we know funds\n /// have been moved to the target wallet and the only step left is\n /// to have the target wallet sweep them.\n struct MovedFundsSweepRequest {\n // 20-byte public key hash of the wallet supposed to sweep the UTXO\n // representing the received funds with their own main UTXO\n bytes20 walletPubKeyHash;\n // Value of the received funds.\n uint64 value;\n // UNIX timestamp the request was created at.\n uint32 createdAt;\n // The current state of the request.\n MovedFundsSweepRequestState state;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\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 pending moved funds sweep 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.pendingMovedFundsSweepRequestsCount == 0,\n \"Source wallet must handle all pending moved funds sweep requests 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. However, the wallet supposed to submit the\n // commitment can keep resetting the moving funds timeout until then.\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 Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(\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 // If the moving funds wallet already submitted their target wallets\n // commitment, there is no point to reset the timeout since the\n // wallet can make the BTC transaction and submit the proof.\n require(\n wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),\n \"Target wallets commitment already submitted\"\n );\n\n require(self.liveWalletsCount == 0, \"Live wallets count must be zero\");\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n wallet.movingFundsRequestedAt +\n self.movingFundsTimeoutResetDelay,\n \"Moving funds timeout cannot be reset yet\"\n );\n\n /* solhint-disable-next-line not-rely-on-time */\n wallet.movingFundsRequestedAt = uint32(block.timestamp);\n\n emit MovingFundsTimeoutReset(walletPubKeyHash);\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(\n self,\n MovingFundsTxOutputsProcessingInfo(\n movingFundsTxHash,\n movingFundsTx.outputVector\n )\n );\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 processInfo Processing info containing the moving funds tx\n /// hash and output vector.\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(\n BridgeState.Storage storage self,\n MovingFundsTxOutputsProcessingInfo memory processInfo\n ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {\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 ) = processInfo.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. Note that the `outputIndex` must be\n // `uint32` to build proper `movedFundsSweepRequests` keys.\n for (\n uint32 outputIndex = 0;\n outputIndex < outputsCount;\n outputIndex++\n ) {\n uint256 outputLength = processInfo\n .movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = processInfo.movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);\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[outputIndex] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[outputIndex] = output.extractValue();\n outputsTotalValue += outputsValues[outputIndex];\n\n // Register a moved funds sweep request that must be handled\n // by the target wallet. The target wallet must sweep the\n // received funds with their own main UTXO in order to update\n // their BTC balance. Worth noting there is no need to check\n // if the sweep request already exists in the system because\n // the moving funds wallet is moved to the Closing state after\n // submitting the moving funds proof so there is no possibility\n // to submit the proof again and register the sweep request twice.\n self.movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n processInfo.movingFundsTxHash,\n outputIndex\n )\n )\n )\n ] = MovedFundsSweepRequest(\n targetWalletPubKeyHash,\n outputsValues[outputIndex],\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovedFundsSweepRequestState.Pending\n );\n // We added a new moved funds sweep request for the target wallet\n // so we must increment their request counter.\n self\n .registeredWallets[targetWalletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\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 /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\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 of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\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 self.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\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 /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\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\n /// the first input pointing to a wallet's sweep Pending request and,\n /// optionally, the second input pointing to the wallet's main UTXO,\n /// if the sweeping wallet has a main UTXO set. There should be only\n /// one output locking funds on the sweeping wallet 20-byte public\n /// key hash,\n /// - `sweepProof` 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 sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\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 (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo,\n walletPubKeyHash\n );\n\n require(\n sweepTxInputsTotalValue - sweepTxOutputValue <=\n self.movedFundsSweepTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n // Use the sweep transaction output as the new sweeping wallet's main UTXO.\n // Transaction output index is always 0 as sweep transaction always\n // contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);\n }\n\n /// @notice Processes the Bitcoin moved funds sweep transaction output vector\n /// by 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 moved funds sweep transaction output\n /// 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 moved funds sweep transaction output value.\n /// @dev Requirements:\n /// - Output vector must contain only one output,\n /// - The single output must be of P2PKH or P2WPKH type and lock the\n /// funds on a 20-byte public key hash.\n function processMovedFundsSweepTxOutput(\n BridgeState.Storage storage self,\n bytes memory sweepTxOutputVector\n ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {\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 performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Moved funds sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\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 /// @return wallet Data of the sweeping wallet.\n /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet\n /// resolved by cross-checking the `mainUtxo` parameter with\n /// the chain state. If the validation went well, this is the\n /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.\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 resolveMovedFundsSweepingWallet(\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 moved funds sweep transaction input vector.\n /// It extracts the first input and tries to match it with one of\n /// the moved funds sweep requests targeting the sweeping wallet.\n /// If the sweep request is an existing Pending request, this\n /// function marks it as Processed. If the sweeping wallet has a\n /// main UTXO, this function extracts the second input, makes sure\n /// it refers to the wallet main UTXO, and marks that main UTXO as\n /// correctly spent.\n /// @param sweepTxInputVector Bitcoin moved funds 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 sweeping 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 /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet.\n /// @return inputsTotalValue Total inputs value sum.\n /// @dev Requirements:\n /// - The input vector must consist of one mandatory and one optional\n /// input,\n /// - The mandatory input must be the first input in the vector,\n /// - The mandatory input must point to a Pending moved funds sweep\n /// request that is targeted to the sweeping wallet,\n /// - The optional output must be the second input in the vector,\n /// - The optional input is required if the sweeping wallet has a\n /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,\n /// that input must point the the sweeping wallet main UTXO.\n function processMovedFundsSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo,\n bytes20 walletPubKeyHash\n ) internal returns (uint256 inputsTotalValue) {\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 performed as\n // part of the `BitcoinTx.validateProof` call.\n // See `BitcoinTx.inputVector` docs for 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 // We always expect the first input to be the swept UTXO. Additionally,\n // if the sweeping wallet has a main UTXO, that main UTXO should be\n // pointed by the second input.\n require(\n inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),\n \"Moved funds sweep transaction must have a proper inputs count\"\n );\n\n // Parse the first input and extract its outpoint tx hash and index.\n (\n bytes32 firstInputOutpointTxHash,\n uint32 firstInputOutpointIndex,\n uint256 firstInputLength\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex\n );\n\n // Build the request key and fetch the corresponding moved funds sweep\n // request from contract storage.\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n firstInputOutpointTxHash,\n firstInputOutpointIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n // We must check if the wallet extracted from the moved funds sweep\n // transaction output is truly the owner of the sweep request connected\n // with the swept UTXO. This is needed to prevent a case when a wallet\n // handles its own sweep request but locks the funds on another\n // wallet public key hash.\n require(\n sweepRequest.walletPubKeyHash == walletPubKeyHash,\n \"Sweep request belongs to another wallet\"\n );\n // If the validation passed, the sweep request must be marked as\n // processed and its value should be counted into the total inputs\n // value sum.\n sweepRequest.state = MovedFundsSweepRequestState.Processed;\n inputsTotalValue += sweepRequest.value;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n\n // If the main UTXO for the sweeping wallet exists, it must be processed.\n if (mainUtxo.txHash != bytes32(0)) {\n // The second input is supposed to point to that sweeping wallet\n // main UTXO. We need to parse that input.\n (\n bytes32 secondInputOutpointTxHash,\n uint32 secondInputOutpointIndex,\n\n ) = parseMovedFundsSweepTxInputAt(\n sweepTxInputVector,\n inputStartingIndex + firstInputLength\n );\n // Make sure the second input refers to the sweeping wallet main UTXO.\n require(\n mainUtxo.txHash == secondInputOutpointTxHash &&\n mainUtxo.txOutputIndex == secondInputOutpointIndex,\n \"Second input must point to the wallet's main UTXO\"\n );\n\n // If the validation passed, count the main UTXO value into the\n // total inputs value sum.\n inputsTotalValue += mainUtxo.txOutputValue;\n\n // Main UTXO used as an input, mark it as spent. This is needed\n // to defend against fraud challenges referring to this main UTXO.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(\n secondInputOutpointTxHash,\n secondInputOutpointIndex\n )\n )\n )\n ] = true;\n }\n\n return inputsTotalValue;\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 parseMovedFundsSweepTxInputAt(\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 Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,,\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 of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n BridgeState.Storage storage self,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n MovedFundsSweepRequest storage sweepRequest = self\n .movedFundsSweepRequests[\n uint256(\n keccak256(\n abi.encodePacked(\n movingFundsTxHash,\n movingFundsTxOutputIndex\n )\n )\n )\n ];\n\n require(\n sweepRequest.state == MovedFundsSweepRequestState.Pending,\n \"Sweep request must be in Pending state\"\n );\n\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >\n sweepRequest.createdAt + self.movedFundsSweepTimeout,\n \"Sweep request has not timed out yet\"\n );\n\n bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n Wallets.WalletState walletState = wallet.state;\n\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds ||\n walletState == Wallets.WalletState.Terminated,\n \"ECDSA wallet must be in Live or MovingFunds or Terminated state\"\n );\n\n sweepRequest.state = MovedFundsSweepRequestState.TimedOut;\n wallet.pendingMovedFundsSweepRequestsCount--;\n\n if (\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds\n ) {\n self.terminateWallet(walletPubKeyHash);\n\n self.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
201
201
  },
202
202
  "@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol": {
203
203
  "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"
@@ -209,7 +209,7 @@
209
209
  "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/MovingFunds.sol\";\nimport \"../bridge/Wallets.sol\";\n\ncontract BridgeStub is Bridge {\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 setProcessedMovedFundsSweepRequests(\n BitcoinTx.UTXO[] calldata utxos\n ) 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.movedFundsSweepRequests[utxoKey].state = MovingFunds\n .MovedFundsSweepRequestState\n .Processed;\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 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 function setPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n self.movedFundsSweepRequests[requestKey] = MovingFunds\n .MovedFundsSweepRequest(\n walletPubKeyHash,\n utxo.txOutputValue,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp),\n MovingFunds.MovedFundsSweepRequestState.Pending\n );\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount++;\n }\n\n function processPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.Processed;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function timeoutPendingMovedFundsSweepRequest(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n uint256 requestKey = uint256(\n keccak256(abi.encodePacked(utxo.txHash, utxo.txOutputIndex))\n );\n\n MovingFunds.MovedFundsSweepRequest storage request = self\n .movedFundsSweepRequests[requestKey];\n\n require(\n request.state == MovingFunds.MovedFundsSweepRequestState.Pending,\n \"Stub sweep request must be in Pending state\"\n );\n\n request.state = MovingFunds.MovedFundsSweepRequestState.TimedOut;\n\n self\n .registeredWallets[walletPubKeyHash]\n .pendingMovedFundsSweepRequestsCount--;\n }\n\n function setMovedFundsSweepTxMaxTotalFee(\n uint64 _movedFundsSweepTxMaxTotalFee\n ) external {\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n }\n}\n"
210
210
  },
211
211
  "contracts/bridge/Bridge.sol": {
212
- "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\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.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.\ncontract Bridge is Governable, EcdsaWalletOwner, Initializable {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep 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 indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed 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 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\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 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed 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 uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) external initializer {\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 // https://github.com/keep-network/tbtc-v2/issues/258\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.redemptionTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsDustThreshold = 20000; // 20000 satoshi\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movedFundsSweepTxMaxTotalFee = 10000; // 10000 satoshi\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 2 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 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 /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\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 /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\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 submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\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:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\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 of the `WalletRegistry` contract,\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 uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\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 pending moved funds sweep 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 Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\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 /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\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 of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\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 Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\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\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` 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 sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\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 of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\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 /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, 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 Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\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 heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud 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 of the `WalletRegistry` contract,\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 bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\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 /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\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 /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\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 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 /// @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 movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout must be greater than zero,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\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 walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\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 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\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 /// @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 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 /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\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 Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\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 /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\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 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 /// @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 movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\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 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\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 fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\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 function fraudParameters()\n external\n view\n returns (\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\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"
212
+ "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\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.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.\ncontract Bridge is Governable, EcdsaWalletOwner, Initializable {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep 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 indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed 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 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\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 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed 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 uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n );\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) external initializer {\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 // https://github.com/keep-network/tbtc-v2/issues/258\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.redemptionTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n self.movingFundsDustThreshold = 20000; // 20000 satoshi\n self.movingFundsTimeoutResetDelay = 6 days;\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movedFundsSweepTxMaxTotalFee = 10000; // 10000 satoshi\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 10000 * 1e18; // 10000 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 2 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 10000 * 1e18; // 10000 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 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 /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\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 /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\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 submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\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:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\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 of the `WalletRegistry` contract,\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 uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\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 pending moved funds sweep 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 Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\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 /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\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 of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\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 Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\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\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` 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 sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\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 of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\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 /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, 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 Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\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 heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\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 preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud 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 of the `WalletRegistry` contract,\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 bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\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 /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\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 /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\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 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 /// @param movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\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 movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\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 walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\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 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\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 /// @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 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 /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\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 Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\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 /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint256 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint256 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\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 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 /// @return movingFundsTimeoutResetDelay Time after which the moving funds\n /// timeout can be reset in case the target wallet commitment\n /// cannot be submitted due to a lack of live wallets in the system.\n /// It is counted from the moment when the wallet was requested to\n /// move their funds and switched to the MovingFunds state or from\n /// the moment the timeout was reset the last time. Value in seconds\n /// This value should be lower than the value of the\n /// `movingFundsTimeout`.\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 movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint256 movingFundsTimeoutNotifierRewardMultiplier,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeoutResetDelay = self.movingFundsTimeoutResetDelay;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\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 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\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 fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\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 function fraudParameters()\n external\n view\n returns (\n uint256 fraudChallengeDepositAmount,\n uint256 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint256 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\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"
213
213
  },
214
214
  "@keep-network/ecdsa/contracts/api/IWalletOwner.sol": {
215
215
  "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\ninterface IWalletOwner {\n /// @notice Callback function executed once a new wallet is created.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletCreatedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n\n /// @notice Callback function executed once a wallet heartbeat failure\n /// is detected.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n}\n"