@keep-network/tbtc-v2 0.1.1-dev.35 → 0.1.1-dev.36
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/{922339b8aca537314dc3d35162317588.json → 4718d6e944ad9d1fc247efda870cf51a.json} +1 -1
- 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 +2 -2
- package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
- package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
- 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 +1 -1
- package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +1 -1
- 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 +164 -75
- package/package.json +1 -1
|
@@ -143,7 +143,7 @@
|
|
|
143
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\";\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"
|
|
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 /// @notice Represents temporary information needed during the processing of\n /// the redemption Bitcoin transaction outputs. This structure is an\n /// internal one and should not be exported outside of the redemption\n /// transaction processing code.\n /// @dev Allows to mitigate \"stack too deep\" errors on EVM.\n struct RedemptionTxOutputsProcessingInfo {\n // The first output starting index in the transaction.\n uint256 outputStartingIndex;\n // The number of outputs in the transaction.\n uint256 outputsCount;\n // P2PKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2PKHScriptKeccak;\n // P2WPKH script for the wallet. Needed to determine the change output.\n bytes32 walletP2WPKHScriptKeccak;\n }\n\n 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 return\n processRedemptionTxOutputs(\n redemptionTxOutputVector,\n walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo(\n outputStartingIndex,\n outputsCount,\n walletP2PKHScriptKeccak,\n walletP2WPKHScriptKeccak\n )\n );\n }\n\n /// @notice Processes all outputs from the redemption transaction. Tries to\n /// identify output as a change output, pending redemption request\n // or reported redemption. Reverts if one of the outputs cannot be\n /// recognized properly. Marks each request as processed by removing\n /// them from `pendingRedemptions` mapping.\n /// @param redemptionTxOutputVector Bitcoin redemption transaction output\n /// vector. This function assumes vector's structure is valid so it\n /// must be validated using e.g. `BTCUtils.validateVout` function\n /// before it is passed here\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output\n /// starting index, the number of outputs and possible wallet change\n /// P2PKH and P2WPKH scripts.\n function processRedemptionTxOutputs(\n bytes memory redemptionTxOutputVector,\n bytes20 walletPubKeyHash,\n RedemptionTxOutputsProcessingInfo memory processInfo\n ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {\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 < processInfo.outputsCount; i++) {\n // TODO: Check if we can optimize gas costs by adding\n // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`\n // in order to avoid allocating bytes in memory.\n uint256 outputLength = redemptionTxOutputVector\n .determineOutputLengthAt(processInfo.outputStartingIndex);\n bytes memory output = redemptionTxOutputVector.slice(\n processInfo.outputStartingIndex,\n outputLength\n );\n\n // Extract the value from given output.\n uint64 outputValue = output.extractValue();\n // The output consists of an 8-byte value and a variable length\n // script. To extract that script we slice the output starting from\n // 9th byte until the end.\n bytes memory outputScript = output.slice(8, output.length - 8);\n\n if (\n resultInfo.changeValue == 0 &&\n (keccak256(outputScript) ==\n processInfo.walletP2PKHScriptKeccak ||\n keccak256(outputScript) ==\n processInfo.walletP2WPKHScriptKeccak) &&\n outputValue > 0\n ) {\n // If we entered here, that means the change output with a\n // proper non-zero value was found.\n resultInfo.changeIndex = uint32(i);\n resultInfo.changeValue = outputValue;\n } else {\n // If we entered here, that the means the given output is\n // supposed to represent a redemption.\n (\n uint64 burnableValue,\n uint64 treasuryFee\n ) = processNonChangeRedemptionTxOutput(\n walletPubKeyHash,\n outputScript,\n outputValue\n );\n resultInfo.totalBurnableValue += burnableValue;\n resultInfo.totalTreasuryFee += treasuryFee;\n processedRedemptionsCount++;\n }\n\n // Make the `outputStartingIndex` pointing to the next output by\n // increasing it by current output's length.\n processInfo.outputStartingIndex += outputLength;\n }\n\n // Protect against the cases when there is only a single change output\n // referring back to the wallet PKH and just burning main UTXO value\n // for transaction fees.\n require(\n processedRedemptionsCount > 0,\n \"Redemption transaction must process at least one redemption\"\n );\n }\n\n /// @notice Processes a single redemption transaction output. Tries to\n /// identify output as a pending redemption request or reported\n /// redemption timeout. Output script passed to this function must\n /// not be the change output. Such output needs to be identified\n /// separately before calling this function.\n /// Reverts if output is neither requested pending redemption nor\n /// requested and reported timed-out redemption.\n /// This function also marks each pending request as processed by\n /// removing it from `pendingRedemptions` mapping.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @param outputScript Non-change output script to be processed\n /// @param outputValue Value of the output being processed\n /// @return burnableValue The value burnable as a result of processing this\n /// single redemption output. This value needs to be summed up with\n /// burnable values of all other outputs to evaluate total burnable\n /// value for the entire redemption transaction. This value is 0\n /// for a timed-out redemption request.\n /// @return treasuryFee The treasury fee from this single redemption output.\n /// This value needs to be summed up with treasury fees of all other\n /// outputs to evaluate the total treasury fee for the entire\n /// redemption transaction. This value is 0 for a timed-out\n /// redemption request.\n function processNonChangeRedemptionTxOutput(\n bytes20 walletPubKeyHash,\n bytes memory outputScript,\n uint64 outputValue\n ) internal returns (uint64 burnableValue, uint64 treasuryFee) {\n // This function should be called only if the given output is\n // supposed to represent a redemption. Build the redemption key\n // to perform that check.\n uint256 redemptionKey = uint256(\n keccak256(abi.encodePacked(walletPubKeyHash, outputScript))\n );\n\n if (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 burnableValue = redeemableAmount;\n // Add the request's treasury fee to the total treasury fee\n // value the Bridge will transfer to the treasury.\n treasuryFee = request.treasuryFee;\n // Request was properly handled so remove its redemption\n // key from the mapping to make it reusable for further\n // requests.\n delete pendingRedemptions[redemptionKey];\n } else {\n // If we entered here, the output is not a redemption\n // request but there is still a chance the given output is\n // related to a reported timed out redemption request.\n // If so, check if the output value matches the request\n // amount to confirm this is an overdue request fulfillment\n // then bypass this output and process the subsequent\n // ones. That also means the wallet was already punished\n // for the inactivity. Otherwise, just revert.\n RedemptionRequest storage request = timedOutRedemptions[\n redemptionKey\n ];\n\n require(\n request.requestedAt != 0,\n \"Output is a non-requested redemption\"\n );\n\n uint64 redeemableAmount = request.requestedAmount -\n request.treasuryFee;\n\n require(\n redeemableAmount - request.txMaxFee <= outputValue &&\n outputValue <= redeemableAmount,\n \"Output value is not within the acceptable range of the timed out request\"\n );\n }\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.\n /// The results of calling this function: the pending redemptions\n /// value for the wallet will be decreased by the requested amount\n /// (minus treasury fee), the tokens taken from the redeemer on\n /// redemption request will be returned to the redeemer, the request\n /// will be moved from pending redemptions to timed-out redemptions.\n /// If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed.\n /// Additionally, if the state of wallet is `Live`, the wallet will\n /// be closed or marked as `MovingFunds` (depending on the presence\n /// or absence of the wallet's main UTXO) and the wallet will no\n /// longer be marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH)\n /// @dev Requirements:\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n 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"
|