@keep-network/tbtc-v2 0.1.1-dev.95 → 0.1.1-dev.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/artifacts/Bank.json +3 -3
- package/artifacts/Bridge.json +11 -11
- package/artifacts/Deposit.json +9 -9
- package/artifacts/DepositSweep.json +7 -7
- package/artifacts/EcdsaDkgValidator.json +1 -1
- package/artifacts/EcdsaInactivity.json +1 -1
- package/artifacts/EcdsaSortitionPool.json +2 -2
- package/artifacts/Fraud.json +7 -7
- package/artifacts/KeepRegistry.json +1 -1
- package/artifacts/KeepStake.json +2 -2
- package/artifacts/KeepToken.json +2 -2
- package/artifacts/KeepTokenStaking.json +1 -1
- package/artifacts/MovingFunds.json +9 -9
- package/artifacts/NuCypherStakingEscrow.json +1 -1
- package/artifacts/NuCypherToken.json +2 -2
- package/artifacts/RandomBeaconStub.json +1 -1
- package/artifacts/Redemption.json +9 -9
- package/artifacts/ReimbursementPool.json +2 -2
- package/artifacts/Relay.json +9 -9
- package/artifacts/T.json +2 -2
- package/artifacts/TBTC.json +3 -3
- package/artifacts/TBTCToken.json +3 -3
- package/artifacts/TBTCVault.json +12 -12
- package/artifacts/TokenStaking.json +1 -1
- package/artifacts/TokenholderGovernor.json +9 -9
- package/artifacts/TokenholderTimelock.json +8 -8
- package/artifacts/VendingMachine.json +10 -10
- package/artifacts/VendingMachineKeep.json +1 -1
- package/artifacts/VendingMachineNuCypher.json +1 -1
- package/artifacts/WalletRegistry.json +5 -5
- package/artifacts/WalletRegistryGovernance.json +2 -2
- package/artifacts/Wallets.json +7 -7
- package/artifacts/solcInputs/{b1eed895af5ae97fee0102eb17dac6e6.json → 3cf46a7694ce157f71d9dbf4db692b09.json} +3 -3
- package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
- package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
- package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
- package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
- package/build/contracts/bridge/Bridge.sol/Bridge.json +2 -2
- package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
- package/build/contracts/bridge/BridgeState.sol/BridgeState.json +2 -2
- package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
- package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
- package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +1 -1
- package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +2 -2
- package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
- package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
- package/build/contracts/bridge/Fraud.sol/Fraud.json +2 -2
- package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +1 -1
- package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
- package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
- package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +2 -2
- package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/OutboundTx.json +2 -2
- package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/Redemption.json +2 -2
- package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
- package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
- package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
- package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
- package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +1 -1
- package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
- package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
- package/contracts/bridge/DepositSweep.sol +3 -0
- package/contracts/bridge/MovingFunds.sol +23 -2
- package/contracts/bridge/Redemption.sol +55 -37
- package/package.json +1 -1
|
@@ -149,10 +149,10 @@
|
|
|
149
149
|
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge deposit\n/// @notice The library handles the logic for revealing Bitcoin deposits to\n/// the Bridge.\n/// @dev The depositor puts together a P2SH or P2WSH address to deposit the\n/// funds. This script is unique to each depositor and looks like this:\n///\n/// ```\n/// <depositorAddress> DROP\n/// <blindingFactor> DROP\n/// DUP HASH160 <walletPubKeyHash> EQUAL\n/// IF\n/// CHECKSIG\n/// ELSE\n/// DUP HASH160 <refundPubkeyHash> EQUALVERIFY\n/// <refundLocktime> CHECKLOCKTIMEVERIFY DROP\n/// CHECKSIG\n/// ENDIF\n/// ```\n///\n/// Since each depositor has their own Ethereum address and their own\n/// secret blinding factor, each depositor’s script is unique, and the hash\n/// of each depositor’s script is unique.\nlibrary Deposit {\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents data which must be revealed by the depositor during\n /// deposit reveal.\n struct DepositRevealInfo {\n // Index of the funding output belonging to the funding transaction.\n uint32 fundingOutputIndex;\n // Ethereum depositor address.\n address depositor;\n // The blinding factor as 8 bytes. Byte endianness doesn't matter\n // as this factor is not interpreted as uint.\n bytes8 blindingFactor;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.\n bytes20 walletPubKeyHash;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // that can be used to make the deposit refund after the refund\n // locktime passes. Hashed in the HASH160 Bitcoin opcode style.\n bytes20 refundPubKeyHash;\n // The refund locktime (4-byte LE). Interpreted according to locktime\n // parsing rules described in:\n // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number\n // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:\n // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki\n bytes4 refundLocktime;\n // Address of the Bank vault to which the deposit is routed to.\n // Optional, can be 0x0. The vault must be trusted by the Bridge.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents tBTC deposit request data.\n struct DepositRequest {\n // Ethereum depositor address.\n address depositor;\n // Deposit amount in satoshi.\n uint64 amount;\n // UNIX timestamp the deposit was revealed at.\n uint32 revealedAt;\n // Address of the Bank vault the deposit is routed to.\n // Optional, can be 0x0.\n address vault;\n // Treasury TBTC fee in satoshi at the moment of deposit reveal.\n uint64 treasuryFee;\n // UNIX timestamp the deposit was swept at. Note this is not the\n // time when the deposit was swept on the Bitcoin chain but actually\n // the time when the sweep proof was delivered to the Ethereum chain.\n uint32 sweptAt;\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 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 /// @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 BridgeState.Storage storage self,\n BitcoinTx.Info calldata fundingTx,\n DepositRevealInfo calldata reveal\n ) external {\n require(\n self.registeredWallets[reveal.walletPubKeyHash].state ==\n Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n require(\n reveal.vault == address(0) || self.isVaultTrusted[reveal.vault],\n \"Vault is not trusted\"\n );\n\n bytes memory expectedScript = abi.encodePacked(\n hex\"14\", // Byte length of depositor Ethereum address.\n reveal.depositor,\n hex\"75\", // OP_DROP\n hex\"08\", // Byte length of blinding factor value.\n reveal.blindingFactor,\n hex\"75\", // OP_DROP\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.walletPubKeyHash,\n hex\"87\", // OP_EQUAL\n hex\"63\", // OP_IF\n hex\"ac\", // OP_CHECKSIG\n hex\"67\", // OP_ELSE\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.refundPubKeyHash,\n hex\"88\", // OP_EQUALVERIFY\n hex\"04\", // Byte length of refund locktime value.\n reveal.refundLocktime,\n hex\"b1\", // OP_CHECKLOCKTIMEVERIFY\n hex\"75\", // OP_DROP\n hex\"ac\", // OP_CHECKSIG\n hex\"68\" // OP_ENDIF\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n bytes memory fundingOutputHash = fundingOutput.extractHash();\n\n if (fundingOutputHash.length == 20) {\n // A 20-byte output hash is used by P2SH. That hash is constructed\n // by applying OP_HASH160 on the locking script. A 20-byte output\n // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the\n // public key). However, since we compare the actual output hash\n // with an expected locking script hash, this check will succeed only\n // for P2SH transaction type with expected script hash value. For\n // P2PKH and P2WPKH, it will fail on the output hash comparison with\n // the expected locking script hash.\n require(\n fundingOutputHash.slice20(0) == expectedScript.hash160View(),\n \"Wrong 20-byte script hash\"\n );\n } else if (fundingOutputHash.length == 32) {\n // A 32-byte output hash is used by P2WSH. That hash is constructed\n // by applying OP_SHA256 on the locking script.\n require(\n fundingOutputHash.toBytes32() == sha256(expectedScript),\n \"Wrong 32-byte script hash\"\n );\n } else {\n revert(\"Wrong script hash length\");\n }\n\n // Resulting TX hash is in native Bitcoin little-endian format.\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n )\n ];\n require(deposit.revealedAt == 0, \"Deposit already revealed\");\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n require(\n fundingOutputAmount >= self.depositDustThreshold,\n \"Deposit amount too small\"\n );\n\n deposit.amount = fundingOutputAmount;\n deposit.depositor = reveal.depositor;\n /* solhint-disable-next-line not-rely-on-time */\n deposit.revealedAt = uint32(block.timestamp);\n deposit.vault = reveal.vault;\n deposit.treasuryFee = self.depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / self.depositTreasuryFeeDivisor\n : 0;\n // slither-disable-next-line reentrancy-events\n emit DepositRevealed(\n fundingTxHash,\n reveal.fundingOutputIndex,\n reveal.depositor,\n fundingOutputAmount,\n reveal.blindingFactor,\n reveal.walletPubKeyHash,\n reveal.refundPubKeyHash,\n reveal.refundLocktime,\n reveal.vault\n );\n }\n}\n"
|
|
150
150
|
},
|
|
151
151
|
"contracts/bridge/DepositSweep.sol": {
|
|
152
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bridge deposit sweep\n/// @notice The library handles the logic for sweeping transactions revealed to\n/// the Bridge\n/// @dev Bridge active wallet periodically signs a transaction that unlocks all\n/// of the valid, revealed deposits above the dust threshold, combines them\n/// into a single UTXO with the existing main wallet UTXO, and relocks\n/// those transactions without a 30-day refund clause to the same wallet.\n/// This has two main effects: it consolidates the UTXO set and it disables\n/// the refund. Balances of depositors in the Bank are increased when the\n/// SPV sweep proof is submitted to the Bridge.\nlibrary DepositSweep {\n using BridgeState for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the deposit sweep Bitcoin transaction inputs. This structure\n /// is an internal one and should not be exported outside of the\n /// deposit sweep transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct DepositSweepTxInputsProcessingInfo {\n // Input vector of the deposit sweep Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVin` 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 sweepTxInputVector;\n // Data of the wallet's main UTXO. If no main UTXO exists for the given\n // sweeping wallet, this parameter's fields should be zeroed to bypass\n // the main UTXO validation\n BitcoinTx.UTXO mainUtxo;\n // Address of the vault where all swept deposits should be routed to.\n // It is used to validate whether all swept deposits have been revealed\n // with the same `vault` parameter. It is an optional parameter.\n // Set to zero address if deposits are not routed to a vault.\n address vault;\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 an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct DepositSweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n // 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 event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @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 BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processDepositSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveDepositSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n DepositSweepTxInputsInfo\n memory inputsInfo = processDepositSweepTxInputs(\n self,\n DepositSweepTxInputsProcessingInfo(\n sweepTx.inputVector,\n resolvedMainUtxo,\n vault\n )\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = depositSweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n if (vault != address(0) && self.isVaultTrusted[vault]) {\n // If the `vault` address is not zero and belongs to a trusted\n // vault, route the deposits to that vault.\n self.bank.increaseBalanceAndCall(\n vault,\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n } else {\n // If the `vault` address is zero or belongs to a non-trusted\n // vault, increase balances in the Bank individually for each\n // depositor.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n }\n\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\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 resolveDepositSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processDepositSweepTxOutput(\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.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @return resultInfo Outcomes of the processing.\n function processDepositSweepTxInputs(\n BridgeState.Storage storage self,\n DepositSweepTxInputsProcessingInfo memory processInfo\n ) internal returns (DepositSweepTxInputsInfo memory resultInfo) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = processInfo.mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = processInfo\n .sweepTxInputVector\n .parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n resultInfo.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n resultInfo.depositedAmounts = new uint256[](\n resultInfo.depositors.length\n );\n resultInfo.treasuryFees = new uint256[](resultInfo.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseDepositSweepTxInputAt(\n processInfo.sweepTxInputVector,\n inputStartingIndex\n );\n\n Deposit.DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n require(\n deposit.vault == processInfo.vault,\n \"Deposit should be routed to another vault\"\n );\n\n if (processedDepositsCount == resultInfo.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n resultInfo.depositors[processedDepositsCount] = deposit\n .depositor;\n resultInfo.depositedAmounts[processedDepositsCount] = deposit\n .amount;\n resultInfo.inputsTotalValue += resultInfo.depositedAmounts[\n processedDepositsCount\n ];\n resultInfo.treasuryFees[processedDepositsCount] = deposit\n .treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n processInfo.mainUtxo.txHash == outpointTxHash &&\n processInfo.mainUtxo.txOutputIndex == outpointIndex\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n resultInfo.inputsTotalValue += processInfo\n .mainUtxo\n .txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == resultInfo.depositors.length == resultInfo.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return resultInfo;\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 parseDepositSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function depositSweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
|
|
152
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bridge deposit sweep\n/// @notice The library handles the logic for sweeping transactions revealed to\n/// the Bridge\n/// @dev Bridge active wallet periodically signs a transaction that unlocks all\n/// of the valid, revealed deposits above the dust threshold, combines them\n/// into a single UTXO with the existing main wallet UTXO, and relocks\n/// those transactions without a 30-day refund clause to the same wallet.\n/// This has two main effects: it consolidates the UTXO set and it disables\n/// the refund. Balances of depositors in the Bank are increased when the\n/// SPV sweep proof is submitted to the Bridge.\nlibrary DepositSweep {\n using BridgeState for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents temporary information needed during the processing\n /// of the deposit sweep Bitcoin transaction inputs. This structure\n /// is an internal one and should not be exported outside of the\n /// deposit sweep transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct DepositSweepTxInputsProcessingInfo {\n // Input vector of the deposit sweep Bitcoin transaction. It is\n // assumed the vector's structure is valid so it must be validated\n // using e.g. `BTCUtils.validateVin` 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 sweepTxInputVector;\n // Data of the wallet's main UTXO. If no main UTXO exists for the given\n // sweeping wallet, this parameter's fields should be zeroed to bypass\n // the main UTXO validation\n BitcoinTx.UTXO mainUtxo;\n // Address of the vault where all swept deposits should be routed to.\n // It is used to validate whether all swept deposits have been revealed\n // with the same `vault` parameter. It is an optional parameter.\n // Set to zero address if deposits are not routed to a vault.\n address vault;\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 an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct DepositSweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n // 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 event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @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 BridgeState.Storage storage self,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external {\n // Wallet state validation is performed in the\n // `resolveDepositSweepingWallet` function.\n\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processDepositSweepTxOutput(self, sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveDepositSweepingWallet(self, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n DepositSweepTxInputsInfo\n memory inputsInfo = processDepositSweepTxInputs(\n self,\n DepositSweepTxInputsProcessingInfo(\n sweepTx.inputVector,\n resolvedMainUtxo,\n vault\n )\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = depositSweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n // slither-disable-next-line reentrancy-events\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n if (vault != address(0) && self.isVaultTrusted[vault]) {\n // If the `vault` address is not zero and belongs to a trusted\n // vault, route the deposits to that vault.\n self.bank.increaseBalanceAndCall(\n vault,\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n } else {\n // If the `vault` address is zero or belongs to a non-trusted\n // vault, increase balances in the Bank individually for each\n // depositor.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n }\n\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\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 resolveDepositSweepingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n view\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here.\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processDepositSweepTxOutput(\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.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n walletPubKeyHash = self.extractPubKeyHash(output);\n value = output.extractValue();\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @return resultInfo Outcomes of the processing.\n function processDepositSweepTxInputs(\n BridgeState.Storage storage self,\n DepositSweepTxInputsProcessingInfo memory processInfo\n ) internal returns (DepositSweepTxInputsInfo memory resultInfo) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = processInfo.mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (uint256 inputsCompactSizeUintLength, uint256 inputsCount) = processInfo\n .sweepTxInputVector\n .parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n resultInfo.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n resultInfo.depositedAmounts = new uint256[](\n resultInfo.depositors.length\n );\n resultInfo.treasuryFees = new uint256[](resultInfo.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseDepositSweepTxInputAt(\n processInfo.sweepTxInputVector,\n inputStartingIndex\n );\n\n Deposit.DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n require(\n deposit.vault == processInfo.vault,\n \"Deposit should be routed to another vault\"\n );\n\n if (processedDepositsCount == resultInfo.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n resultInfo.depositors[processedDepositsCount] = deposit\n .depositor;\n resultInfo.depositedAmounts[processedDepositsCount] = deposit\n .amount;\n resultInfo.inputsTotalValue += resultInfo.depositedAmounts[\n processedDepositsCount\n ];\n resultInfo.treasuryFees[processedDepositsCount] = deposit\n .treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n processInfo.mainUtxo.txHash == outpointTxHash &&\n processInfo.mainUtxo.txOutputIndex == outpointIndex\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n resultInfo.inputsTotalValue += processInfo\n .mainUtxo\n .txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == resultInfo.depositors.length == resultInfo.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return resultInfo;\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 parseDepositSweepTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function depositSweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
|
|
153
153
|
},
|
|
154
154
|
"contracts/bridge/Redemption.sol": {
|
|
155
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @notice Aggregates functions common to the redemption transaction proof\n/// validation and to the moving funds transaction proof validation.\nlibrary OutboundTx {\n using BTCUtils for bytes;\n\n /// @notice Checks whether an outbound Bitcoin transaction performed from\n /// the given wallet has an input vector that contains a single\n /// input referring to the wallet's main UTXO. Marks that main UTXO\n /// as correctly spent if the validation succeeds. Reverts otherwise.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the outbound transaction.\n function processWalletOutboundTxInput(\n BridgeState.Storage storage self,\n bytes memory walletOutboundTxInputVector,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) internal {\n // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Assert that the single outbound transaction input actually\n // refers to the wallet's main UTXO.\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex\n ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);\n require(\n mainUtxo.txHash == outpointTxHash &&\n mainUtxo.txOutputIndex == outpointIndex,\n \"Outbound transaction input must point to the wallet's main UTXO\"\n );\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)\n )\n )\n ] = true;\n }\n\n /// @notice Parses the input vector of an outbound Bitcoin transaction\n /// performed from the given wallet. It extracts the single input\n /// then the transaction hash and output index from its outpoint.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the input's outpoint.\n function parseWalletOutboundTxInput(\n bytes memory walletOutboundTxInputVector\n ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation.\n // See `BitcoinTx.inputVector` docs for more details.\n (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();\n require(\n inputsCount == 1,\n \"Outbound transaction must have a single input\"\n );\n\n bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);\n\n outpointTxHash = input.extractInputTxIdLE();\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(input.extractTxIndexLE())\n );\n\n // There is only one input in the transaction. Input has an outpoint\n // field that is a reference to the transaction being spent (see\n // `BitcoinTx` docs). The outpoint contains the hash of the transaction\n // to spend (`outpointTxHash`) and the index of the specific output\n // from that transaction (`outpointIndex`).\n return (outpointTxHash, outpointIndex);\n }\n}\n\n/// @title Bridge redemption\n/// @notice The library handles the logic for redeeming Bitcoin balances from\n/// the Bridge.\n/// @dev To initiate a redemption, a user with a Bank balance supplies\n/// a Bitcoin address. Then, the system calculates the redemption fee, and\n/// releases balance to the provided Bitcoin address. Just like in case of\n/// sweeps of revealed deposits, redemption requests are processed in\n/// batches and require SPV proof to be submitted to the Bridge.\nlibrary Redemption {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n // 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 /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n // 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 temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n // 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 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 /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// This function handles the simplest case, where balance owner is\n /// the redeemer.\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 balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed. Balance owner address is stored as\n /// a redemeer address who will be able co claim back the Bank\n /// balance if anything goes wrong during the redemption.\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 Bank balance\n /// that is taken from the `balanceOwner` 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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n address balanceOwner,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n requestRedemption(\n self,\n walletPubKeyHash,\n mainUtxo,\n balanceOwner,\n balanceOwner,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Used by\n /// `Bridge.receiveBalanceApproval`. Can handle more complex cases\n /// where balance owner may be someone else than the redeemer.\n /// @param balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` 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 /// @param redemptionData ABI-encoded redemption data:\n /// [\n /// address redeemer,\n /// bytes20 walletPubKeyHash,\n /// bytes32 mainUtxoTxHash,\n /// uint32 mainUtxoTxOutputIndex,\n /// uint64 mainUtxoTxOutputValue,\n /// bytes redeemerOutputScript\n /// ]\n ///\n /// - redeemer: The Ethereum address of the redeemer who will be able\n /// to claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their Bitcoin\n /// balance from the Bank, `balanceOwner` is the same as `redemeer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redemeer` is\n /// the address for which the vault is redeeming its balance to,\n /// - walletPubKeyHash: The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key),\n /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as\n /// currently known on the Ethereum chain,\n /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output\n /// index, as currently known on Ethereum chain,\n /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output\n /// value, as currently known on Ethereum chain,\n /// - redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n address balanceOwner,\n uint64 amount,\n bytes calldata redemptionData\n ) external {\n (\n address redeemer,\n bytes20 walletPubKeyHash,\n bytes32 mainUtxoTxHash,\n uint32 mainUtxoTxOutputIndex,\n uint64 mainUtxoTxOutputValue,\n bytes memory redeemerOutputScript\n ) = abi.decode(\n redemptionData,\n (address, bytes20, bytes32, uint32, uint64, bytes)\n );\n\n requestRedemption(\n self,\n walletPubKeyHash,\n BitcoinTx.UTXO(\n mainUtxoTxHash,\n mainUtxoTxOutputIndex,\n mainUtxoTxOutputValue\n ),\n balanceOwner,\n redeemer,\n redeemerOutputScript,\n amount\n );\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 balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param redeemer The Ethereum address of the redeemer who will be able to\n /// claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their Bitcoin\n /// balance from the Bank, `balanceOwner` is the same as `redeemer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is\n /// the address for which the vault is redeeming its balance to.\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 Bank balance\n /// that is taken from the `balanceOwner` 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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO memory mainUtxo,\n address balanceOwner,\n address redeemer,\n bytes memory redeemerOutputScript,\n uint64 amount\n ) internal {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= self.redemptionDustThreshold,\n \"Redemption amount too small\"\n );\n\n // The redemption key is built on top of the wallet public key hash\n // and redeemer output script pair. That means there can be only one\n // request asking for redemption from the given wallet to the given\n // BTC script at the same time.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n\n // Check if given redemption key is not used by a pending redemption.\n // There is no need to check for existence in `timedOutRedemptions`\n // since the wallet's state is changed to other than Live after\n // first time out is reported so making new requests is not possible.\n // slither-disable-next-line incorrect-equality\n require(\n self.pendingRedemptions[redemptionKey].requestedAt == 0,\n \"There is a pending redemption request from this wallet to the same address\"\n );\n\n // No need to check whether `amount - treasuryFee - txMaxFee > 0`\n // since the `redemptionDustThreshold` should force that condition\n // to be always true.\n uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0\n ? amount / self.redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = self.redemptionTxMaxFee;\n\n // The main wallet UTXO's value doesn't include all pending redemptions.\n // To determine if the requested redemption can be performed by the\n // wallet we need to subtract the total value of all pending redemptions\n // from that wallet's main UTXO value. Given that the treasury fee is\n // not redeemed from the wallet, we are subtracting it.\n wallet.pendingRedemptionsValue += amount - treasuryFee;\n require(\n mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,\n \"Insufficient wallet funds\"\n );\n\n self.pendingRedemptions[redemptionKey] = RedemptionRequest(\n redeemer,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n redeemer,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(balanceOwner, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 redemptionTxHash = self.validateProof(\n redemptionTx,\n redemptionProof\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\n self,\n redemptionTx.outputVector,\n walletPubKeyHash\n );\n\n if (outputsInfo.changeValue > 0) {\n // If the change value is grater than zero, it means the change\n // output exists and can be used as new wallet's main UTXO.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(\n redemptionTxHash,\n outputsInfo.changeIndex,\n outputsInfo.changeValue\n )\n );\n } else {\n // If the change value is zero, it means the change output doesn't\n // exists and no funds left on the wallet. Delete the main UTXO\n // for that wallet to represent that state in a proper way.\n delete wallet.mainUtxoHash;\n }\n\n wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;\n\n emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);\n\n self.bank.decreaseBalance(outputsInfo.totalBurnableValue);\n self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);\n }\n\n /// @notice Processes the Bitcoin redemption transaction output vector.\n /// It extracts each output and tries to identify it as a pending\n /// redemption request, reported timed out request, or change.\n /// Reverts if one of the outputs cannot be recognized properly.\n /// This function also marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @return info Outcomes of the processing.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash\n ) internal returns (RedemptionTxOutputsInfo memory info) {\n // Determining the total number of redemption transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = redemptionTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH\n // scripts that can be used to lock the change. This is done upfront to\n // save on gas. Both scripts have a strict format defined by Bitcoin.\n //\n // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 walletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", walletPubKeyHash, hex\"88ac\")\n );\n // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 walletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", walletPubKeyHash)\n );\n\n return\n processRedemptionTxOutputs(\n self,\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\n // Helper flag indicating whether there was at least one redemption\n // output present (redemption must be either pending or reported as\n // timed out).\n bool redemptionPresent = false;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n // https://github.com/keep-network/tbtc-v2/issues/257\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n self,\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n redemptionPresent = true;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n redemptionPresent,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing them from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed.\n /// @param outputValue Value of the output being processed.\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {\n // If we entered here, that means the output was identified\n // as a pending redemption request.\n RedemptionRequest storage request = self.pendingRedemptions[\n redemptionKey\n ];\n // Compute the request's redeemable amount as the requested\n // amount reduced by the treasury fee. The request's\n // minimal amount is then the redeemable amount reduced by\n // the maximum transaction fee.\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n // Output value must fit between the request's redeemable\n // and minimal amounts to be deemed valid.\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the pending request\"\n );\n // Add the redeemable amount to the total burnable value\n // the Bridge will use to decrease its balance in the Bank.\n burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete self.pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = self.timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\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 BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n Redemption.RedemptionRequest memory request = self.pendingRedemptions[\n redemptionKey\n ];\n\n require(request.requestedAt > 0, \"Redemption request does not exist\");\n require(\n /* solhint-disable-next-line not-rely-on-time */\n request.requestedAt + self.redemptionTimeout < block.timestamp,\n \"Redemption request has not timed out\"\n );\n\n // Update the wallet's pending redemptions value\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"Wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n self.timedOutRedemptions[redemptionKey] = request;\n delete self.pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Slash the wallet operators and reward the notifier\n self.ecdsaWalletRegistry.seize(\n self.redemptionTimeoutSlashingAmount,\n self.redemptionTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n // Propagate timeout consequences to the wallet\n self.notifyWalletTimedOutRedemption(walletPubKeyHash);\n }\n\n // slither-disable-next-line reentrancy-events\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n self.bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n}\n"
|
|
155
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @notice Aggregates functions common to the redemption transaction proof\n/// validation and to the moving funds transaction proof validation.\nlibrary OutboundTx {\n using BTCUtils for bytes;\n\n /// @notice Checks whether an outbound Bitcoin transaction performed from\n /// the given wallet has an input vector that contains a single\n /// input referring to the wallet's main UTXO. Marks that main UTXO\n /// as correctly spent if the validation succeeds. Reverts otherwise.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n function processWalletOutboundTxInput(\n BridgeState.Storage storage self,\n bytes memory walletOutboundTxInputVector,\n BitcoinTx.UTXO calldata mainUtxo\n ) internal {\n // Assert that the single outbound transaction input actually\n // refers to the wallet's main UTXO.\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex\n ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);\n require(\n mainUtxo.txHash == outpointTxHash &&\n mainUtxo.txOutputIndex == outpointIndex,\n \"Outbound transaction input must point to the wallet's main UTXO\"\n );\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)\n )\n )\n ] = true;\n }\n\n /// @notice Parses the input vector of an outbound Bitcoin transaction\n /// performed from the given wallet. It extracts the single input\n /// then the transaction hash and output index from its outpoint.\n /// There are two outbound transactions from a wallet possible: a\n /// redemption transaction or a moving funds to another wallet\n /// transaction.\n /// @param walletOutboundTxInputVector Bitcoin outbound transaction input\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVin` function\n /// before it is passed here.\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the input's outpoint.\n function parseWalletOutboundTxInput(\n bytes memory walletOutboundTxInputVector\n ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {\n // To determine the total number of Bitcoin transaction inputs,\n // we need to parse the compactSize uint (VarInt) the input vector is\n // prepended by. That compactSize uint encodes the number of vector\n // elements using the format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVin` validation.\n // See `BitcoinTx.inputVector` docs for more details.\n (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();\n require(\n inputsCount == 1,\n \"Outbound transaction must have a single input\"\n );\n\n bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);\n\n outpointTxHash = input.extractInputTxIdLE();\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(input.extractTxIndexLE())\n );\n\n // There is only one input in the transaction. Input has an outpoint\n // field that is a reference to the transaction being spent (see\n // `BitcoinTx` docs). The outpoint contains the hash of the transaction\n // to spend (`outpointTxHash`) and the index of the specific output\n // from that transaction (`outpointIndex`).\n return (outpointTxHash, outpointIndex);\n }\n}\n\n/// @title Bridge redemption\n/// @notice The library handles the logic for redeeming Bitcoin balances from\n/// the Bridge.\n/// @dev To initiate a redemption, a user with a Bank balance supplies\n/// a Bitcoin address. Then, the system calculates the redemption fee, and\n/// releases balance to the provided Bitcoin address. Just like in case of\n/// sweeps of revealed deposits, redemption requests are processed in\n/// batches and require SPV proof to be submitted to the Bridge.\nlibrary Redemption {\n using BridgeState for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using BitcoinTx for BridgeState.Storage;\n\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n // 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 /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n // 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 temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n // 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 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 /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// This function handles the simplest case, where balance owner is\n /// the redeemer.\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 balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed. Balance owner address is stored as\n /// a redemeer address who will be able co claim back the Bank\n /// balance if anything goes wrong during the redemption.\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 Bank balance\n /// that is taken from the `balanceOwner` 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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n address balanceOwner,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n requestRedemption(\n self,\n walletPubKeyHash,\n mainUtxo,\n balanceOwner,\n balanceOwner,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Used by\n /// `Bridge.receiveBalanceApproval`. Can handle more complex cases\n /// where balance owner may be someone else than the redeemer.\n /// @param balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` 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 /// @param redemptionData ABI-encoded redemption data:\n /// [\n /// address redeemer,\n /// bytes20 walletPubKeyHash,\n /// bytes32 mainUtxoTxHash,\n /// uint32 mainUtxoTxOutputIndex,\n /// uint64 mainUtxoTxOutputValue,\n /// bytes redeemerOutputScript\n /// ]\n ///\n /// - redeemer: The Ethereum address of the redeemer who will be able\n /// to claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their Bitcoin\n /// balance from the Bank, `balanceOwner` is the same as `redemeer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redemeer` is\n /// the address for which the vault is redeeming its balance to,\n /// - walletPubKeyHash: The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key),\n /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as\n /// currently known on the Ethereum chain,\n /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output\n /// index, as currently known on Ethereum chain,\n /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output\n /// value, as currently known on Ethereum chain,\n /// - redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n address balanceOwner,\n uint64 amount,\n bytes calldata redemptionData\n ) external {\n (\n address redeemer,\n bytes20 walletPubKeyHash,\n bytes32 mainUtxoTxHash,\n uint32 mainUtxoTxOutputIndex,\n uint64 mainUtxoTxOutputValue,\n bytes memory redeemerOutputScript\n ) = abi.decode(\n redemptionData,\n (address, bytes20, bytes32, uint32, uint64, bytes)\n );\n\n requestRedemption(\n self,\n walletPubKeyHash,\n BitcoinTx.UTXO(\n mainUtxoTxHash,\n mainUtxoTxOutputIndex,\n mainUtxoTxOutputValue\n ),\n balanceOwner,\n redeemer,\n redeemerOutputScript,\n amount\n );\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 balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param redeemer The Ethereum address of the redeemer who will be able to\n /// claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their Bitcoin\n /// balance from the Bank, `balanceOwner` is the same as `redeemer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is\n /// the address for which the vault is redeeming its balance to.\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 Bank balance\n /// that is taken from the `balanceOwner` 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 /// - Balance owner must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO memory mainUtxo,\n address balanceOwner,\n address redeemer,\n bytes memory redeemerOutputScript,\n uint64 amount\n ) internal {\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= self.redemptionDustThreshold,\n \"Redemption amount too small\"\n );\n\n // The redemption key is built on top of the wallet public key hash\n // and redeemer output script pair. That means there can be only one\n // request asking for redemption from the given wallet to the given\n // BTC script at the same time.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n\n // Check if given redemption key is not used by a pending redemption.\n // There is no need to check for existence in `timedOutRedemptions`\n // since the wallet's state is changed to other than Live after\n // first time out is reported so making new requests is not possible.\n // slither-disable-next-line incorrect-equality\n require(\n self.pendingRedemptions[redemptionKey].requestedAt == 0,\n \"There is a pending redemption request from this wallet to the same address\"\n );\n\n // No need to check whether `amount - treasuryFee - txMaxFee > 0`\n // since the `redemptionDustThreshold` should force that condition\n // to be always true.\n uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0\n ? amount / self.redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = self.redemptionTxMaxFee;\n\n // The main wallet UTXO's value doesn't include all pending redemptions.\n // To determine if the requested redemption can be performed by the\n // wallet we need to subtract the total value of all pending redemptions\n // from that wallet's main UTXO value. Given that the treasury fee is\n // not redeemed from the wallet, we are subtracting it.\n wallet.pendingRedemptionsValue += amount - treasuryFee;\n require(\n mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,\n \"Insufficient wallet funds\"\n );\n\n self.pendingRedemptions[redemptionKey] = RedemptionRequest(\n redeemer,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n redeemer,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(balanceOwner, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // Wallet state validation is performed in the `resolveRedeemingWallet`\n // function.\n\n // The actual transaction proof is performed here. After that point, we\n // can assume the transaction happened on Bitcoin chain and has\n // a sufficient number of confirmations as determined by\n // `txProofDifficultyFactor` constant.\n bytes32 redemptionTxHash = self.validateProof(\n redemptionTx,\n redemptionProof\n );\n\n Wallets.Wallet storage wallet = resolveRedeemingWallet(\n self,\n walletPubKeyHash,\n mainUtxo\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n OutboundTx.processWalletOutboundTxInput(\n self,\n redemptionTx.inputVector,\n mainUtxo\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\n self,\n redemptionTx.outputVector,\n walletPubKeyHash\n );\n\n if (outputsInfo.changeValue > 0) {\n // If the change value is grater than zero, it means the change\n // output exists and can be used as new wallet's main UTXO.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(\n redemptionTxHash,\n outputsInfo.changeIndex,\n outputsInfo.changeValue\n )\n );\n } else {\n // If the change value is zero, it means the change output doesn't\n // exists and no funds left on the wallet. Delete the main UTXO\n // for that wallet to represent that state in a proper way.\n delete wallet.mainUtxoHash;\n }\n\n wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;\n\n emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);\n\n self.bank.decreaseBalance(outputsInfo.totalBurnableValue);\n self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);\n }\n\n /// @notice Resolves redeeming wallet based on the provided wallet public\n /// key 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.\n /// @return wallet Data of the sweeping wallet.\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state,\n /// - Main UTXO of the redeeming wallet must exists in the storage,\n /// - The passed `mainUTXO` parameter must be equal to the stored one.\n function resolveRedeemingWallet(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) internal view returns (Wallets.Wallet storage wallet) {\n wallet = self.registeredWallets[walletPubKeyHash];\n\n // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n 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\n /// @notice Processes the Bitcoin redemption transaction output vector.\n /// It extracts each output and tries to identify it as a pending\n /// redemption request, reported timed out request, or change.\n /// Reverts if one of the outputs cannot be recognized properly.\n /// This function also marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @return info Outcomes of the processing.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash\n ) internal returns (RedemptionTxOutputsInfo memory info) {\n // Determining the total number of redemption transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = redemptionTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH\n // scripts that can be used to lock the change. This is done upfront to\n // save on gas. Both scripts have a strict format defined by Bitcoin.\n //\n // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 walletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", walletPubKeyHash, hex\"88ac\")\n );\n // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.\n // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 walletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", walletPubKeyHash)\n );\n\n return\n processRedemptionTxOutputs(\n self,\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n BridgeState.Storage storage self,\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\n // Helper flag indicating whether there was at least one redemption\n // output present (redemption must be either pending or reported as\n // timed out).\n bool redemptionPresent = false;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n // https://github.com/keep-network/tbtc-v2/issues/257\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n self,\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n redemptionPresent = true;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n redemptionPresent,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing them from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed.\n /// @param outputValue Value of the output being processed.\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {\n // If we entered here, that means the output was identified\n // as a pending redemption request.\n RedemptionRequest storage request = self.pendingRedemptions[\n redemptionKey\n ];\n // Compute the request's redeemable amount as the requested\n // amount reduced by the treasury fee. The request's\n // minimal amount is then the redeemable amount reduced by\n // the maximum transaction fee.\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n // Output value must fit between the request's redeemable\n // and minimal amounts to be deemed valid.\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the pending request\"\n );\n // Add the redeemable amount to the total burnable value\n // the Bridge will use to decrease its balance in the Bank.\n burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete self.pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = self.timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function:\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 BridgeState.Storage storage self,\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n Redemption.RedemptionRequest memory request = self.pendingRedemptions[\n redemptionKey\n ];\n\n require(request.requestedAt > 0, \"Redemption request does not exist\");\n require(\n /* solhint-disable-next-line not-rely-on-time */\n request.requestedAt + self.redemptionTimeout < block.timestamp,\n \"Redemption request has not timed out\"\n );\n\n // Update the wallet's pending redemptions value\n Wallets.Wallet storage wallet = self.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"Wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n self.timedOutRedemptions[redemptionKey] = request;\n delete self.pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Slash the wallet operators and reward the notifier\n self.ecdsaWalletRegistry.seize(\n self.redemptionTimeoutSlashingAmount,\n self.redemptionTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n // Propagate timeout consequences to the wallet\n self.notifyWalletTimedOutRedemption(walletPubKeyHash);\n }\n\n // slither-disable-next-line reentrancy-events\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n self.bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n}\n"
|
|
156
156
|
},
|
|
157
157
|
"contracts/bridge/BitcoinTx.sol": {
|
|
158
158
|
"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\";\nimport {ValidateSPV} from \"@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol\";\n\nimport \"./BridgeState.sol\";\n\n/// @title Bitcoin transaction\n/// @notice Allows to reference Bitcoin raw transaction in Solidity.\n/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format\n///\n/// Raw Bitcoin transaction data:\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|--------------|------------------------|---------------------------|\n/// | 4 | version | int32_t (LE) | TX version number |\n/// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |\n/// | varies | tx_in | txIn[] | TX inputs |\n/// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |\n/// | varies | tx_out | txOut[] | TX outputs |\n/// | 4 | lock_time | uint32_t (LE) | Unix time or block number |\n///\n//\n/// Non-coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 36 | previous_output | outpoint | The previous outpoint being spent |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |\n/// | varies | signature_script | char[] | The signature script, empty for P2WSH |\n/// | 4 | sequence | uint32_t (LE) | Sequence number |\n///\n///\n/// The reference to transaction being spent (outpoint):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |-------|-------|---------------|------------------------------------------|\n/// | 32 | hash | char[32] | Hash of the transaction to spend |\n/// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |\n///\n///\n/// Transaction output (txOut):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|-----------------|-----------------------|--------------------------------------|\n/// | 8 | value | int64_t (LE) | Number of satoshis to spend |\n/// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |\n/// | varies | pk_script | char[] | Pubkey script |\n///\n/// compactSize uint format:\n///\n/// | Value | Bytes | Format |\n/// |-----------------------------------------|-------|----------------------------------------------|\n/// | >= 0 && <= 252 | 1 | uint8_t |\n/// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |\n/// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |\n/// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |\n///\n/// (*) compactSize uint is often references as VarInt)\n///\n/// Coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |\n/// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |\n/// | varies | height | char[] | The block height of this block (BIP34) (*) |\n/// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |\n/// | 4 | sequence | uint32_t (LE) | Sequence number\n///\n/// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to\n/// the stack followed by the block height as a little-endian unsigned integer. This script must be as\n/// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total\n/// size four bytes until block 16,777,216 about 300 years from now.\nlibrary BitcoinTx {\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using ValidateSPV for bytes;\n using ValidateSPV for bytes32;\n\n /// @notice Represents Bitcoin transaction data.\n struct Info {\n /// @notice Bitcoin transaction version.\n /// @dev `version` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes signed integer, little endian.\n bytes4 version;\n /// @notice All Bitcoin transaction inputs, prepended by the number of\n /// transaction inputs.\n /// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.\n ///\n /// The number of transaction inputs encoded as compactSize\n /// unsigned integer, little-endian.\n ///\n /// Note that some popular block explorers reverse the order of\n /// bytes from `outpoint`'s `hash` and display it as big-endian.\n /// Solidity code of Bridge expects hashes in little-endian, just\n /// like they are represented in a raw Bitcoin transaction.\n bytes inputVector;\n /// @notice All Bitcoin transaction outputs prepended by the number of\n /// transaction outputs.\n /// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.\n ///\n /// The number of transaction outputs encoded as a compactSize\n /// unsigned integer, little-endian.\n bytes outputVector;\n /// @notice Bitcoin transaction locktime.\n ///\n /// @dev `lock_time` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes unsigned integer, little endian.\n bytes4 locktime;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents data needed to perform a Bitcoin SPV proof.\n struct Proof {\n /// @notice The merkle proof of transaction inclusion in a block.\n bytes merkleProof;\n /// @notice Transaction index in the block (0-indexed).\n uint256 txIndexInBlock;\n /// @notice Single byte-string of 80-byte bitcoin headers,\n /// lowest height first.\n bytes bitcoinHeaders;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents info about an unspent transaction output.\n struct UTXO {\n /// @notice Hash of the transaction the output belongs to.\n /// @dev Byte order corresponds to the Bitcoin internal byte order.\n bytes32 txHash;\n /// @notice Index of the transaction output (0-indexed).\n uint32 txOutputIndex;\n /// @notice Value of the transaction output.\n uint64 txOutputValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents Bitcoin signature in the R/S/V format.\n struct RSVSignature {\n /// @notice Signature r value.\n bytes32 r;\n /// @notice Signature s value.\n bytes32 s;\n /// @notice Signature recovery value.\n uint8 v;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Validates the SPV proof of the Bitcoin transaction.\n /// Reverts in case the validation or proof verification fail.\n /// @param txInfo Bitcoin transaction data.\n /// @param proof Bitcoin proof data.\n /// @return txHash Proven 32-byte transaction hash.\n function validateProof(\n BridgeState.Storage storage self,\n Info calldata txInfo,\n Proof calldata proof\n ) internal view returns (bytes32 txHash) {\n require(\n txInfo.inputVector.validateVin(),\n \"Invalid input vector provided\"\n );\n require(\n txInfo.outputVector.validateVout(),\n \"Invalid output vector provided\"\n );\n\n txHash = abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n\n require(\n txHash.prove(\n proof.bitcoinHeaders.extractMerkleRootLE(),\n proof.merkleProof,\n proof.txIndexInBlock\n ),\n \"Tx merkle proof is not valid for provided header and tx hash\"\n );\n\n evaluateProofDifficulty(self, proof.bitcoinHeaders);\n\n return txHash;\n }\n\n /// @notice Evaluates the given Bitcoin proof difficulty against the actual\n /// Bitcoin chain difficulty provided by the relay oracle.\n /// Reverts in case the evaluation fails.\n /// @param bitcoinHeaders Bitcoin headers chain being part of the SPV\n /// proof. Used to extract the observed proof difficulty.\n function evaluateProofDifficulty(\n BridgeState.Storage storage self,\n bytes memory bitcoinHeaders\n ) internal view {\n IRelay relay = self.relay;\n uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();\n uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();\n\n uint256 requestedDiff = 0;\n uint256 firstHeaderDiff = bitcoinHeaders\n .extractTarget()\n .calculateDifficulty();\n\n if (firstHeaderDiff == currentEpochDifficulty) {\n requestedDiff = currentEpochDifficulty;\n } else if (firstHeaderDiff == previousEpochDifficulty) {\n requestedDiff = previousEpochDifficulty;\n } else {\n revert(\"Not at current or previous difficulty\");\n }\n\n uint256 observedDiff = bitcoinHeaders.validateHeaderChain();\n\n require(\n observedDiff != ValidateSPV.getErrBadLength(),\n \"Invalid length of the headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrInvalidChain(),\n \"Invalid headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrLowWork(),\n \"Insufficient work in a header\"\n );\n\n require(\n observedDiff >= requestedDiff * self.txProofDifficultyFactor,\n \"Insufficient accumulated difficulty in header chain\"\n );\n }\n\n /// @notice Extracts public key hash from the provided P2PKH or P2WPKH output.\n /// Reverts if the validation fails.\n /// @param output The transaction output.\n /// @return pubKeyHash 20-byte public key hash the output locks funds on.\n /// @dev Requirements:\n /// - The output must be of P2PKH or P2WPKH type and lock the funds\n /// on a 20-byte public key hash.\n function extractPubKeyHash(BridgeState.Storage storage, bytes memory output)\n internal\n pure\n returns (bytes20 pubKeyHash)\n {\n bytes memory pubKeyHashBytes = output.extractHash();\n\n require(\n pubKeyHashBytes.length == 20,\n \"Output's public key hash must have 20 bytes\"\n );\n\n pubKeyHash = pubKeyHashBytes.slice20(0);\n\n // We need to make sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 P2PKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"1976a914\", pubKeyHash, hex\"88ac\")\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 P2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", pubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == P2PKHScriptKeccak ||\n outputScriptKeccak == P2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n return pubKeyHash;\n }\n}\n"
|
|
@@ -167,7 +167,7 @@
|
|
|
167
167
|
"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.ecdsaWalletRegistry.seize(\n self.fraudSlashingAmount,\n self.fraudNotifierRewardMultiplier,\n challenge.challenger,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n self.terminateWallet(walletPubKeyHash);\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"
|
|
168
168
|
},
|
|
169
169
|
"contracts/bridge/MovingFunds.sol": {
|
|
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 {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 \"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 \"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.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n self.terminateWallet(walletPubKeyHash);\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 \"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 \"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.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n self.terminateWallet(walletPubKeyHash);\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
|
|
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 {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 \"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 // Assert that main UTXO for passed wallet exists in storage.\n bytes32 mainUtxoHash = self\n .registeredWallets[walletPubKeyHash]\n .mainUtxoHash;\n require(mainUtxoHash != bytes32(0), \"No main UTXO for given wallet\");\n\n // Assert that passed main UTXO parameter is the same as in storage and\n // can be used for further processing.\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // 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 );\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 \"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.ecdsaWalletRegistry.seize(\n self.movingFundsTimeoutSlashingAmount,\n self.movingFundsTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n self.terminateWallet(walletPubKeyHash);\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 \"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 // Wallet state validation is performed in the\n // `resolveMovedFundsSweepingWallet` function.\n\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 \"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.ecdsaWalletRegistry.seize(\n self.movedFundsSweepTimeoutSlashingAmount,\n self.movedFundsSweepTimeoutNotifierRewardMultiplier,\n msg.sender,\n wallet.ecdsaWalletID,\n walletMembersIDs\n );\n\n self.terminateWallet(walletPubKeyHash);\n }\n\n // slither-disable-next-line reentrancy-events\n emit MovedFundsSweepTimedOut(\n walletPubKeyHash,\n movingFundsTxHash,\n movingFundsTxOutputIndex\n );\n }\n}\n"
|
|
171
171
|
},
|
|
172
172
|
"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol": {
|
|
173
173
|
"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\nimport \"../libraries/EcdsaDkg.sol\";\n\ninterface IWalletRegistry {\n /// @notice Requests a new wallet creation.\n /// @dev Only the Wallet Owner can call this function.\n function requestNewWallet() external;\n\n /// @notice Closes an existing wallet.\n /// @param walletID ID of the wallet.\n /// @dev Only the Wallet Owner can call this function.\n function closeWallet(bytes32 walletID) external;\n\n /// @notice Adds all signing group members of the wallet with the given ID\n /// to the slashing queue of the staking contract. The notifier will\n /// receive reward per each group member from the staking contract\n /// notifiers treasury. The reward is scaled by the\n /// `rewardMultiplier` provided as a parameter.\n /// @param amount Amount of tokens to seize from each signing group member\n /// @param rewardMultiplier Fraction of the staking contract notifiers\n /// reward the notifier should receive; should be between [0, 100]\n /// @param notifier Address of the misbehavior notifier\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @dev Only the Wallet Owner can call this function.\n /// Requirements:\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - `rewardMultiplier` must be between [0, 100].\n /// - This function does revert if staking contract call reverts.\n /// The calling code needs to handle the potential revert.\n function seize(\n uint96 amount,\n uint256 rewardMultiplier,\n address notifier,\n bytes32 walletID,\n uint32[] calldata walletMembersIDs\n ) external;\n\n /// @notice Gets public key of a wallet with a given wallet ID.\n /// The public key is returned in an uncompressed format as a 64-byte\n /// concatenation of X and Y coordinates.\n /// @param walletID ID of the wallet.\n /// @return Uncompressed public key of the wallet.\n function getWalletPublicKey(bytes32 walletID)\n external\n view\n returns (bytes memory);\n\n /// @notice Check current wallet creation state.\n function getWalletCreationState() external view returns (EcdsaDkg.State);\n\n /// @notice Checks whether the given operator is a member of the given\n /// wallet signing group.\n /// @param walletID ID of the wallet\n /// @param walletMembersIDs Identifiers of the wallet signing group members\n /// @param operator Address of the checked operator\n /// @param walletMemberIndex Position of the operator in the wallet signing\n /// group members list\n /// @return True - if the operator is a member of the given wallet signing\n /// group. False - otherwise.\n /// @dev Requirements:\n /// - The `operator` parameter must be an actual sortition pool operator.\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events.\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]\n function isWalletMember(\n bytes32 walletID,\n uint32[] calldata walletMembersIDs,\n address operator,\n uint256 walletMemberIndex\n ) external view returns (bool);\n}\n"
|