@keep-network/tbtc-v2 0.1.1-dev.34 → 0.1.1-dev.35
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/TBTC.json +3 -3
- package/artifacts/TBTCToken.json +3 -3
- package/artifacts/VendingMachine.json +10 -10
- package/artifacts/solcInputs/{a67a2c11233ce411fb55a9f369ced323.json → 922339b8aca537314dc3d35162317588.json} +12 -6
- package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
- package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
- package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
- package/build/contracts/bridge/Bridge.sol/Bridge.json +89 -113
- 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/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
- package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +1 -1
- package/build/contracts/bridge/Frauds.sol/Frauds.json +2 -2
- package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
- package/build/contracts/bridge/{Bridge.sol → IRelay.sol}/IRelay.json +1 -1
- package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
- package/build/contracts/bridge/Sweep.sol/Sweep.json +48 -0
- 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/token/TBTC.sol/TBTC.dbg.json +1 -1
- package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
- package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
- package/contracts/bridge/Bridge.sol +57 -506
- package/contracts/bridge/BridgeState.sol +50 -0
- package/contracts/bridge/IRelay.sol +28 -0
- package/contracts/bridge/Sweep.sol +510 -0
- package/package.json +1 -1
- package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +0 -4
|
@@ -140,23 +140,29 @@
|
|
|
140
140
|
"content": "pragma solidity ^0.8.4;\n\n/** @title ValidateSPV*/\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {SafeMath} from \"./SafeMath.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary ValidateSPV {\n\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using SafeMath for uint256;\n\n enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS }\n enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD }\n\n uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;\n uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe;\n uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd;\n\n function getErrBadLength() internal pure returns (uint256) {\n return ERR_BAD_LENGTH;\n }\n\n function getErrInvalidChain() internal pure returns (uint256) {\n return ERR_INVALID_CHAIN;\n }\n\n function getErrLowWork() internal pure returns (uint256) {\n return ERR_LOW_WORK;\n }\n\n /// @notice Validates a tx inclusion in the block\n /// @dev `index` is not a reliable indicator of location within a block\n /// @param _txid The txid (LE)\n /// @param _merkleRoot The merkle root (as in the block header)\n /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root)\n /// @param _index The leaf's index in the tree (0-indexed)\n /// @return true if fully valid, false otherwise\n function prove(\n bytes32 _txid,\n bytes32 _merkleRoot,\n bytes memory _intermediateNodes,\n uint _index\n ) internal view returns (bool) {\n // Shortcut the empty-block case\n if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) {\n return true;\n }\n\n // If the Merkle proof failed, bubble up error\n return BTCUtils.verifyHash256Merkle(\n _txid,\n _intermediateNodes,\n _merkleRoot,\n _index\n );\n }\n\n /// @notice Hashes transaction to get txid\n /// @dev Supports Legacy and Witness\n /// @param _version 4-bytes version\n /// @param _vin Raw bytes length-prefixed input vector\n /// @param _vout Raw bytes length-prefixed output vector\n /// @param _locktime 4-byte tx locktime\n /// @return 32-byte transaction id, little endian\n function calculateTxId(\n bytes4 _version,\n bytes memory _vin,\n bytes memory _vout,\n bytes4 _locktime\n ) internal view returns (bytes32) {\n // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime)\n return abi.encodePacked(_version, _vin, _vout, _locktime).hash256View();\n }\n\n /// @notice Checks validity of header chain\n /// @notice Compares the hash of each header to the prevHash in the next header\n /// @param _headers Raw byte array of header chain\n /// @return _totalDifficulty The total accumulated difficulty of the header chain, or an error code\n function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) {\n\n // Check header chain length\n if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;}\n\n // Initialize header start index\n bytes32 _digest;\n\n _totalDifficulty = 0;\n\n bytes memory _header;\n\n // Allocate _header with extra space after it to fit 3 full words\n assembly {\n _header := mload(0x40)\n mstore(0x40, add(_header, add(32, 96)))\n mstore(_header, 80)\n }\n\n for (uint256 _start = 0; _start < _headers.length; _start += 80) {\n\n // ith header start index and ith header\n _headers.sliceInPlace(_header, _start);\n\n // After the first header, check that headers are in a chain\n if (_start != 0) {\n if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;}\n }\n\n // ith header target\n uint256 _target = _header.extractTarget();\n\n // Require that the header has sufficient work\n _digest = _header.hash256View();\n if(uint256(_digest).reverseUint256() > _target) {\n return ERR_LOW_WORK;\n }\n\n // Add ith header difficulty to difficulty sum\n _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty());\n }\n }\n\n /// @notice Checks validity of header work\n /// @param _digest Header digest\n /// @param _target The target threshold\n /// @return true if header work is valid, false otherwise\n function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) {\n if (_digest == bytes32(0)) {return false;}\n return (uint256(_digest).reverseUint256() < _target);\n }\n\n /// @notice Checks validity of header chain\n /// @dev Compares current header prevHash to previous header's digest\n /// @param _header The raw bytes header\n /// @param _prevHeaderDigest The previous header's digest\n /// @return true if the connect is valid, false otherwise\n function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) {\n\n // Extract prevHash of current header\n bytes32 _prevHash = _header.extractPrevBlockLE();\n\n // Compare prevHash of current header to previous header's digest\n if (_prevHash != _prevHeaderDigest) {return false;}\n\n return true;\n }\n}\n"
|
|
141
141
|
},
|
|
142
142
|
"contracts/test/BridgeStub.sol": {
|
|
143
|
-
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/Wallets.sol\";\n\n// TODO: Try to create a separate BridgeStub for every test group (wallets,\n// frauds, etc.) to decrease the size.\ncontract BridgeStub is Bridge {\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _walletRegistry,\n uint256 _txProofDifficultyFactor\n )\n Bridge(\n _bank,\n _relay,\n _treasury,\n _walletRegistry,\n _txProofDifficultyFactor\n )\n {}\n\n function setSweptDeposits(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.deposits[utxoKey].sweptAt = 1641650400;\n }\n }\n\n function setSpentMainUtxos(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n spentMainUTXOs[utxoKey] = true;\n }\n }\n\n function setActiveWallet(bytes20 activeWalletPubKeyHash) external {\n wallets.activeWalletPubKeyHash = activeWalletPubKeyHash;\n }\n\n function setWalletMainUtxo(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n wallets.registeredWallets[walletPubKeyHash].mainUtxoHash = keccak256(\n abi.encodePacked(\n utxo.txHash,\n utxo.txOutputIndex,\n utxo.txOutputValue\n )\n );\n }\n\n function unsetWalletMainUtxo(bytes20 walletPubKeyHash) external {\n delete wallets.registeredWallets[walletPubKeyHash].mainUtxoHash;\n }\n\n function setWallet(bytes20 walletPubKeyHash, Wallets.Wallet calldata wallet)\n external\n {\n wallets.registeredWallets[walletPubKeyHash] = wallet;\n }\n\n function setDepositDustThreshold(uint64 _depositDustThreshold) external {\n self.depositDustThreshold = _depositDustThreshold;\n }\n\n function setDepositTxMaxFee(uint64 _depositTxMaxFee) external {\n depositTxMaxFee = _depositTxMaxFee;\n }\n\n function setRedemptionDustThreshold(uint64 _redemptionDustThreshold)\n external\n {\n redemptionDustThreshold = _redemptionDustThreshold;\n }\n\n function setRedemptionTreasuryFeeDivisor(\n uint64 _redemptionTreasuryFeeDivisor\n ) external {\n redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n }\n\n function setMovingFundsTxMaxTotalFee(uint64 _movingFundsTxMaxTotalFee)\n external\n {\n movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n }\n}\n"
|
|
143
|
+
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.9;\n\nimport \"../bridge/BitcoinTx.sol\";\nimport \"../bridge/Bridge.sol\";\nimport \"../bridge/Wallets.sol\";\n\n// TODO: Try to create a separate BridgeStub for every test group (wallets,\n// frauds, etc.) to decrease the size.\ncontract BridgeStub is Bridge {\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _walletRegistry,\n uint256 _txProofDifficultyFactor\n )\n Bridge(\n _bank,\n _relay,\n _treasury,\n _walletRegistry,\n _txProofDifficultyFactor\n )\n {}\n\n function setSweptDeposits(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.deposits[utxoKey].sweptAt = 1641650400;\n }\n }\n\n function setSpentMainUtxos(BitcoinTx.UTXO[] calldata utxos) external {\n for (uint256 i = 0; i < utxos.length; i++) {\n uint256 utxoKey = uint256(\n keccak256(\n abi.encodePacked(utxos[i].txHash, utxos[i].txOutputIndex)\n )\n );\n self.spentMainUTXOs[utxoKey] = true;\n }\n }\n\n function setActiveWallet(bytes20 activeWalletPubKeyHash) external {\n wallets.activeWalletPubKeyHash = activeWalletPubKeyHash;\n }\n\n function setWalletMainUtxo(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata utxo\n ) external {\n wallets.registeredWallets[walletPubKeyHash].mainUtxoHash = keccak256(\n abi.encodePacked(\n utxo.txHash,\n utxo.txOutputIndex,\n utxo.txOutputValue\n )\n );\n }\n\n function unsetWalletMainUtxo(bytes20 walletPubKeyHash) external {\n delete wallets.registeredWallets[walletPubKeyHash].mainUtxoHash;\n }\n\n function setWallet(bytes20 walletPubKeyHash, Wallets.Wallet calldata wallet)\n external\n {\n wallets.registeredWallets[walletPubKeyHash] = wallet;\n }\n\n function setDepositDustThreshold(uint64 _depositDustThreshold) external {\n self.depositDustThreshold = _depositDustThreshold;\n }\n\n function setDepositTxMaxFee(uint64 _depositTxMaxFee) external {\n self.depositTxMaxFee = _depositTxMaxFee;\n }\n\n function setRedemptionDustThreshold(uint64 _redemptionDustThreshold)\n external\n {\n redemptionDustThreshold = _redemptionDustThreshold;\n }\n\n function setRedemptionTreasuryFeeDivisor(\n uint64 _redemptionTreasuryFeeDivisor\n ) external {\n redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n }\n\n function setMovingFundsTxMaxTotalFee(uint64 _movingFundsTxMaxTotalFee)\n external\n {\n movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n }\n}\n"
|
|
144
144
|
},
|
|
145
145
|
"contracts/bridge/Bridge.sol": {
|
|
146
|
-
"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 \"@openzeppelin/contracts/access/Ownable.sol\";\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"../bank/Bank.sol\";\nimport \"./BridgeState.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Frauds.sol\";\n\n/// @title Interface for the Bitcoin relay\n/// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay\n/// provides the difficulty of the previous and current epoch. One\n/// difficulty epoch spans 2016 blocks.\ninterface IRelay {\n /// @notice Returns the difficulty of the current epoch.\n function getCurrentEpochDifficulty() external view returns (uint256);\n\n /// @notice Returns the difficulty of the previous epoch.\n function getPrevEpochDifficulty() external view returns (uint256);\n}\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank.\n///\n/// TODO: All wallets-related operations that are currently done directly\n/// by the Bridge can be probably delegated to the Wallets library.\n/// Examples of such operations are main UTXO or pending redemptions\n/// value updates.\ncontract Bridge is Ownable, EcdsaWalletOwner {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using Frauds for Frauds.Data;\n using Wallets for Wallets.Data;\n\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n\n /// @notice Represents an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct SweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n }\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n }\n\n /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n uint256 public txProofDifficultyFactor;\n\n /// TODO: Revisit whether it should be governable or not.\n /// @notice Address of the Bank this Bridge belongs to.\n Bank public bank;\n\n /// TODO: Make it governable.\n /// @notice Handle to the Bitcoin relay.\n IRelay public relay;\n\n /// TODO: Revisit whether it should be governable or not.\n /// @notice Address where the redemptions treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n address public treasury;\n\n BridgeState.Storage internal self;\n\n /// TODO: Make it governable.\n /// @notice Maximum amount of BTC transaction fee that can be incurred by\n /// each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev This is a per-deposit input max fee for the sweep transaction.\n uint64 public depositTxMaxFee;\n\n /// TODO: Make it governable.\n /// @notice The minimal amount that can be requested for redemption.\n /// Value of this parameter must take into account the value of\n /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n uint64 public redemptionDustThreshold;\n\n /// TODO: Make it governable.\n /// @notice Divisor used to compute the treasury fee taken from each\n /// redemption request and transferred to the treasury upon\n /// successful request finalization. That fee is computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 public redemptionTreasuryFeeDivisor;\n\n /// TODO: Make it governable.\n /// @notice Maximum amount of BTC transaction fee that can be incurred by\n /// each redemption request being part of the given redemption\n /// transaction. If the maximum BTC transaction fee is exceeded, such\n /// transaction is considered a fraud.\n /// @dev This is a per-redemption output max fee for the redemption transaction.\n uint64 public redemptionTxMaxFee;\n\n /// TODO: Make it governable.\n /// @notice Time after which the redemption request can be reported as\n /// timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported\n /// timed out requests are cancelled and locked TBTC is returned\n /// to the redeemer in full amount.\n uint256 public redemptionTimeout;\n\n /// TODO: Make it governable.\n /// @notice Maximum amount of the total BTC transaction fee that is\n /// acceptable in a single moving funds transaction.\n /// @dev This is a TOTAL max fee for the moving funds transaction. Note that\n /// `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n /// if per single redemption. `movingFundsTxMaxTotalFee` is a total fee\n /// for the entire transaction.\n uint64 public movingFundsTxMaxTotalFee;\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n mapping(uint256 => bool) public spentMainUTXOs;\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out\n mapping(uint256 => RedemptionRequest) public pendingRedemptions;\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n mapping(uint256 => RedemptionRequest) public timedOutRedemptions;\n\n /// @notice Contains parameters related to frauds and the collection of all\n /// submitted fraud challenges.\n Frauds.Data internal frauds;\n\n /// @notice State related with wallets.\n Wallets.Data internal wallets;\n\n event WalletCreationPeriodUpdated(uint32 newCreationPeriod);\n\n event WalletBtcBalanceRangeUpdated(\n uint64 newMinBtcBalance,\n uint64 newMaxBtcBalance\n );\n\n event WalletMaxAgeUpdated(uint32 newMaxAge);\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdated(\n uint256 newFraudNotifierRewardMultiplier\n );\n\n event FraudChallengeDefeatTimeoutUpdated(\n uint256 newFraudChallengeDefeatTimeout\n );\n\n event FraudChallengeDepositAmountUpdated(\n uint256 newFraudChallengeDepositAmount\n );\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript,\n address redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPublicKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPublicKeyHash,\n bytes32 sighash\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) {\n require(_bank != address(0), \"Bank address cannot be zero\");\n bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n relay = IRelay(_relay);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n treasury = _treasury;\n\n txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n redemptionTxMaxFee = 10000; // 10000 satoshi\n redemptionTimeout = 172800; // 48 hours\n movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n\n // TODO: Revisit initial values.\n frauds.setSlashingAmount(10000 * 1e18); // 10000 T\n frauds.setNotifierRewardMultiplier(100); // 100%\n frauds.setChallengeDefeatTimeout(7 days);\n frauds.setChallengeDepositAmount(2 ether);\n\n // TODO: Revisit initial values.\n wallets.init(_ecdsaWalletRegistry);\n wallets.setCreationPeriod(1 weeks);\n wallets.setBtcBalanceRange(1 * 1e8, 10 * 1e8); // [1 BTC, 10 BTC]\n wallets.setMaxAge(26 weeks); // ~6 months\n }\n\n /// @notice Updates parameters used by the `Wallets` library.\n /// @param creationPeriod New value of the wallet creation period\n /// @param minBtcBalance New value of the minimum BTC balance\n /// @param maxBtcBalance New value of the maximum BTC balance\n /// @param maxAge New value of the wallet maximum age\n /// @dev Requirements:\n /// - Caller must be the contract owner.\n /// - Minimum BTC balance must be greater than zero\n /// - Maximum BTC balance must be greater than minimum BTC balance\n function updateWalletsParameters(\n uint32 creationPeriod,\n uint64 minBtcBalance,\n uint64 maxBtcBalance,\n uint32 maxAge\n ) external onlyOwner {\n wallets.setCreationPeriod(creationPeriod);\n wallets.setBtcBalanceRange(minBtcBalance, maxBtcBalance);\n wallets.setMaxAge(maxAge);\n }\n\n /// @return creationPeriod Value of the wallet creation period\n /// @return minBtcBalance Value of the minimum BTC balance\n /// @return maxBtcBalance Value of the maximum BTC balance\n /// @return maxAge Value of the wallet max age\n function getWalletsParameters()\n external\n view\n returns (\n uint32 creationPeriod,\n uint64 minBtcBalance,\n uint64 maxBtcBalance,\n uint32 maxAge\n )\n {\n creationPeriod = wallets.creationPeriod;\n minBtcBalance = wallets.minBtcBalance;\n maxBtcBalance = wallets.maxBtcBalance;\n maxAge = wallets.maxAge;\n\n return (creationPeriod, minBtcBalance, maxBtcBalance, maxAge);\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost.\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault\n /// @param isTrusted flag indicating whether the vault is trusted or not\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted) external onlyOwner {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored.\n /// - Wallet creation must not be in progress\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time\n /// - The active wallet BTC balance is above the maximum threshold\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n wallets.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Given wallet data must not belong to an already registered wallet\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n wallets.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate\n /// @param publicKeyY Wallet's public key's Y coordinate\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Wallet must be in Live state\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n wallets.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshis left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero.\n /// - Wallet must be in Live state\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n wallets.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @return Wallet details.\n function getWallet(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return wallets.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function getActiveWalletPubKeyHash() external view returns (bytes20) {\n return wallets.activeWalletPubKeyHash;\n }\n\n /// @notice Determines the current Bitcoin SPV proof difficulty context.\n /// @return proofDifficulty Bitcoin proof difficulty context.\n function proofDifficultyContext()\n internal\n view\n returns (BitcoinTx.ProofDifficulty memory proofDifficulty)\n {\n proofDifficulty.currentEpochDifficulty = relay\n .getCurrentEpochDifficulty();\n proofDifficulty.previousEpochDifficulty = relay\n .getPrevEpochDifficulty();\n proofDifficulty.difficultyFactor = txProofDifficultyFactor;\n\n return proofDifficulty;\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`\n /// @param reveal Deposit reveal data, see `RevealInfo struct\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet\n /// - `reveal.vault` must be 0x0 or point to a trusted vault\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.RevealInfo calldata reveal\n ) external {\n self.revealDeposit(wallets, fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n // TODO: Fail early if the function call gets frontrunned. See discussion:\n // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204\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 = BitcoinTx.validateProof(\n sweepTx,\n sweepProof,\n proofDifficultyContext()\n );\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processSweepTxOutput(sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveSweepingWallet(walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(\n sweepTx.inputVector,\n resolvedMainUtxo\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = sweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n // Update depositors balances in the Bank.\n bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n // Pass the treasury fee to the treasury address.\n bank.increaseBalance(treasury, totalTreasuryFee);\n\n // TODO: Handle deposits having `vault` set.\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state.\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveSweepingWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = wallets.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processSweepTxOutput(bytes memory sweepTxOutputVector)\n internal\n pure\n returns (bytes20 walletPubKeyHash, uint64 value)\n {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n value = output.extractValue();\n bytes memory walletPubKeyHashBytes = output.extractHash();\n // The sweep transaction output should always be P2PKH or P2WPKH.\n // In both cases, the wallet public key hash should be 20 bytes length.\n require(\n walletPubKeyHashBytes.length == 20,\n \"Wallet public key hash should have 20 bytes\"\n );\n /* solhint-disable-next-line no-inline-assembly */\n assembly {\n walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))\n }\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @param sweepTxInputVector Bitcoin sweep transaction input vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before\n /// it is passed here\n /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO\n /// exists for the given the wallet, this parameter's fields should\n /// be zeroed to bypass the main UTXO validation\n /// @return info Outcomes of the processing.\n function processSweepTxInputs(\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo\n ) internal returns (SweepTxInputsInfo memory info) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (\n uint256 inputsCompactSizeUintLength,\n uint256 inputsCount\n ) = sweepTxInputVector.parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n info.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n info.depositedAmounts = new uint256[](info.depositors.length);\n info.treasuryFees = new uint256[](info.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);\n\n Deposit.Request storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n if (processedDepositsCount == info.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n info.depositors[processedDepositsCount] = deposit.depositor;\n info.depositedAmounts[processedDepositsCount] = deposit.amount;\n info.inputsTotalValue += info.depositedAmounts[\n processedDepositsCount\n ];\n info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n mainUtxo.txHash == outpointTxHash\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n info.inputsTotalValue += mainUtxo.txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return info;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector\n /// @param inputStartingIndex Index the given input starts at\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function sweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n ///@param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPubKey` must be in `Live` or `MovingFunds`\n /// state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n 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 = wallets.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Wallet is neither in Live nor MovingFunds state\"\n );\n\n frauds.submitChallenge(\n walletPublicKey,\n walletPubKeyHash,\n sighash,\n signature\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 bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n uint256 utxoKey = frauds.unwrapChallenge(\n walletPublicKey,\n preimage,\n witness\n );\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 || spentMainUTXOs[utxoKey],\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n frauds.defeatChallenge(walletPublicKey, preimage, treasury);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - `walletPublicKey`and `sighash` must identify an open fraud\n /// challenge\n /// - the amount of time indicated by `challengeDefeatTimeout` must\n /// pass after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n frauds.notifyChallengeDefeatTimeout(walletPublicKey, sighash);\n }\n\n /// @notice Returns parameters used by the `Frauds` library.\n /// @return slashingAmount Value of the slashing amount\n /// @return notifierRewardMultiplier Value of the notifier reward multiplier\n /// @return challengeDefeatTimeout Value of the challenge defeat timeout\n /// @return challengeDepositAmount Value of the challenge deposit amount\n function getFraudParameters()\n external\n view\n returns (\n uint256 slashingAmount,\n uint256 notifierRewardMultiplier,\n uint256 challengeDefeatTimeout,\n uint256 challengeDepositAmount\n )\n {\n slashingAmount = frauds.slashingAmount;\n notifierRewardMultiplier = frauds.notifierRewardMultiplier;\n challengeDefeatTimeout = frauds.challengeDefeatTimeout;\n challengeDepositAmount = frauds.challengeDepositAmount;\n\n return (\n slashingAmount,\n notifierRewardMultiplier,\n challengeDefeatTimeout,\n challengeDepositAmount\n );\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Frauds.FraudChallenge memory)\n {\n return frauds.challenges[challengeKey];\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// - `redeemerOutputScript` must be a proper Bitcoin script\n /// - `redeemerOutputScript` cannot have wallet PKH as payload\n /// - `amount` must be above or equal the `redemptionDustThreshold`\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time\n /// - Wallet must have enough Bitcoin balance to proceed the request\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n Wallets.Wallet storage wallet = wallets.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // TODO: Confirm if `walletPubKeyHash` should be validated by checking\n // if it is the oldest one who can handle the request. This will\n // be suggested by the dApp but may not be respected by users who\n // interact directly with the contract. Do we need to enforce it\n // here? One option is not to enforce it, to save on gas, but if\n // we see this rule is not respected, upgrade Bridge contract to\n // require it.\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= 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 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 = redemptionTreasuryFeeDivisor > 0\n ? amount / redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = 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 pendingRedemptions[redemptionKey] = RedemptionRequest(\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n bank.transferBalanceFrom(msg.sender, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data\n /// @param redemptionProof Bitcoin redemption proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance.\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // TODO: Just as for `submitSweepProof`, fail early if the function\n // call gets frontrunned. See discussion:\n // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204\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 = BitcoinTx.validateProof(\n redemptionTx,\n redemptionProof,\n proofDifficultyContext()\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n processWalletOutboundTxInput(\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = wallets.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 MovingFuds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\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 bank.decreaseBalance(outputsInfo.totalBurnableValue);\n bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);\n }\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 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 = wallets\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 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 /// @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 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 // Helper variable that counts the number of processed redemption\n // outputs. Redemptions can be either pending or reported as timed out.\n // TODO: Revisit the approach with redemptions count according to\n // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765\n uint256 processedRedemptionsCount = 0;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n 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 info.changeValue == 0 &&\n (keccak256(outputScript) == walletP2PKHScriptKeccak ||\n keccak256(outputScript) == 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 info.changeIndex = uint32(i);\n info.changeValue = outputValue;\n } else {\n // If we entered here, that the means 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 (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 = 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 info.totalBurnableValue += redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n info.totalTreasuryFee += 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 pendingRedemptions[redemptionKey];\n\n processedRedemptionsCount++;\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 = 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 processedRedemptionsCount++;\n }\n }\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 // 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 processedRedemptionsCount > 0,\n \"Redemption transaction must process at least one redemption\"\n );\n\n return info;\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n RedemptionRequest memory request = pendingRedemptions[redemptionKey];\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 + 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 = wallets.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n // TODO: Allow the wallets in `Closing` state when the state is added\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"The wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n timedOutRedemptions[redemptionKey] = request;\n delete pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Propagate timeout consequences to the wallet\n wallets.notifyRedemptionTimedOut(walletPubKeyHash);\n }\n\n emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);\n\n // Return the requested amount of tokens to the redeemer\n bank.transferBalance(request.redeemer, request.requestedAmount);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // 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 = BitcoinTx.validateProof(\n movingFundsTx,\n movingFundsProof,\n proofDifficultyContext()\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n processWalletOutboundTxInput(\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n wallets.notifyFundsMoved(walletPubKeyHash, targetWalletsHash);\n\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc.\n /// - Each output must refer to a 20-byte public key hash.\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)\n internal\n view\n returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)\n {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n uint256 outputLength = movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n // Extract the output script payload.\n bytes memory targetWalletPubKeyHashBytes = output.extractHash();\n // Output script payload must refer to a known wallet public key\n // hash which is always 20-byte.\n require(\n targetWalletPubKeyHashBytes.length == 20,\n \"Target wallet public key hash must have 20 bytes\"\n );\n\n bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes\n .slice20(0);\n\n // The next step is making sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 targetWalletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(\n hex\"1976a914\",\n targetWalletPubKeyHash,\n hex\"88ac\"\n )\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 targetWalletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", targetWalletPubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == targetWalletP2PKHScriptKeccak ||\n outputScriptKeccak == targetWalletP2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[i] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[i] = output.extractValue();\n outputsTotalValue += outputsValues[i];\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n function depositParameters()\n external\n view\n returns (uint64 depositDustThreshold, uint64 depositTreasuryFeeDivisor)\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.Request memory)\n {\n // TODO: rename to getDeposit?\n return self.deposits[depositKey];\n }\n}\n"
|
|
146
|
+
"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 \"@openzeppelin/contracts/access/Ownable.sol\";\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 {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./Sweep.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Frauds.sol\";\n\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank.\n///\n/// TODO: All wallets-related operations that are currently done directly\n/// by the Bridge can be probably delegated to the Wallets library.\n/// Examples of such operations are main UTXO or pending redemptions\n/// value updates.\ncontract Bridge is Ownable, EcdsaWalletOwner {\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using Sweep for BridgeState.Storage;\n using Frauds for Frauds.Data;\n using Wallets for Wallets.Data;\n\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n\n /// @notice Represents a redemption request.\n struct RedemptionRequest {\n // ETH address of the redeemer who created the request.\n address redeemer;\n // Requested TBTC amount in satoshi.\n uint64 requestedAmount;\n // Treasury TBTC fee in satoshi at the moment of request creation.\n uint64 treasuryFee;\n // Transaction maximum BTC fee in satoshi at the moment of request\n // creation.\n uint64 txMaxFee;\n // UNIX timestamp the request was created at.\n uint32 requestedAt;\n }\n\n /// @notice Represents an outcome of the redemption Bitcoin transaction\n /// outputs processing.\n struct RedemptionTxOutputsInfo {\n // Total TBTC value in satoshi that should be burned by the Bridge.\n // It includes the total amount of all BTC redeemed in the transaction\n // and the fee paid to BTC miners for the redemption transaction.\n uint64 totalBurnableValue;\n // Total TBTC value in satoshi that should be transferred to\n // the treasury. It is a sum of all treasury fees paid by all\n // redeemers included in the redemption transaction.\n uint64 totalTreasuryFee;\n // Index of the change output. The change output becomes\n // the new main wallet's UTXO.\n uint32 changeIndex;\n // Value in satoshi of the change output.\n uint64 changeValue;\n }\n\n BridgeState.Storage internal self;\n\n /// TODO: Make it governable.\n /// @notice The minimal amount that can be requested for redemption.\n /// Value of this parameter must take into account the value of\n /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n uint64 public redemptionDustThreshold;\n\n /// TODO: Make it governable.\n /// @notice Divisor used to compute the treasury fee taken from each\n /// redemption request and transferred to the treasury upon\n /// successful request finalization. That fee is computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 public redemptionTreasuryFeeDivisor;\n\n /// TODO: Make it governable.\n /// @notice Maximum amount of BTC transaction fee that can be incurred by\n /// each redemption request being part of the given redemption\n /// transaction. If the maximum BTC transaction fee is exceeded, such\n /// transaction is considered a fraud.\n /// @dev This is a per-redemption output max fee for the redemption transaction.\n uint64 public redemptionTxMaxFee;\n\n /// TODO: Make it governable.\n /// @notice Time after which the redemption request can be reported as\n /// timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported\n /// timed out requests are cancelled and locked TBTC is returned\n /// to the redeemer in full amount.\n uint256 public redemptionTimeout;\n\n /// TODO: Make it governable.\n /// @notice Maximum amount of the total BTC transaction fee that is\n /// acceptable in a single moving funds transaction.\n /// @dev This is a TOTAL max fee for the moving funds transaction. Note that\n /// `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n /// if per single redemption. `movingFundsTxMaxTotalFee` is a total fee\n /// for the entire transaction.\n uint64 public movingFundsTxMaxTotalFee;\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out\n mapping(uint256 => RedemptionRequest) public pendingRedemptions;\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// keccak256(walletPubKeyHash | redeemerOutputScript). The\n /// walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and redeemerOutputScript is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request. Timed out requests are stored in this mapping to\n /// avoid slashing the wallets multiple times for the same timeout.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping basing on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n mapping(uint256 => RedemptionRequest) public timedOutRedemptions;\n\n /// @notice Contains parameters related to frauds and the collection of all\n /// submitted fraud challenges.\n Frauds.Data internal frauds;\n\n /// @notice State related with wallets.\n Wallets.Data internal wallets;\n\n event WalletCreationPeriodUpdated(uint32 newCreationPeriod);\n\n event WalletBtcBalanceRangeUpdated(\n uint64 newMinBtcBalance,\n uint64 newMaxBtcBalance\n );\n\n event WalletMaxAgeUpdated(uint32 newMaxAge);\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdated(\n uint256 newFraudNotifierRewardMultiplier\n );\n\n event FraudChallengeDefeatTimeoutUpdated(\n uint256 newFraudChallengeDefeatTimeout\n );\n\n event FraudChallengeDepositAmountUpdated(\n uint256 newFraudChallengeDepositAmount\n );\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript,\n address redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPublicKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPublicKeyHash,\n bytes32 sighash\n );\n\n event MovingFundsCompleted(\n bytes20 walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n constructor(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n uint256 _txProofDifficultyFactor\n ) {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n // TODO: Revisit initial values.\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 10000; // 10000 satoshi\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n redemptionTxMaxFee = 10000; // 10000 satoshi\n redemptionTimeout = 172800; // 48 hours\n movingFundsTxMaxTotalFee = 10000; // 10000 satoshi\n\n // TODO: Revisit initial values.\n frauds.setSlashingAmount(10000 * 1e18); // 10000 T\n frauds.setNotifierRewardMultiplier(100); // 100%\n frauds.setChallengeDefeatTimeout(7 days);\n frauds.setChallengeDepositAmount(2 ether);\n\n // TODO: Revisit initial values.\n wallets.init(_ecdsaWalletRegistry);\n wallets.setCreationPeriod(1 weeks);\n wallets.setBtcBalanceRange(1 * 1e8, 10 * 1e8); // [1 BTC, 10 BTC]\n wallets.setMaxAge(26 weeks); // ~6 months\n }\n\n /// @notice Updates parameters used by the `Wallets` library.\n /// @param creationPeriod New value of the wallet creation period\n /// @param minBtcBalance New value of the minimum BTC balance\n /// @param maxBtcBalance New value of the maximum BTC balance\n /// @param maxAge New value of the wallet maximum age\n /// @dev Requirements:\n /// - Caller must be the contract owner.\n /// - Minimum BTC balance must be greater than zero\n /// - Maximum BTC balance must be greater than minimum BTC balance\n function updateWalletsParameters(\n uint32 creationPeriod,\n uint64 minBtcBalance,\n uint64 maxBtcBalance,\n uint32 maxAge\n ) external onlyOwner {\n wallets.setCreationPeriod(creationPeriod);\n wallets.setBtcBalanceRange(minBtcBalance, maxBtcBalance);\n wallets.setMaxAge(maxAge);\n }\n\n /// @return creationPeriod Value of the wallet creation period\n /// @return minBtcBalance Value of the minimum BTC balance\n /// @return maxBtcBalance Value of the maximum BTC balance\n /// @return maxAge Value of the wallet max age\n function getWalletsParameters()\n external\n view\n returns (\n uint32 creationPeriod,\n uint64 minBtcBalance,\n uint64 maxBtcBalance,\n uint32 maxAge\n )\n {\n creationPeriod = wallets.creationPeriod;\n minBtcBalance = wallets.minBtcBalance;\n maxBtcBalance = wallets.maxBtcBalance;\n maxAge = wallets.maxAge;\n\n return (creationPeriod, minBtcBalance, maxBtcBalance, maxAge);\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost.\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault\n /// @param isTrusted flag indicating whether the vault is trusted or not\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted) external onlyOwner {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored.\n /// - Wallet creation must not be in progress\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time\n /// - The active wallet BTC balance is above the maximum threshold\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n wallets.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Given wallet data must not belong to an already registered wallet\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n wallets.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate\n /// @param publicKeyY Wallet's public key's Y coordinate\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`\n /// - Wallet must be in Live state\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n wallets.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshis left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero.\n /// - Wallet must be in Live state\n function notifyCloseableWallet(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n wallets.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @return Wallet details.\n function getWallet(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return wallets.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function getActiveWalletPubKeyHash() external view returns (bytes20) {\n return wallets.activeWalletPubKeyHash;\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`\n /// @param reveal Deposit reveal data, see `RevealInfo struct\n /// @dev Requirements:\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet\n /// - `reveal.vault` must be 0x0 or point to a trusted vault\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction\n /// - `reveal.depositor` must be the Ethereum address used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.RevealInfo calldata reveal\n ) external {\n self.revealDeposit(wallets, fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.submitSweepProof(wallets, sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n ///@param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - Wallet behind `walletPubKey` must be in `Live` or `MovingFunds`\n /// state\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n 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 = wallets.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds,\n \"Wallet is neither in Live nor MovingFunds state\"\n );\n\n frauds.submitChallenge(\n walletPublicKey,\n walletPubKeyHash,\n sighash,\n signature\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 bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n uint256 utxoKey = frauds.unwrapChallenge(\n walletPublicKey,\n preimage,\n witness\n );\n\n // Check that the UTXO key identifies a correctly spent UTXO.\n require(\n self.deposits[utxoKey].sweptAt > 0 || self.spentMainUTXOs[utxoKey],\n \"Spent UTXO not found among correctly spent UTXOs\"\n );\n\n frauds.defeatChallenge(walletPublicKey, preimage, self.treasury);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - `walletPublicKey`and `sighash` must identify an open fraud\n /// challenge\n /// - the amount of time indicated by `challengeDefeatTimeout` must\n /// pass after the challenge was reported\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n frauds.notifyChallengeDefeatTimeout(walletPublicKey, sighash);\n }\n\n /// @notice Returns parameters used by the `Frauds` library.\n /// @return slashingAmount Value of the slashing amount\n /// @return notifierRewardMultiplier Value of the notifier reward multiplier\n /// @return challengeDefeatTimeout Value of the challenge defeat timeout\n /// @return challengeDepositAmount Value of the challenge deposit amount\n function getFraudParameters()\n external\n view\n returns (\n uint256 slashingAmount,\n uint256 notifierRewardMultiplier,\n uint256 challengeDefeatTimeout,\n uint256 challengeDepositAmount\n )\n {\n slashingAmount = frauds.slashingAmount;\n notifierRewardMultiplier = frauds.notifierRewardMultiplier;\n challengeDefeatTimeout = frauds.challengeDefeatTimeout;\n challengeDepositAmount = frauds.challengeDepositAmount;\n\n return (\n slashingAmount,\n notifierRewardMultiplier,\n challengeDefeatTimeout,\n challengeDepositAmount\n );\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Frauds.FraudChallenge memory)\n {\n return frauds.challenges[challengeKey];\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key)\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC\n /// @param amount Requested amount in satoshi. This is also the TBTC amount\n /// that is taken from redeemer's balance in the Bank upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// - `redeemerOutputScript` must be a proper Bitcoin script\n /// - `redeemerOutputScript` cannot have wallet PKH as payload\n /// - `amount` must be above or equal the `redemptionDustThreshold`\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time\n /// - Wallet must have enough Bitcoin balance to proceed the request\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n Wallets.Wallet storage wallet = wallets.registeredWallets[\n walletPubKeyHash\n ];\n\n require(\n wallet.state == Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n require(\n mainUtxoHash != bytes32(0),\n \"No main UTXO for the given wallet\"\n );\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n\n // TODO: Confirm if `walletPubKeyHash` should be validated by checking\n // if it is the oldest one who can handle the request. This will\n // be suggested by the dApp but may not be respected by users who\n // interact directly with the contract. Do we need to enforce it\n // here? One option is not to enforce it, to save on gas, but if\n // we see this rule is not respected, upgrade Bridge contract to\n // require it.\n\n // Validate if redeemer output script is a correct standard type\n // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub\n // output with 0 as value and using `BTCUtils.extractHash` on it. Such\n // a function extracts the payload properly only from standard outputs\n // so if it succeeds, we have a guarantee the redeemer output script\n // is proper. Worth to note `extractHash` ignores the value at all\n // so this is why we can use 0 safely. This way of validation is the\n // same as in tBTC v1.\n bytes memory redeemerOutputScriptPayload = abi\n .encodePacked(bytes8(0), redeemerOutputScript)\n .extractHash();\n require(\n redeemerOutputScriptPayload.length > 0,\n \"Redeemer output script must be a standard type\"\n );\n // Check if the redeemer output script payload does not point to the\n // wallet public key hash.\n require(\n keccak256(abi.encodePacked(walletPubKeyHash)) !=\n keccak256(redeemerOutputScriptPayload),\n \"Redeemer output script must not point to the wallet PKH\"\n );\n\n require(\n amount >= 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 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 = redemptionTreasuryFeeDivisor > 0\n ? amount / redemptionTreasuryFeeDivisor\n : 0;\n uint64 txMaxFee = 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 pendingRedemptions[redemptionKey] = RedemptionRequest(\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee,\n /* solhint-disable-next-line not-rely-on-time */\n uint32(block.timestamp)\n );\n\n emit RedemptionRequested(\n walletPubKeyHash,\n redeemerOutputScript,\n msg.sender,\n amount,\n treasuryFee,\n txMaxFee\n );\n\n self.bank.transferBalanceFrom(msg.sender, address(this), amount);\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data\n /// @param redemptionProof Bitcoin redemption proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance.\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // TODO: Just as for `submitSweepProof`, fail early if the function\n // call gets frontrunned. See discussion:\n // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204\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 = BitcoinTx.validateProof(\n redemptionTx,\n redemptionProof,\n self.proofDifficultyContext()\n );\n\n // Process the redemption transaction input. Specifically, check if it\n // refers to the expected wallet's main UTXO.\n processWalletOutboundTxInput(\n redemptionTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n Wallets.Wallet storage wallet = wallets.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 MovingFuds state\"\n );\n\n // Process redemption transaction outputs to extract some info required\n // for further processing.\n RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(\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 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 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 = wallets\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 /// @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 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 // Helper variable that counts the number of processed redemption\n // outputs. Redemptions can be either pending or reported as timed out.\n // TODO: Revisit the approach with redemptions count according to\n // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765\n uint256 processedRedemptionsCount = 0;\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n 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 info.changeValue == 0 &&\n (keccak256(outputScript) == walletP2PKHScriptKeccak ||\n keccak256(outputScript) == 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 info.changeIndex = uint32(i);\n info.changeValue = outputValue;\n } else {\n // If we entered here, that the means 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 (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 = 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 info.totalBurnableValue += redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n info.totalTreasuryFee += 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 pendingRedemptions[redemptionKey];\n\n processedRedemptionsCount++;\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 = 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 processedRedemptionsCount++;\n }\n }\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 // 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 processedRedemptionsCount > 0,\n \"Redemption transaction must process at least one redemption\"\n );\n\n return info;\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n bytes calldata redeemerOutputScript\n ) external {\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))\n );\n RedemptionRequest memory request = pendingRedemptions[redemptionKey];\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 + 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 = wallets.registeredWallets[\n walletPubKeyHash\n ];\n wallet.pendingRedemptionsValue -=\n request.requestedAmount -\n request.treasuryFee;\n\n require(\n // TODO: Allow the wallets in `Closing` state when the state is added\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds ||\n wallet.state == Wallets.WalletState.Terminated,\n \"The wallet must be in Live, MovingFunds or Terminated state\"\n );\n\n // It is worth noting that there is no need to check if\n // `timedOutRedemption` mapping already contains the given redemption\n // key. There is no possibility to re-use a key of a reported timed-out\n // redemption because the wallet responsible for causing the timeout is\n // moved to a state that prevents it to receive new redemption requests.\n\n // Move the redemption from pending redemptions to timed-out redemptions\n timedOutRedemptions[redemptionKey] = request;\n delete pendingRedemptions[redemptionKey];\n\n if (\n wallet.state == Wallets.WalletState.Live ||\n wallet.state == Wallets.WalletState.MovingFunds\n ) {\n // Propagate timeout consequences to the wallet\n wallets.notifyRedemptionTimedOut(walletPubKeyHash);\n }\n\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 /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data\n /// @param movingFundsProof Bitcoin moving funds proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment.\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set.\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state.\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to.\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external {\n // 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 = BitcoinTx.validateProof(\n movingFundsTx,\n movingFundsProof,\n self.proofDifficultyContext()\n );\n\n // Process the moving funds transaction input. Specifically, check if\n // it refers to the expected wallet's main UTXO.\n processWalletOutboundTxInput(\n movingFundsTx.inputVector,\n mainUtxo,\n walletPubKeyHash\n );\n\n (\n bytes32 targetWalletsHash,\n uint256 outputsTotalValue\n ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);\n\n require(\n mainUtxo.txOutputValue - outputsTotalValue <=\n movingFundsTxMaxTotalFee,\n \"Transaction fee is too high\"\n );\n\n wallets.notifyFundsMoved(walletPubKeyHash, targetWalletsHash);\n\n emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);\n }\n\n /// @notice Processes the moving funds Bitcoin transaction output vector\n /// and extracts information required for further processing.\n /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @return targetWalletsHash keccak256 hash over the list of actual\n /// target wallets used in the transaction.\n /// @return outputsTotalValue Sum of all outputs values.\n /// @dev Requirements:\n /// - The `movingFundsTxOutputVector` must be parseable, i.e. must\n /// be validated by the caller as stated in their parameter doc.\n /// - Each output must refer to a 20-byte public key hash.\n /// - The total outputs value must be evenly divided over all outputs.\n function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)\n internal\n view\n returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)\n {\n // Determining the total number of Bitcoin transaction outputs in\n // the same way as for number of inputs. See `BitcoinTx.outputVector`\n // docs for more details.\n (\n uint256 outputsCompactSizeUintLength,\n uint256 outputsCount\n ) = movingFundsTxOutputVector.parseVarInt();\n\n // To determine the first output starting index, we must jump over\n // the compactSize uint which prepends the output vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;\n\n bytes20[] memory targetWallets = new bytes20[](outputsCount);\n uint64[] memory outputsValues = new uint64[](outputsCount);\n\n // Outputs processing loop.\n for (uint256 i = 0; i < outputsCount; i++) {\n uint256 outputLength = movingFundsTxOutputVector\n .determineOutputLengthAt(outputStartingIndex);\n\n bytes memory output = movingFundsTxOutputVector.slice(\n outputStartingIndex,\n outputLength\n );\n\n // Extract the output script payload.\n bytes memory targetWalletPubKeyHashBytes = output.extractHash();\n // Output script payload must refer to a known wallet public key\n // hash which is always 20-byte.\n require(\n targetWalletPubKeyHashBytes.length == 20,\n \"Target wallet public key hash must have 20 bytes\"\n );\n\n bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes\n .slice20(0);\n\n // The next step is making sure that the 20-byte public key hash\n // is actually used in the right context of a P2PKH or P2WPKH\n // output. To do so, we must extract the full script from the output\n // and compare with the expected P2PKH and P2WPKH scripts\n // referring to that 20-byte public key hash. The output consists\n // of an 8-byte value and a variable length script. To extract the\n // script we slice the output starting from 9th byte until the end.\n bytes32 outputScriptKeccak = keccak256(\n output.slice(8, output.length - 8)\n );\n // Build the expected P2PKH script which has the following byte\n // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x19: Byte length of the entire script\n // - 0x76: OP_DUP\n // - 0xa9: OP_HASH160\n // - 0x14: Byte length of the public key hash\n // - 0x88: OP_EQUALVERIFY\n // - 0xac: OP_CHECKSIG\n // which matches the P2PKH structure as per:\n // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n bytes32 targetWalletP2PKHScriptKeccak = keccak256(\n abi.encodePacked(\n hex\"1976a914\",\n targetWalletPubKeyHash,\n hex\"88ac\"\n )\n );\n // Build the expected P2WPKH script which has the following format:\n // <0x160014> <20-byte PKH>. According to\n // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n // - 0x16: Byte length of the entire script\n // - 0x00: OP_0\n // - 0x14: Byte length of the public key hash\n // which matches the P2WPKH structure as per:\n // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n bytes32 targetWalletP2WPKHScriptKeccak = keccak256(\n abi.encodePacked(hex\"160014\", targetWalletPubKeyHash)\n );\n // Make sure the actual output script matches either the P2PKH\n // or P2WPKH format.\n require(\n outputScriptKeccak == targetWalletP2PKHScriptKeccak ||\n outputScriptKeccak == targetWalletP2WPKHScriptKeccak,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n // Add the wallet public key hash to the list that will be used\n // to build the result list hash. There is no need to check if\n // given output is a change here because the actual target wallet\n // list must be exactly the same as the pre-committed target wallet\n // list which is guaranteed to be valid.\n targetWallets[i] = targetWalletPubKeyHash;\n\n // Extract the value from given output.\n outputsValues[i] = output.extractValue();\n outputsTotalValue += outputsValues[i];\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n outputStartingIndex += outputLength;\n }\n\n // Compute the indivisible remainder that remains after dividing the\n // outputs total value over all outputs evenly.\n uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;\n // Compute the minimum allowed output value by dividing the outputs\n // total value (reduced by the remainder) by the number of outputs.\n uint256 minOutputValue = (outputsTotalValue -\n outputsTotalValueRemainder) / outputsCount;\n // Maximum possible value is the minimum value with the remainder included.\n uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;\n\n for (uint256 i = 0; i < outputsCount; i++) {\n require(\n minOutputValue <= outputsValues[i] &&\n outputsValues[i] <= maxOutputValue,\n \"Transaction amount is not distributed evenly\"\n );\n }\n\n targetWalletsHash = keccak256(abi.encodePacked(targetWallets));\n\n return (targetWalletsHash, outputsTotalValue);\n }\n\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n function getContracts() external view returns (Bank bank, IRelay relay) {\n bank = self.bank;\n relay = self.relay;\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @return treasury Address where the deposit treasury fees will be\n /// sent to. Treasury takes part in the operators rewarding process.\n /// @return txProofDifficultyFactor The number of confirmations on the\n /// Bitcoin chain required to successfully evaluate an SPV proof.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n address treasury,\n uint256 txProofDifficultyFactor\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n treasury = self.treasury;\n txProofDifficultyFactor = self.txProofDifficultyFactor;\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.Request memory)\n {\n // TODO: rename to getDeposit?\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n}\n"
|
|
147
147
|
},
|
|
148
148
|
"@keep-network/ecdsa/contracts/api/IWalletOwner.sol": {
|
|
149
149
|
"content": "// SPDX-License-Identifier: MIT\n//\n// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀\n// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌\n// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓\n//\n// Trust math, not hardware.\n\npragma solidity ^0.8.9;\n\ninterface IWalletOwner {\n /// @notice Callback function executed once a new wallet is created.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletCreatedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n\n /// @notice Callback function executed once a wallet heartbeat failure\n /// is detected.\n /// @dev Should be callable only by the Wallet Registry.\n /// @param walletID Wallet's unique identifier.\n /// @param publicKeyY Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32 walletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external;\n}\n"
|
|
150
150
|
},
|
|
151
|
-
"contracts/bridge/
|
|
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\
|
|
151
|
+
"contracts/bridge/IRelay.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\n/// @title Interface for the Bitcoin relay\n/// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay\n/// provides the difficulty of the previous and current epoch. One\n/// difficulty epoch spans 2016 blocks.\ninterface IRelay {\n /// @notice Returns the difficulty of the current epoch.\n function getCurrentEpochDifficulty() external view returns (uint256);\n\n /// @notice Returns the difficulty of the previous epoch.\n function getPrevEpochDifficulty() external view returns (uint256);\n}\n"
|
|
153
153
|
},
|
|
154
|
-
"contracts/bridge/
|
|
155
|
-
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {CheckBitcoinSigs} from \"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Bridge.sol\";\n\nlibrary Frauds {\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct Data {\n /// The amount of stake slashed from each member of a wallet for a fraud.\n uint256 slashingAmount;\n /// The percentage of the notifier reward from the staking contract\n /// the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 notifierRewardMultiplier;\n /// The amount of time the wallet has to defeat a fraud challenge.\n uint256 challengeDefeatTimeout;\n /// The amount of ETH in wei the party challenging the wallet for fraud\n /// needs to deposit.\n uint256 challengeDepositAmount;\n /// Collection of all submitted fraud challenges indexed by challenge\n /// key built as keccak256(walletPublicKey|sighash).\n mapping(uint256 => FraudChallenge) challenges;\n }\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n }\n\n event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdated(\n uint256 newFraudNotifierRewardMultiplier\n );\n\n event FraudChallengeDefeatTimeoutUpdated(\n uint256 newFraudChallengeDefeatTimeout\n );\n\n event FraudChallengeDepositAmountUpdated(\n uint256 newFraudChallengeDepositAmount\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPublicKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPublicKeyHash,\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 walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.challengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[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\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Unwraps the fraud challenge by verifying the given challenge\n /// and returns the UTXO key extracted from the preimage.\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 /// @return utxoKey UTXO key that identifies spent 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 function unwrapChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external returns (uint256 utxoKey) {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[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 return\n witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n }\n\n /// @notice Finalizes fraud challenge defeat by marking a pending fraud\n /// challenge against the wallet as resolved and sending the ether\n /// deposited by the challenger to the treasury.\n /// In order to finalize the challenge defeat the same\n /// `walletPublicKey` must be provided as was used in the fraud\n /// challenge. Additionally a preimage must be provided which was\n /// used to calculate the sighash during input signing.\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 treasury Treasury associated with the Bridge\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 defeatChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n address treasury\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.challenges[challengeKey];\n\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls\n 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 emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after a\n /// fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` must identify an open fraud\n /// challenge\n /// - the amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported\n function notifyChallengeDefeatTimeout(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[challengeKey];\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.challengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n // TODO: Call notifyFraud from Wallets library\n // TODO: Reward the challenger\n\n challenge.resolved = true;\n\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls\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 emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Sets the new value for the `slashingAmount` parameter.\n /// @param _newSlashingAmount the new value for `slashingAmount`\n function setSlashingAmount(Data storage self, uint256 _newSlashingAmount)\n external\n {\n self.slashingAmount = _newSlashingAmount;\n emit FraudSlashingAmountUpdated(_newSlashingAmount);\n }\n\n /// @notice Sets the new value for the `notifierRewardMultiplier` parameter.\n /// @param _newNotifierRewardMultiplier the new value for `notifierRewardMultiplier`\n /// @dev The value of `notifierRewardMultiplier` must be <= 100.\n function setNotifierRewardMultiplier(\n Data storage self,\n uint256 _newNotifierRewardMultiplier\n ) external {\n require(\n _newNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be <= 100\"\n );\n self.notifierRewardMultiplier = _newNotifierRewardMultiplier;\n emit FraudNotifierRewardMultiplierUpdated(_newNotifierRewardMultiplier);\n }\n\n /// @notice Sets the new value for the `challengeDefeatTimeout` parameter.\n /// @param _newChallengeDefeatTimeout the new value for `challengeDefeatTimeout`\n /// @dev The value of `challengeDefeatTimeout` must be > 0.\n function setChallengeDefeatTimeout(\n Data storage self,\n uint256 _newChallengeDefeatTimeout\n ) external {\n require(\n _newChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be > 0\"\n );\n self.challengeDefeatTimeout = _newChallengeDefeatTimeout;\n emit FraudChallengeDefeatTimeoutUpdated(_newChallengeDefeatTimeout);\n }\n\n /// @notice Sets the new value for the `challengeDepositAmount` parameter.\n /// @param _newChallengeDepositAmount the new value for `challengeDepositAmount`\n /// @dev The value of `challengeDepositAmount` must be > 0.\n function setChallengeDepositAmount(\n Data storage self,\n uint256 _newChallengeDepositAmount\n ) external {\n require(\n _newChallengeDepositAmount > 0,\n \"Fraud challenge deposit amount must be > 0\"\n );\n self.challengeDepositAmount = _newChallengeDepositAmount;\n emit FraudChallengeDepositAmountUpdated(_newChallengeDepositAmount);\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"
|
|
154
|
+
"contracts/bridge/BridgeState.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 \"./IRelay.sol\";\nimport \"./Deposit.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n struct Storage {\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n uint256 txProofDifficultyFactor;\n /// TODO: Revisit whether it should be governable or not.\n /// @notice Address of the Bank this Bridge belongs to.\n Bank bank;\n /// TODO: Make it governable.\n /// @notice Bitcoin relay providing the current Bitcoin network\n /// difficulty.\n IRelay relay;\n /// TODO: Revisit whether it should be governable or not.\n /// @notice Address where the deposit and redemption treasury fees will\n /// be sent to. Treasury takes part in the operators rewarding\n /// process.\n address treasury;\n /// TODO: Make it governable.\n /// @notice The minimal amount that can be requested to deposit.\n /// Value of this parameter must take into account the value of\n /// `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n uint64 depositDustThreshold;\n /// TODO: Make it governable.\n /// @notice Divisor used to compute the treasury fee taken from each\n /// deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n /// TODO: Make it governable.\n /// @notice Maximum amount of BTC transaction fee that can be incurred by\n /// each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @dev This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n mapping(uint256 => Deposit.Request) deposits;\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n mapping(address => bool) isVaultTrusted;\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n }\n\n // TODO: Is it the right place for this function? Should we move it to Bridge?\n /// @notice Determines the current Bitcoin SPV proof difficulty context.\n /// @return proofDifficulty Bitcoin proof difficulty context.\n function proofDifficultyContext(Storage storage self)\n internal\n view\n returns (BitcoinTx.ProofDifficulty memory proofDifficulty)\n {\n IRelay relay = self.relay;\n proofDifficulty.currentEpochDifficulty = relay\n .getCurrentEpochDifficulty();\n proofDifficulty.previousEpochDifficulty = relay\n .getPrevEpochDifficulty();\n proofDifficulty.difficultyFactor = self.txProofDifficultyFactor;\n\n return proofDifficulty;\n }\n}\n"
|
|
156
156
|
},
|
|
157
157
|
"contracts/bridge/Deposit.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\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\nlibrary Deposit {\n using Wallets for Wallets.Data;\n\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 RevealInfo {\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 }\n\n /// @notice Represents tBTC deposit request data.\n struct Request {\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 }\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n /// @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 Wallets.Data storage wallets,\n BitcoinTx.Info calldata fundingTx,\n RevealInfo calldata reveal\n ) external {\n require(\n wallets.registeredWallets[reveal.walletPubKeyHash].state ==\n Wallets.WalletState.Live,\n \"Wallet is not in Live state\"\n );\n\n require(\n reveal.vault == address(0) || self.isVaultTrusted[reveal.vault],\n \"Vault is not trusted\"\n );\n\n // TODO: Should we enforce a specific locktime at contract level?\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 Request 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\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"
|
|
159
159
|
},
|
|
160
|
+
"contracts/bridge/Sweep.sol": {
|
|
161
|
+
"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\nlibrary Sweep {\n using BridgeState for BridgeState.Storage;\n\n using BTCUtils for bytes;\n\n /// @notice Represents an outcome of the sweep Bitcoin transaction\n /// inputs processing.\n struct SweepTxInputsInfo {\n // Sum of all inputs values i.e. all deposits and main UTXO value,\n // if present.\n uint256 inputsTotalValue;\n // Addresses of depositors who performed processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n address[] depositors;\n // Amounts of deposits corresponding to processed deposits. Ordered in\n // the same order as deposits inputs in the input vector. Size of this\n // array is either equal to the number of inputs (main UTXO doesn't\n // exist) or less by one (main UTXO exists and is pointed by one of\n // the inputs).\n uint256[] depositedAmounts;\n // Values of the treasury fee corresponding to processed deposits.\n // Ordered in the same order as deposits inputs in the input vector.\n // Size of this array is either equal to the number of inputs (main\n // UTXO doesn't exist) or less by one (main UTXO exists and is pointed\n // by one of the inputs).\n uint256[] treasuryFees;\n }\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data\n /// @param sweepProof Bitcoin sweep proof data\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash.\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash.\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant.\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitSweepProof(\n BridgeState.Storage storage self,\n Wallets.Data storage wallets,\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n // TODO: Fail early if the function call gets frontrunned. See discussion:\n // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204\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 = BitcoinTx.validateProof(\n sweepTx,\n sweepProof,\n self.proofDifficultyContext()\n );\n\n // Process sweep transaction output and extract its target wallet\n // public key hash and value.\n (\n bytes20 walletPubKeyHash,\n uint64 sweepTxOutputValue\n ) = processSweepTxOutput(sweepTx.outputVector);\n\n (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n ) = resolveSweepingWallet(wallets, walletPubKeyHash, mainUtxo);\n\n // Process sweep transaction inputs and extract all information needed\n // to perform deposit bookkeeping.\n SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(\n self,\n sweepTx.inputVector,\n resolvedMainUtxo\n );\n\n // Helper variable that will hold the sum of treasury fees paid by\n // all deposits.\n uint256 totalTreasuryFee = 0;\n\n // Determine the transaction fee that should be incurred by each deposit\n // and the indivisible remainder that should be additionally incurred\n // by the last deposit.\n (\n uint256 depositTxFee,\n uint256 depositTxFeeRemainder\n ) = sweepTxFeeDistribution(\n inputsInfo.inputsTotalValue,\n sweepTxOutputValue,\n inputsInfo.depositedAmounts.length\n );\n\n // Make sure the highest value of the deposit transaction fee does not\n // exceed the maximum value limited by the governable parameter.\n require(\n depositTxFee + depositTxFeeRemainder <= self.depositTxMaxFee,\n \"Transaction fee is too high\"\n );\n\n // Reduce each deposit amount by treasury fee and transaction fee.\n for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {\n // The last deposit should incur the deposit transaction fee\n // remainder.\n uint256 depositTxFeeIncurred = i ==\n inputsInfo.depositedAmounts.length - 1\n ? depositTxFee + depositTxFeeRemainder\n : depositTxFee;\n\n // There is no need to check whether\n // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`\n // since the `depositDustThreshold` should force that condition\n // to be always true.\n inputsInfo.depositedAmounts[i] =\n inputsInfo.depositedAmounts[i] -\n inputsInfo.treasuryFees[i] -\n depositTxFeeIncurred;\n totalTreasuryFee += inputsInfo.treasuryFees[i];\n }\n\n // Record this sweep data and assign them to the wallet public key hash\n // as new main UTXO. Transaction output index is always 0 as sweep\n // transaction always contains only one output.\n wallet.mainUtxoHash = keccak256(\n abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)\n );\n\n emit DepositsSwept(walletPubKeyHash, sweepTxHash);\n\n // Update depositors balances in the Bank.\n self.bank.increaseBalances(\n inputsInfo.depositors,\n inputsInfo.depositedAmounts\n );\n // Pass the treasury fee to the treasury address.\n self.bank.increaseBalance(self.treasury, totalTreasuryFee);\n\n // TODO: Handle deposits having `vault` set.\n }\n\n /// @notice Resolves sweeping wallet based on the provided wallet public key\n /// hash. Validates the wallet state and current main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletPubKeyHash public key hash of the wallet proving the sweep\n /// Bitcoin transaction.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored\n /// @dev Requirements:\n /// - Sweeping wallet must be either in Live or MovingFunds state.\n /// - If the main UTXO of the sweeping wallet exists in the storage,\n /// the passed `mainUTXO` parameter must be equal to the stored one.\n function resolveSweepingWallet(\n Wallets.Data storage wallets,\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n )\n internal\n returns (\n Wallets.Wallet storage wallet,\n BitcoinTx.UTXO memory resolvedMainUtxo\n )\n {\n wallet = wallets.registeredWallets[walletPubKeyHash];\n\n Wallets.WalletState walletState = wallet.state;\n require(\n walletState == Wallets.WalletState.Live ||\n walletState == Wallets.WalletState.MovingFunds,\n \"Wallet must be in Live or MovingFunds state\"\n );\n\n // Check if the main UTXO for given wallet exists. If so, validate\n // passed main UTXO data against the stored hash and use them for\n // further processing. If no main UTXO exists, use empty data.\n resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);\n bytes32 mainUtxoHash = wallet.mainUtxoHash;\n if (mainUtxoHash != bytes32(0)) {\n require(\n keccak256(\n abi.encodePacked(\n mainUtxo.txHash,\n mainUtxo.txOutputIndex,\n mainUtxo.txOutputValue\n )\n ) == mainUtxoHash,\n \"Invalid main UTXO data\"\n );\n resolvedMainUtxo = mainUtxo;\n }\n }\n\n /// @notice Processes the Bitcoin sweep transaction output vector by\n /// extracting the single output and using it to gain additional\n /// information required for further processing (e.g. value and\n /// wallet public key hash).\n /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVout` function before\n /// it is passed here\n /// @return walletPubKeyHash 20-byte wallet public key hash.\n /// @return value 8-byte sweep transaction output value.\n function processSweepTxOutput(bytes memory sweepTxOutputVector)\n internal\n pure\n returns (bytes20 walletPubKeyHash, uint64 value)\n {\n // To determine the total number of sweep transaction outputs, we need to\n // parse the compactSize uint (VarInt) the output vector is prepended by.\n // That compactSize uint encodes the number of vector elements using the\n // format presented in:\n // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers\n // We don't need asserting the compactSize uint is parseable since it\n // was already checked during `validateVout` validation.\n // See `BitcoinTx.outputVector` docs for more details.\n (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();\n require(\n outputsCount == 1,\n \"Sweep transaction must have a single output\"\n );\n\n bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);\n value = output.extractValue();\n bytes memory walletPubKeyHashBytes = output.extractHash();\n // The sweep transaction output should always be P2PKH or P2WPKH.\n // In both cases, the wallet public key hash should be 20 bytes length.\n require(\n walletPubKeyHashBytes.length == 20,\n \"Wallet public key hash should have 20 bytes\"\n );\n /* solhint-disable-next-line no-inline-assembly */\n assembly {\n walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))\n }\n\n return (walletPubKeyHash, value);\n }\n\n /// @notice Processes the Bitcoin sweep transaction input vector. It\n /// extracts each input and tries to obtain associated deposit or\n /// main UTXO data, depending on the input type. Reverts\n /// if one of the inputs cannot be recognized as a pointer to a\n /// revealed deposit or expected main UTXO.\n /// This function also marks each processed deposit as swept.\n /// @param sweepTxInputVector Bitcoin sweep transaction input vector.\n /// This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before\n /// it is passed here\n /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO\n /// exists for the given the wallet, this parameter's fields should\n /// be zeroed to bypass the main UTXO validation\n /// @return info Outcomes of the processing.\n function processSweepTxInputs(\n BridgeState.Storage storage self,\n bytes memory sweepTxInputVector,\n BitcoinTx.UTXO memory mainUtxo\n ) internal returns (SweepTxInputsInfo memory info) {\n // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO\n // for the given wallet doesn't exist and it is not expected to be\n // included in the sweep transaction input vector.\n bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);\n bool mainUtxoFound = false;\n\n // Determining the total number of sweep transaction inputs in the same\n // way as for number of outputs. See `BitcoinTx.inputVector` docs for\n // more details.\n (\n uint256 inputsCompactSizeUintLength,\n uint256 inputsCount\n ) = sweepTxInputVector.parseVarInt();\n\n // To determine the first input starting index, we must jump over\n // the compactSize uint which prepends the input vector. One byte\n // must be added because `BtcUtils.parseVarInt` does not include\n // compactSize uint tag in the returned length.\n //\n // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`\n // returns `0`, so we jump over one byte of compactSize uint.\n //\n // For >= 253 && <= 0xffff there is `0xfd` tag,\n // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no\n // tag byte included) so we need to jump over 1+2 bytes of\n // compactSize uint.\n //\n // Please refer `BTCUtils` library and compactSize uint\n // docs in `BitcoinTx` library for more details.\n uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;\n\n // Determine the swept deposits count. If main UTXO is NOT expected,\n // all inputs should be deposits. If main UTXO is expected, one input\n // should point to that main UTXO.\n info.depositors = new address[](\n !mainUtxoExpected ? inputsCount : inputsCount - 1\n );\n info.depositedAmounts = new uint256[](info.depositors.length);\n info.treasuryFees = new uint256[](info.depositors.length);\n\n // Initialize helper variables.\n uint256 processedDepositsCount = 0;\n\n // Inputs processing loop.\n for (uint256 i = 0; i < inputsCount; i++) {\n (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);\n\n Deposit.Request storage deposit = self.deposits[\n uint256(\n keccak256(abi.encodePacked(outpointTxHash, outpointIndex))\n )\n ];\n\n if (deposit.revealedAt != 0) {\n // If we entered here, that means the input was identified as\n // a revealed deposit.\n require(deposit.sweptAt == 0, \"Deposit already swept\");\n\n if (processedDepositsCount == info.depositors.length) {\n // If this condition is true, that means a deposit input\n // took place of an expected main UTXO input.\n // In other words, there is no expected main UTXO\n // input and all inputs come from valid, revealed deposits.\n revert(\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n }\n\n /* solhint-disable-next-line not-rely-on-time */\n deposit.sweptAt = uint32(block.timestamp);\n\n info.depositors[processedDepositsCount] = deposit.depositor;\n info.depositedAmounts[processedDepositsCount] = deposit.amount;\n info.inputsTotalValue += info.depositedAmounts[\n processedDepositsCount\n ];\n info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;\n\n processedDepositsCount++;\n } else if (\n mainUtxoExpected != mainUtxoFound &&\n mainUtxo.txHash == outpointTxHash\n ) {\n // If we entered here, that means the input was identified as\n // the expected main UTXO.\n info.inputsTotalValue += mainUtxo.txOutputValue;\n mainUtxoFound = true;\n\n // Main UTXO used as an input, mark it as spent.\n self.spentMainUTXOs[\n uint256(\n keccak256(\n abi.encodePacked(outpointTxHash, outpointIndex)\n )\n )\n ] = true;\n } else {\n revert(\"Unknown input type\");\n }\n\n // Make the `inputStartingIndex` pointing to the next input by\n // increasing it by current input's length.\n inputStartingIndex += inputLength;\n }\n\n // Construction of the input processing loop guarantees that:\n // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`\n // is always true at this point. We just use the first variable\n // to assert the total count of swept deposit is bigger than zero.\n require(\n processedDepositsCount > 0,\n \"Sweep transaction must process at least one deposit\"\n );\n\n // Assert the main UTXO was used as one of current sweep's inputs if\n // it was actually expected.\n require(\n mainUtxoExpected == mainUtxoFound,\n \"Expected main UTXO not present in sweep transaction inputs\"\n );\n\n return info;\n }\n\n /// @notice Parses a Bitcoin transaction input starting at the given index.\n /// @param inputVector Bitcoin transaction input vector\n /// @param inputStartingIndex Index the given input starts at\n /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is\n /// pointed in the given input's outpoint.\n /// @return outpointIndex 4-byte index of the Bitcoin transaction output\n /// which is pointed in the given input's outpoint.\n /// @return inputLength Byte length of the given input.\n /// @dev This function assumes vector's structure is valid so it must be\n /// validated using e.g. `BTCUtils.validateVin` function before it\n /// is passed here.\n function parseTxInputAt(\n bytes memory inputVector,\n uint256 inputStartingIndex\n )\n internal\n pure\n returns (\n bytes32 outpointTxHash,\n uint32 outpointIndex,\n uint256 inputLength\n )\n {\n outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);\n\n outpointIndex = BTCUtils.reverseUint32(\n uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))\n );\n\n inputLength = inputVector.determineInputLengthAt(inputStartingIndex);\n\n return (outpointTxHash, outpointIndex, inputLength);\n }\n\n /// @notice Determines the distribution of the sweep transaction fee\n /// over swept deposits.\n /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.\n /// @param sweepTxOutputValue Value of the sweep transaction output.\n /// @param depositsCount Count of the deposits swept by the sweep transaction.\n /// @return depositTxFee Transaction fee per deposit determined by evenly\n /// spreading the divisible part of the sweep transaction fee\n /// over all deposits.\n /// @return depositTxFeeRemainder The indivisible part of the sweep\n /// transaction fee than cannot be distributed over all deposits.\n /// @dev It is up to the caller to decide how the remainder should be\n /// counted in. This function only computes its value.\n function sweepTxFeeDistribution(\n uint256 sweepTxInputsTotalValue,\n uint256 sweepTxOutputValue,\n uint256 depositsCount\n )\n internal\n pure\n returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)\n {\n // The sweep transaction fee is just the difference between inputs\n // amounts sum and the output amount.\n uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;\n // Compute the indivisible remainder that remains after dividing the\n // sweep transaction fee over all deposits evenly.\n depositTxFeeRemainder = sweepTxFee % depositsCount;\n // Compute the transaction fee per deposit by dividing the sweep\n // transaction fee (reduced by the remainder) by the number of deposits.\n depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;\n\n return (depositTxFee, depositTxFeeRemainder);\n }\n}\n"
|
|
162
|
+
},
|
|
163
|
+
"contracts/bridge/Frauds.sol": {
|
|
164
|
+
"content": "// SPDX-License-Identifier: MIT\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity ^0.8.9;\n\nimport {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\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Bridge.sol\";\n\nlibrary Frauds {\n using BytesLib for bytes;\n using BTCUtils for bytes;\n using BTCUtils for uint32;\n using EcdsaLib for bytes;\n\n struct Data {\n /// The amount of stake slashed from each member of a wallet for a fraud.\n uint256 slashingAmount;\n /// The percentage of the notifier reward from the staking contract\n /// the notifier of a fraud receives. The value is in the range [0, 100].\n uint256 notifierRewardMultiplier;\n /// The amount of time the wallet has to defeat a fraud challenge.\n uint256 challengeDefeatTimeout;\n /// The amount of ETH in wei the party challenging the wallet for fraud\n /// needs to deposit.\n uint256 challengeDepositAmount;\n /// Collection of all submitted fraud challenges indexed by challenge\n /// key built as keccak256(walletPublicKey|sighash).\n mapping(uint256 => FraudChallenge) challenges;\n }\n\n struct FraudChallenge {\n // The address of the party challenging the wallet.\n address challenger;\n // The amount of ETH the challenger deposited.\n uint256 depositAmount;\n // The timestamp the challenge was submitted at.\n uint32 reportedAt;\n // The flag indicating whether the challenge has been resolved.\n bool resolved;\n }\n\n event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdated(\n uint256 newFraudNotifierRewardMultiplier\n );\n\n event FraudChallengeDefeatTimeoutUpdated(\n uint256 newFraudChallengeDefeatTimeout\n );\n\n event FraudChallengeDepositAmountUpdated(\n uint256 newFraudChallengeDepositAmount\n );\n\n event FraudChallengeSubmitted(\n bytes20 walletPublicKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);\n\n event FraudChallengeDefeatTimedOut(\n bytes20 walletPublicKeyHash,\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 walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @param signature Bitcoin signature in the R/S/V format\n /// @dev Requirements:\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// - Wallet can be challenged for the given signature only once\n function submitChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes20 walletPubKeyHash,\n bytes32 sighash,\n BitcoinTx.RSVSignature calldata signature\n ) external {\n require(\n msg.value >= self.challengeDepositAmount,\n \"The amount of ETH deposited is too low\"\n );\n\n require(\n CheckBitcoinSigs.checkSig(\n walletPublicKey,\n sighash,\n signature.v,\n signature.r,\n signature.s\n ),\n \"Signature verification failure\"\n );\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[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\n emit FraudChallengeSubmitted(\n walletPubKeyHash,\n sighash,\n signature.v,\n signature.r,\n signature.s\n );\n }\n\n /// @notice Unwraps the fraud challenge by verifying the given challenge\n /// and returns the UTXO key extracted from the preimage.\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 /// @return utxoKey UTXO key that identifies spent 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 function unwrapChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external returns (uint256 utxoKey) {\n bytes32 sighash = preimage.hash256();\n\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[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 return\n witness\n ? extractUtxoKeyFromWitnessPreimage(preimage)\n : extractUtxoKeyFromNonWitnessPreimage(preimage);\n }\n\n /// @notice Finalizes fraud challenge defeat by marking a pending fraud\n /// challenge against the wallet as resolved and sending the ether\n /// deposited by the challenger to the treasury.\n /// In order to finalize the challenge defeat the same\n /// `walletPublicKey` must be provided as was used in the fraud\n /// challenge. Additionally a preimage must be provided which was\n /// used to calculate the sighash during input signing.\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 treasury Treasury associated with the Bridge\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 defeatChallenge(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n address treasury\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.challenges[challengeKey];\n\n // Mark the challenge as resolved as it was successfully defeated\n challenge.resolved = true;\n\n // Send the ether deposited by the challenger to the treasury\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls\n 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 emit FraudChallengeDefeated(walletPubKeyHash, sighash);\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after a\n /// fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes)\n /// @param sighash The hash that was used to produce the ECDSA signature\n /// that is the subject of the fraud claim. This hash is constructed\n /// by applying double SHA-256 over a serialized subset of the\n /// transaction. The exact subset used as hash preimage depends on\n /// the transaction input the signature is produced for. See BIP-143\n /// for reference\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` must identify an open fraud\n /// challenge\n /// - the amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported\n function notifyChallengeDefeatTimeout(\n Data storage self,\n bytes calldata walletPublicKey,\n bytes32 sighash\n ) external {\n uint256 challengeKey = uint256(\n keccak256(abi.encodePacked(walletPublicKey, sighash))\n );\n\n FraudChallenge storage challenge = self.challenges[challengeKey];\n require(challenge.reportedAt > 0, \"Fraud challenge does not exist\");\n require(\n !challenge.resolved,\n \"Fraud challenge has already been resolved\"\n );\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp >=\n challenge.reportedAt + self.challengeDefeatTimeout,\n \"Fraud challenge defeat period did not time out yet\"\n );\n\n // TODO: Call notifyFraud from Wallets library\n // TODO: Reward the challenger\n\n challenge.resolved = true;\n\n // Return the ether deposited by the challenger\n /* solhint-disable avoid-low-level-calls */\n // slither-disable-next-line low-level-calls\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 emit FraudChallengeDefeatTimedOut(walletPubKeyHash, sighash);\n }\n\n /// @notice Sets the new value for the `slashingAmount` parameter.\n /// @param _newSlashingAmount the new value for `slashingAmount`\n function setSlashingAmount(Data storage self, uint256 _newSlashingAmount)\n external\n {\n self.slashingAmount = _newSlashingAmount;\n emit FraudSlashingAmountUpdated(_newSlashingAmount);\n }\n\n /// @notice Sets the new value for the `notifierRewardMultiplier` parameter.\n /// @param _newNotifierRewardMultiplier the new value for `notifierRewardMultiplier`\n /// @dev The value of `notifierRewardMultiplier` must be <= 100.\n function setNotifierRewardMultiplier(\n Data storage self,\n uint256 _newNotifierRewardMultiplier\n ) external {\n require(\n _newNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be <= 100\"\n );\n self.notifierRewardMultiplier = _newNotifierRewardMultiplier;\n emit FraudNotifierRewardMultiplierUpdated(_newNotifierRewardMultiplier);\n }\n\n /// @notice Sets the new value for the `challengeDefeatTimeout` parameter.\n /// @param _newChallengeDefeatTimeout the new value for `challengeDefeatTimeout`\n /// @dev The value of `challengeDefeatTimeout` must be > 0.\n function setChallengeDefeatTimeout(\n Data storage self,\n uint256 _newChallengeDefeatTimeout\n ) external {\n require(\n _newChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be > 0\"\n );\n self.challengeDefeatTimeout = _newChallengeDefeatTimeout;\n emit FraudChallengeDefeatTimeoutUpdated(_newChallengeDefeatTimeout);\n }\n\n /// @notice Sets the new value for the `challengeDepositAmount` parameter.\n /// @param _newChallengeDepositAmount the new value for `challengeDepositAmount`\n /// @dev The value of `challengeDepositAmount` must be > 0.\n function setChallengeDepositAmount(\n Data storage self,\n uint256 _newChallengeDepositAmount\n ) external {\n require(\n _newChallengeDepositAmount > 0,\n \"Fraud challenge deposit amount must be > 0\"\n );\n self.challengeDepositAmount = _newChallengeDepositAmount;\n emit FraudChallengeDepositAmountUpdated(_newChallengeDepositAmount);\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"
|
|
165
|
+
},
|
|
160
166
|
"@keep-network/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol": {
|
|
161
167
|
"content": "pragma solidity ^0.8.4;\n\n/** @title CheckBitcoinSigs */\n/** @author Summa (https://summa.one) */\n\nimport {BytesLib} from \"./BytesLib.sol\";\nimport {BTCUtils} from \"./BTCUtils.sol\";\n\n\nlibrary CheckBitcoinSigs {\n\n using BytesLib for bytes;\n using BTCUtils for bytes;\n\n /// @notice Derives an Ethereum Account address from a pubkey\n /// @dev The address is the last 20 bytes of the keccak256 of the address\n /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array\n /// @return The account address\n function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) {\n require(_pubkey.length == 64, \"Pubkey must be 64-byte raw, uncompressed key.\");\n\n // keccak hash of uncompressed unprefixed pubkey\n bytes32 _digest = keccak256(_pubkey);\n return address(uint160(uint256(_digest)));\n }\n\n /// @notice Calculates the p2wpkh output script of a pubkey\n /// @dev Compresses keys to 33 bytes as required by Bitcoin\n /// @param _pubkey The public key, compressed or uncompressed\n /// @return The p2wkph output script\n function p2wpkhFromPubkey(bytes memory _pubkey) internal view returns (bytes memory) {\n bytes memory _compressedPubkey;\n uint8 _prefix;\n\n if (_pubkey.length == 64) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(0));\n } else if (_pubkey.length == 65) {\n _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2;\n _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice32(1));\n } else {\n _compressedPubkey = _pubkey;\n }\n\n require(_compressedPubkey.length == 33, \"Witness PKH requires compressed keys\");\n\n bytes20 _pubkeyHash = _compressedPubkey.hash160View();\n return abi.encodePacked(hex\"0014\", _pubkeyHash);\n }\n\n /// @notice checks a signed message's validity under a pubkey\n /// @dev does this using ecrecover because Ethereum has no soul\n /// @param _pubkey the public key to check (64 bytes)\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkSig(\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal pure returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n address _expected = accountFromPubkey(_pubkey);\n address _actual = ecrecover(_digest, _v, _r, _s);\n return _actual == _expected;\n }\n\n /// @notice checks a signed message against a bitcoin p2wpkh output script\n /// @dev does this my verifying the p2wpkh matches an ethereum account\n /// @param _p2wpkhOutputScript the bitcoin output script\n /// @param _pubkey the uncompressed, unprefixed public key to check\n /// @param _digest the message digest signed\n /// @param _v the signature recovery value\n /// @param _r the signature r value\n /// @param _s the signature s value\n /// @return true if signature is valid, else false\n function checkBitcoinSig(\n bytes memory _p2wpkhOutputScript,\n bytes memory _pubkey,\n bytes32 _digest,\n uint8 _v,\n bytes32 _r,\n bytes32 _s\n ) internal view returns (bool) {\n require(_pubkey.length == 64, \"Requires uncompressed unprefixed pubkey\");\n\n bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer?\n if (!_isExpectedSigner) {return false;}\n\n bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s);\n return _sigResult;\n }\n\n /// @notice checks if a message is the sha256 preimage of a digest\n /// @dev this is NOT the hash256! this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isSha256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return sha256(_candidate) == _digest;\n }\n\n /// @notice checks if a message is the keccak256 preimage of a digest\n /// @dev this step is necessary for ECDSA security!\n /// @param _digest the digest\n /// @param _candidate the purported preimage\n /// @return true if the preimage matches the digest, else false\n function isKeccak256Preimage(\n bytes memory _candidate,\n bytes32 _digest\n ) internal pure returns (bool) {\n return keccak256(_candidate) == _digest;\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputScript the length-prefixed output script\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhSpendSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes memory _outputScript // lenght-prefixed output script\n ) internal view returns (bytes32) {\n // Fixes elements to easily make a 1-in 1-out sighash digest\n // Does not support timelocks\n // bytes memory _scriptCode = abi.encodePacked(\n // hex\"1976a914\", // length, dup, hash160, pkh_length\n // _inputPKH,\n // hex\"88ac\"); // equal, checksig\n\n bytes32 _hashOutputs = abi.encodePacked(\n _outputValue, // 8-byte LE\n _outputScript).hash256View();\n\n bytes memory _sighashPreimage = abi.encodePacked(\n hex\"01000000\", // version\n _outpoint.hash256View(), // hashPrevouts\n hex\"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9\", // hashSequence(00000000)\n _outpoint, // outpoint\n // p2wpkh script code\n hex\"1976a914\", // length, dup, hash160, pkh_length\n _inputPKH,\n hex\"88ac\", // equal, checksig\n // end script code\n _inputValue, // value of the input in 8-byte LE\n hex\"00000000\", // input nSequence\n _hashOutputs, // hash of the single output\n hex\"00000000\", // nLockTime\n hex\"01000000\" // SIGHASH_ALL\n );\n return _sighashPreimage.hash256View();\n }\n\n /// @notice calculates the signature hash of a Bitcoin transaction with the provided details\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function wpkhToWpkhSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhSpendSighash(\n _outpoint,\n _inputPKH,\n _inputValue,\n _outputValue,\n abi.encodePacked(\n hex\"160014\", // wpkh tag\n _outputPKH)\n );\n }\n\n /// @notice Preserved for API compatibility with older version\n /// @dev documented in bip143. many values are hardcoded here\n /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index)\n /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey))\n /// @param _inputValue the value of the input in satoshi\n /// @param _outputValue the value of the output in satoshi\n /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey))\n /// @return the double-sha256 (hash256) signature hash as defined by bip143\n function oneInputOneOutputSighash(\n bytes memory _outpoint, // 36-byte UTXO id\n bytes20 _inputPKH, // 20-byte hash160\n bytes8 _inputValue, // 8-byte LE\n bytes8 _outputValue, // 8-byte LE\n bytes20 _outputPKH // 20-byte hash160\n ) internal view returns (bytes32) {\n return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH);\n }\n\n}\n"
|
|
162
168
|
},
|