@keep-network/tbtc-v2 0.1.1-dev.9 → 0.1.1-dev.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/Bank.json +807 -0
  3. package/artifacts/Bridge.json +2300 -0
  4. package/artifacts/Deposit.json +117 -0
  5. package/artifacts/DepositSweep.json +77 -0
  6. package/artifacts/EcdsaDkgValidator.json +532 -0
  7. package/artifacts/EcdsaInactivity.json +156 -0
  8. package/artifacts/EcdsaSortitionPool.json +1004 -0
  9. package/artifacts/Fraud.json +164 -0
  10. package/artifacts/KeepRegistry.json +99 -0
  11. package/artifacts/KeepStake.json +286 -0
  12. package/artifacts/KeepToken.json +711 -0
  13. package/artifacts/KeepTokenStaking.json +483 -0
  14. package/artifacts/MovingFunds.json +249 -0
  15. package/artifacts/NuCypherStakingEscrow.json +256 -0
  16. package/artifacts/NuCypherToken.json +711 -0
  17. package/artifacts/RandomBeaconStub.json +141 -0
  18. package/artifacts/Redemption.json +174 -0
  19. package/artifacts/ReimbursementPool.json +509 -0
  20. package/artifacts/Relay.json +123 -0
  21. package/artifacts/T.json +1148 -0
  22. package/artifacts/TBTC.json +27 -26
  23. package/artifacts/TBTCToken.json +27 -26
  24. package/artifacts/TBTCVault.json +691 -0
  25. package/artifacts/TokenStaking.json +2288 -0
  26. package/artifacts/TokenholderGovernor.json +1795 -0
  27. package/artifacts/TokenholderTimelock.json +1058 -0
  28. package/artifacts/VendingMachine.json +31 -30
  29. package/artifacts/VendingMachineKeep.json +400 -0
  30. package/artifacts/VendingMachineNuCypher.json +400 -0
  31. package/artifacts/WalletRegistry.json +1843 -0
  32. package/artifacts/WalletRegistryGovernance.json +2754 -0
  33. package/artifacts/Wallets.json +186 -0
  34. package/artifacts/solcInputs/2522ad78efeee521d6cb3252a08f9f62.json +314 -0
  35. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  36. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  37. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  38. package/build/contracts/bank/Bank.sol/Bank.json +27 -4
  39. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +4 -0
  40. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.json +34 -0
  41. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  42. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  43. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  44. package/build/contracts/bridge/Bridge.sol/Bridge.json +2547 -196
  45. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  46. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +226 -0
  47. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  48. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  49. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +4 -0
  50. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +30 -0
  51. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  52. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  53. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  54. package/build/contracts/bridge/Fraud.sol/Fraud.json +86 -0
  55. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +4 -0
  56. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.json +10 -0
  57. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  58. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  59. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  60. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +138 -0
  61. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +4 -0
  62. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +10 -0
  63. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +4 -0
  64. package/build/contracts/bridge/Redemption.sol/Redemption.json +92 -0
  65. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  66. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  67. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  68. package/build/contracts/bridge/Wallets.sol/Wallets.json +112 -0
  69. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  70. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  71. package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +4 -0
  72. package/build/contracts/vault/DonationVault.sol/DonationVault.json +108 -0
  73. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  74. package/build/contracts/vault/IVault.sol/IVault.json +24 -1
  75. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  76. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +295 -9
  77. package/contracts/GovernanceUtils.sol +4 -4
  78. package/contracts/bank/Bank.sol +119 -57
  79. package/contracts/bank/IReceiveBalanceApproval.sol +45 -0
  80. package/contracts/bridge/BitcoinTx.sol +232 -10
  81. package/contracts/bridge/Bridge.sol +1692 -244
  82. package/contracts/bridge/BridgeState.sol +739 -0
  83. package/contracts/bridge/Deposit.sol +269 -0
  84. package/contracts/bridge/DepositSweep.sol +571 -0
  85. package/contracts/bridge/EcdsaLib.sol +45 -0
  86. package/contracts/bridge/Fraud.sol +604 -0
  87. package/contracts/bridge/Heartbeat.sol +112 -0
  88. package/contracts/bridge/IRelay.sol +28 -0
  89. package/contracts/bridge/MovingFunds.sol +1089 -0
  90. package/contracts/bridge/Redemption.sol +1021 -0
  91. package/contracts/bridge/VendingMachine.sol +2 -2
  92. package/contracts/bridge/Wallets.sol +553 -0
  93. package/contracts/hardhat-dependency-compiler/.hardhat-dependency-compiler +1 -0
  94. package/contracts/hardhat-dependency-compiler/@keep-network/ecdsa/contracts/WalletRegistry.sol +3 -0
  95. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol +3 -0
  96. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol +3 -0
  97. package/contracts/token/TBTC.sol +1 -1
  98. package/contracts/vault/DonationVault.sol +125 -0
  99. package/contracts/vault/IVault.sol +19 -13
  100. package/contracts/vault/TBTCVault.sol +200 -23
  101. package/deploy/00_resolve_relay.ts +28 -0
  102. package/deploy/{03_transfer_roles.ts → 03_transfer_vending_machine_roles.ts} +1 -1
  103. package/deploy/04_deploy_bank.ts +27 -0
  104. package/deploy/05_deploy_bridge.ts +80 -0
  105. package/deploy/06_deploy_tbtc_vault.ts +30 -0
  106. package/deploy/07_bank_update_bridge.ts +19 -0
  107. package/deploy/08_transfer_bank_ownership.ts +15 -0
  108. package/deploy/09_transfer_tbtc_vault_ownership.ts +15 -0
  109. package/deploy/10_transfer_bridge_governance.ts +20 -0
  110. package/deploy/11_initialize_wallet_owner.ts +18 -0
  111. package/deploy/11_transfer_proxy_admin_ownership.ts +30 -0
  112. package/deploy/12_deploy_proxy_admin_with_deputy.ts +33 -0
  113. package/export.json +15771 -443
  114. package/package.json +34 -26
  115. package/artifacts/solcInputs/58d5b3ee7688835879381470de985d6b.json +0 -128
@@ -0,0 +1,1021 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity ^0.8.9;
17
+
18
+ import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
19
+ import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
20
+
21
+ import "./BitcoinTx.sol";
22
+ import "./BridgeState.sol";
23
+ import "./Wallets.sol";
24
+
25
+ import "../bank/Bank.sol";
26
+
27
+ /// @notice Aggregates functions common to the redemption transaction proof
28
+ /// validation and to the moving funds transaction proof validation.
29
+ library OutboundTx {
30
+ using BTCUtils for bytes;
31
+
32
+ /// @notice Checks whether an outbound Bitcoin transaction performed from
33
+ /// the given wallet has an input vector that contains a single
34
+ /// input referring to the wallet's main UTXO. Marks that main UTXO
35
+ /// as correctly spent if the validation succeeds. Reverts otherwise.
36
+ /// There are two outbound transactions from a wallet possible: a
37
+ /// redemption transaction or a moving funds to another wallet
38
+ /// transaction.
39
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input
40
+ /// vector. This function assumes vector's structure is valid so it
41
+ /// must be validated using e.g. `BTCUtils.validateVin` function
42
+ /// before it is passed here.
43
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
44
+ /// the Ethereum chain.
45
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
46
+ // HASH160 over the compressed ECDSA public key) of the wallet which
47
+ /// performed the outbound transaction.
48
+ function processWalletOutboundTxInput(
49
+ BridgeState.Storage storage self,
50
+ bytes memory walletOutboundTxInputVector,
51
+ BitcoinTx.UTXO calldata mainUtxo,
52
+ bytes20 walletPubKeyHash
53
+ ) internal {
54
+ // Assert that main UTXO for passed wallet exists in storage.
55
+ bytes32 mainUtxoHash = self
56
+ .registeredWallets[walletPubKeyHash]
57
+ .mainUtxoHash;
58
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
59
+
60
+ // Assert that passed main UTXO parameter is the same as in storage and
61
+ // can be used for further processing.
62
+ require(
63
+ keccak256(
64
+ abi.encodePacked(
65
+ mainUtxo.txHash,
66
+ mainUtxo.txOutputIndex,
67
+ mainUtxo.txOutputValue
68
+ )
69
+ ) == mainUtxoHash,
70
+ "Invalid main UTXO data"
71
+ );
72
+
73
+ // Assert that the single outbound transaction input actually
74
+ // refers to the wallet's main UTXO.
75
+ (
76
+ bytes32 outpointTxHash,
77
+ uint32 outpointIndex
78
+ ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);
79
+ require(
80
+ mainUtxo.txHash == outpointTxHash &&
81
+ mainUtxo.txOutputIndex == outpointIndex,
82
+ "Outbound transaction input must point to the wallet's main UTXO"
83
+ );
84
+
85
+ // Main UTXO used as an input, mark it as spent.
86
+ self.spentMainUTXOs[
87
+ uint256(
88
+ keccak256(
89
+ abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
90
+ )
91
+ )
92
+ ] = true;
93
+ }
94
+
95
+ /// @notice Parses the input vector of an outbound Bitcoin transaction
96
+ /// performed from the given wallet. It extracts the single input
97
+ /// then the transaction hash and output index from its outpoint.
98
+ /// There are two outbound transactions from a wallet possible: a
99
+ /// redemption transaction or a moving funds to another wallet
100
+ /// transaction.
101
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction input
102
+ /// vector. This function assumes vector's structure is valid so it
103
+ /// must be validated using e.g. `BTCUtils.validateVin` function
104
+ /// before it is passed here.
105
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
106
+ /// pointed in the input's outpoint.
107
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
108
+ /// which is pointed in the input's outpoint.
109
+ function parseWalletOutboundTxInput(
110
+ bytes memory walletOutboundTxInputVector
111
+ ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {
112
+ // To determine the total number of Bitcoin transaction inputs,
113
+ // we need to parse the compactSize uint (VarInt) the input vector is
114
+ // prepended by. That compactSize uint encodes the number of vector
115
+ // elements using the format presented in:
116
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
117
+ // We don't need asserting the compactSize uint is parseable since it
118
+ // was already checked during `validateVin` validation.
119
+ // See `BitcoinTx.inputVector` docs for more details.
120
+ (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();
121
+ require(
122
+ inputsCount == 1,
123
+ "Outbound transaction must have a single input"
124
+ );
125
+
126
+ bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);
127
+
128
+ outpointTxHash = input.extractInputTxIdLE();
129
+
130
+ outpointIndex = BTCUtils.reverseUint32(
131
+ uint32(input.extractTxIndexLE())
132
+ );
133
+
134
+ // There is only one input in the transaction. Input has an outpoint
135
+ // field that is a reference to the transaction being spent (see
136
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
137
+ // to spend (`outpointTxHash`) and the index of the specific output
138
+ // from that transaction (`outpointIndex`).
139
+ return (outpointTxHash, outpointIndex);
140
+ }
141
+ }
142
+
143
+ /// @title Bridge redemption
144
+ /// @notice The library handles the logic for redeeming Bitcoin balances from
145
+ /// the Bridge.
146
+ /// @dev To initiate a redemption, a user with a Bank balance supplies
147
+ /// a Bitcoin address. Then, the system calculates the redemption fee, and
148
+ /// releases balance to the provided Bitcoin address. Just like in case of
149
+ /// sweeps of revealed deposits, redemption requests are processed in
150
+ /// batches and require SPV proof to be submitted to the Bridge.
151
+ library Redemption {
152
+ using BridgeState for BridgeState.Storage;
153
+ using Wallets for BridgeState.Storage;
154
+ using BitcoinTx for BridgeState.Storage;
155
+
156
+ using BTCUtils for bytes;
157
+ using BytesLib for bytes;
158
+
159
+ /// @notice Represents a redemption request.
160
+ struct RedemptionRequest {
161
+ // ETH address of the redeemer who created the request.
162
+ address redeemer;
163
+ // Requested TBTC amount in satoshi.
164
+ uint64 requestedAmount;
165
+ // Treasury TBTC fee in satoshi at the moment of request creation.
166
+ uint64 treasuryFee;
167
+ // Transaction maximum BTC fee in satoshi at the moment of request
168
+ // creation.
169
+ uint64 txMaxFee;
170
+ // UNIX timestamp the request was created at.
171
+ uint32 requestedAt;
172
+ // This struct doesn't contain `__gap` property as the structure is stored
173
+ // in a mapping, mappings store values in different slots and they are
174
+ // not contiguous with other values.
175
+ }
176
+
177
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
178
+ /// outputs processing.
179
+ struct RedemptionTxOutputsInfo {
180
+ // Total TBTC value in satoshi that should be burned by the Bridge.
181
+ // It includes the total amount of all BTC redeemed in the transaction
182
+ // and the fee paid to BTC miners for the redemption transaction.
183
+ uint64 totalBurnableValue;
184
+ // Total TBTC value in satoshi that should be transferred to
185
+ // the treasury. It is a sum of all treasury fees paid by all
186
+ // redeemers included in the redemption transaction.
187
+ uint64 totalTreasuryFee;
188
+ // Index of the change output. The change output becomes
189
+ // the new main wallet's UTXO.
190
+ uint32 changeIndex;
191
+ // Value in satoshi of the change output.
192
+ uint64 changeValue;
193
+ // This struct doesn't contain `__gap` property as the structure is not
194
+ // stored, it is used as a function's memory argument.
195
+ }
196
+
197
+ /// @notice Represents temporary information needed during the processing of
198
+ /// the redemption Bitcoin transaction outputs. This structure is an
199
+ /// internal one and should not be exported outside of the redemption
200
+ /// transaction processing code.
201
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
202
+ struct RedemptionTxOutputsProcessingInfo {
203
+ // The first output starting index in the transaction.
204
+ uint256 outputStartingIndex;
205
+ // The number of outputs in the transaction.
206
+ uint256 outputsCount;
207
+ // P2PKH script for the wallet. Needed to determine the change output.
208
+ bytes32 walletP2PKHScriptKeccak;
209
+ // P2WPKH script for the wallet. Needed to determine the change output.
210
+ bytes32 walletP2WPKHScriptKeccak;
211
+ // This struct doesn't contain `__gap` property as the structure is not
212
+ // stored, it is used as a function's memory argument.
213
+ }
214
+
215
+ event RedemptionRequested(
216
+ bytes20 indexed walletPubKeyHash,
217
+ bytes redeemerOutputScript,
218
+ address indexed redeemer,
219
+ uint64 requestedAmount,
220
+ uint64 treasuryFee,
221
+ uint64 txMaxFee
222
+ );
223
+
224
+ event RedemptionsCompleted(
225
+ bytes20 indexed walletPubKeyHash,
226
+ bytes32 redemptionTxHash
227
+ );
228
+
229
+ event RedemptionTimedOut(
230
+ bytes20 indexed walletPubKeyHash,
231
+ bytes redeemerOutputScript
232
+ );
233
+
234
+ /// @notice Requests redemption of the given amount from the specified
235
+ /// wallet to the redeemer Bitcoin output script.
236
+ /// This function handles the simplest case, where balance owner is
237
+ /// the redeemer.
238
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
239
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
240
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
241
+ /// the Ethereum chain.
242
+ /// @param balanceOwner The address of the Bank balance owner whose balance
243
+ /// is getting redeemed. Balance owner address is stored as
244
+ /// a redemeer address who will be able co claim back the Bank
245
+ /// balance if anything goes wrong during the redemption.
246
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
247
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
248
+ /// redeemed BTC.
249
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
250
+ /// that is taken from the `balanceOwner` upon request.
251
+ /// Once the request is handled, the actual amount of BTC locked
252
+ /// on the redeemer output script will be always lower than this value
253
+ /// since the treasury and Bitcoin transaction fees must be incurred.
254
+ /// The minimal amount satisfying the request can be computed as:
255
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
256
+ /// Fees values are taken at the moment of request creation.
257
+ /// @dev Requirements:
258
+ /// - Wallet behind `walletPubKeyHash` must be live,
259
+ /// - `mainUtxo` components must point to the recent main UTXO
260
+ /// of the given wallet, as currently known on the Ethereum chain,
261
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
262
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
263
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
264
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
265
+ /// used for only one pending request at the same time,
266
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
267
+ /// - Balance owner must make an allowance in the Bank that the Bridge
268
+ /// contract can spend the given `amount`.
269
+ function requestRedemption(
270
+ BridgeState.Storage storage self,
271
+ bytes20 walletPubKeyHash,
272
+ BitcoinTx.UTXO calldata mainUtxo,
273
+ address balanceOwner,
274
+ bytes calldata redeemerOutputScript,
275
+ uint64 amount
276
+ ) external {
277
+ requestRedemption(
278
+ self,
279
+ walletPubKeyHash,
280
+ mainUtxo,
281
+ balanceOwner,
282
+ balanceOwner,
283
+ redeemerOutputScript,
284
+ amount
285
+ );
286
+ }
287
+
288
+ /// @notice Requests redemption of the given amount from the specified
289
+ /// wallet to the redeemer Bitcoin output script. Used by
290
+ /// `Bridge.receiveBalanceApproval`. Can handle more complex cases
291
+ /// where balance owner may be someone else than the redeemer.
292
+ /// @param balanceOwner The address of the Bank balance owner whose balance
293
+ /// is getting redeemed.
294
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
295
+ /// that is taken from the `balanceOwner` upon request.
296
+ /// Once the request is handled, the actual amount of BTC locked
297
+ /// on the redeemer output script will be always lower than this value
298
+ /// since the treasury and Bitcoin transaction fees must be incurred.
299
+ /// The minimal amount satisfying the request can be computed as:
300
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
301
+ /// Fees values are taken at the moment of request creation.
302
+ /// @param redemptionData ABI-encoded redemption data:
303
+ /// [
304
+ /// address redeemer,
305
+ /// bytes20 walletPubKeyHash,
306
+ /// bytes32 mainUtxoTxHash,
307
+ /// uint32 mainUtxoTxOutputIndex,
308
+ /// uint64 mainUtxoTxOutputValue,
309
+ /// bytes redeemerOutputScript
310
+ /// ]
311
+ ///
312
+ /// - redeemer: The Ethereum address of the redeemer who will be able
313
+ /// to claim Bank balance if anything goes wrong during the redemption.
314
+ /// In the most basic case, when someone redeems their Bitcoin
315
+ /// balance from the Bank, `balanceOwner` is the same as `redemeer`.
316
+ /// However, when a Vault is redeeming part of its balance for some
317
+ /// redeemer address (for example, someone who has earlier deposited
318
+ /// into that Vault), `balanceOwner` is the Vault, and `redemeer` is
319
+ /// the address for which the vault is redeeming its balance to,
320
+ /// - walletPubKeyHash: The 20-byte wallet public key hash (computed
321
+ /// using Bitcoin HASH160 over the compressed ECDSA public key),
322
+ /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as
323
+ /// currently known on the Ethereum chain,
324
+ /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output
325
+ /// index, as currently known on Ethereum chain,
326
+ /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output
327
+ /// value, as currently known on Ethereum chain,
328
+ /// - redeemerOutputScript The redeemer's length-prefixed output
329
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
330
+ /// redeemed BTC.
331
+ /// @dev Requirements:
332
+ /// - Wallet behind `walletPubKeyHash` must be live,
333
+ /// - `mainUtxo*` components must point to the recent main UTXO
334
+ /// of the given wallet, as currently known on the Ethereum chain,
335
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
336
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
337
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
338
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
339
+ /// used for only one pending request at the same time,
340
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
341
+ /// - Balance owner must make an allowance in the Bank that the Bridge
342
+ /// contract can spend the given `amount`.
343
+ function requestRedemption(
344
+ BridgeState.Storage storage self,
345
+ address balanceOwner,
346
+ uint64 amount,
347
+ bytes calldata redemptionData
348
+ ) external {
349
+ (
350
+ address redeemer,
351
+ bytes20 walletPubKeyHash,
352
+ bytes32 mainUtxoTxHash,
353
+ uint32 mainUtxoTxOutputIndex,
354
+ uint64 mainUtxoTxOutputValue,
355
+ bytes memory redeemerOutputScript
356
+ ) = abi.decode(
357
+ redemptionData,
358
+ (address, bytes20, bytes32, uint32, uint64, bytes)
359
+ );
360
+
361
+ requestRedemption(
362
+ self,
363
+ walletPubKeyHash,
364
+ BitcoinTx.UTXO(
365
+ mainUtxoTxHash,
366
+ mainUtxoTxOutputIndex,
367
+ mainUtxoTxOutputValue
368
+ ),
369
+ balanceOwner,
370
+ redeemer,
371
+ redeemerOutputScript,
372
+ amount
373
+ );
374
+ }
375
+
376
+ /// @notice Requests redemption of the given amount from the specified
377
+ /// wallet to the redeemer Bitcoin output script.
378
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
379
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
380
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
381
+ /// the Ethereum chain.
382
+ /// @param balanceOwner The address of the Bank balance owner whose balance
383
+ /// is getting redeemed.
384
+ /// @param redeemer The Ethereum address of the redeemer who will be able to
385
+ /// claim Bank balance if anything goes wrong during the redemption.
386
+ /// In the most basic case, when someone redeems their Bitcoin
387
+ /// balance from the Bank, `balanceOwner` is the same as `redeemer`.
388
+ /// However, when a Vault is redeeming part of its balance for some
389
+ /// redeemer address (for example, someone who has earlier deposited
390
+ /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is
391
+ /// the address for which the vault is redeeming its balance to.
392
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
393
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
394
+ /// redeemed BTC.
395
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
396
+ /// that is taken from the `balanceOwner` upon request.
397
+ /// Once the request is handled, the actual amount of BTC locked
398
+ /// on the redeemer output script will be always lower than this value
399
+ /// since the treasury and Bitcoin transaction fees must be incurred.
400
+ /// The minimal amount satisfying the request can be computed as:
401
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
402
+ /// Fees values are taken at the moment of request creation.
403
+ /// @dev Requirements:
404
+ /// - Wallet behind `walletPubKeyHash` must be live,
405
+ /// - `mainUtxo` components must point to the recent main UTXO
406
+ /// of the given wallet, as currently known on the Ethereum chain,
407
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
408
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
409
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
410
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
411
+ /// used for only one pending request at the same time,
412
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
413
+ /// - Balance owner must make an allowance in the Bank that the Bridge
414
+ /// contract can spend the given `amount`.
415
+ function requestRedemption(
416
+ BridgeState.Storage storage self,
417
+ bytes20 walletPubKeyHash,
418
+ BitcoinTx.UTXO memory mainUtxo,
419
+ address balanceOwner,
420
+ address redeemer,
421
+ bytes memory redeemerOutputScript,
422
+ uint64 amount
423
+ ) internal {
424
+ Wallets.Wallet storage wallet = self.registeredWallets[
425
+ walletPubKeyHash
426
+ ];
427
+
428
+ require(
429
+ wallet.state == Wallets.WalletState.Live,
430
+ "Wallet must be in Live state"
431
+ );
432
+
433
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
434
+ require(
435
+ mainUtxoHash != bytes32(0),
436
+ "No main UTXO for the given wallet"
437
+ );
438
+ require(
439
+ keccak256(
440
+ abi.encodePacked(
441
+ mainUtxo.txHash,
442
+ mainUtxo.txOutputIndex,
443
+ mainUtxo.txOutputValue
444
+ )
445
+ ) == mainUtxoHash,
446
+ "Invalid main UTXO data"
447
+ );
448
+
449
+ // Validate if redeemer output script is a correct standard type
450
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
451
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
452
+ // a function extracts the payload properly only from standard outputs
453
+ // so if it succeeds, we have a guarantee the redeemer output script
454
+ // is proper. Worth to note `extractHash` ignores the value at all
455
+ // so this is why we can use 0 safely. This way of validation is the
456
+ // same as in tBTC v1.
457
+ bytes memory redeemerOutputScriptPayload = abi
458
+ .encodePacked(bytes8(0), redeemerOutputScript)
459
+ .extractHash();
460
+ require(
461
+ redeemerOutputScriptPayload.length > 0,
462
+ "Redeemer output script must be a standard type"
463
+ );
464
+ // Check if the redeemer output script payload does not point to the
465
+ // wallet public key hash.
466
+ require(
467
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
468
+ keccak256(redeemerOutputScriptPayload),
469
+ "Redeemer output script must not point to the wallet PKH"
470
+ );
471
+
472
+ require(
473
+ amount >= self.redemptionDustThreshold,
474
+ "Redemption amount too small"
475
+ );
476
+
477
+ // The redemption key is built on top of the wallet public key hash
478
+ // and redeemer output script pair. That means there can be only one
479
+ // request asking for redemption from the given wallet to the given
480
+ // BTC script at the same time.
481
+ uint256 redemptionKey = uint256(
482
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
483
+ );
484
+
485
+ // Check if given redemption key is not used by a pending redemption.
486
+ // There is no need to check for existence in `timedOutRedemptions`
487
+ // since the wallet's state is changed to other than Live after
488
+ // first time out is reported so making new requests is not possible.
489
+ // slither-disable-next-line incorrect-equality
490
+ require(
491
+ self.pendingRedemptions[redemptionKey].requestedAt == 0,
492
+ "There is a pending redemption request from this wallet to the same address"
493
+ );
494
+
495
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
496
+ // since the `redemptionDustThreshold` should force that condition
497
+ // to be always true.
498
+ uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0
499
+ ? amount / self.redemptionTreasuryFeeDivisor
500
+ : 0;
501
+ uint64 txMaxFee = self.redemptionTxMaxFee;
502
+
503
+ // The main wallet UTXO's value doesn't include all pending redemptions.
504
+ // To determine if the requested redemption can be performed by the
505
+ // wallet we need to subtract the total value of all pending redemptions
506
+ // from that wallet's main UTXO value. Given that the treasury fee is
507
+ // not redeemed from the wallet, we are subtracting it.
508
+ wallet.pendingRedemptionsValue += amount - treasuryFee;
509
+ require(
510
+ mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
511
+ "Insufficient wallet funds"
512
+ );
513
+
514
+ self.pendingRedemptions[redemptionKey] = RedemptionRequest(
515
+ redeemer,
516
+ amount,
517
+ treasuryFee,
518
+ txMaxFee,
519
+ /* solhint-disable-next-line not-rely-on-time */
520
+ uint32(block.timestamp)
521
+ );
522
+
523
+ emit RedemptionRequested(
524
+ walletPubKeyHash,
525
+ redeemerOutputScript,
526
+ redeemer,
527
+ amount,
528
+ treasuryFee,
529
+ txMaxFee
530
+ );
531
+
532
+ self.bank.transferBalanceFrom(balanceOwner, address(this), amount);
533
+ }
534
+
535
+ /// @notice Used by the wallet to prove the BTC redemption transaction
536
+ /// and to make the necessary bookkeeping. Redemption is only
537
+ /// accepted if it satisfies SPV proof.
538
+ ///
539
+ /// The function is performing Bank balance updates by burning
540
+ /// the total redeemed Bitcoin amount from Bridge balance and
541
+ /// transferring the treasury fee sum to the treasury address.
542
+ ///
543
+ /// It is possible to prove the given redemption only one time.
544
+ /// @param redemptionTx Bitcoin redemption transaction data.
545
+ /// @param redemptionProof Bitcoin redemption proof data.
546
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
547
+ /// the Ethereum chain.
548
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
549
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
550
+ /// performed the redemption transaction.
551
+ /// @dev Requirements:
552
+ /// - `redemptionTx` components must match the expected structure. See
553
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
554
+ /// correspond to appropriate Bitcoin transaction fields to produce
555
+ /// a provable transaction hash,
556
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
557
+ /// exactly 1 input that refers to the wallet's main UTXO. That
558
+ /// transaction should have 1..n outputs handling existing pending
559
+ /// redemption requests or pointing to reported timed out requests.
560
+ /// There can be also 1 optional output representing the
561
+ /// change and pointing back to the 20-byte wallet public key hash.
562
+ /// The change should be always present if the redeemed value sum
563
+ /// is lower than the total wallet's BTC balance,
564
+ /// - `redemptionProof` components must match the expected structure.
565
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
566
+ /// field must contain a valid number of block headers, not less
567
+ /// than the `txProofDifficultyFactor` contract constant,
568
+ /// - `mainUtxo` components must point to the recent main UTXO
569
+ /// of the given wallet, as currently known on the Ethereum chain.
570
+ /// Additionally, the recent main UTXO on Ethereum must be set,
571
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
572
+ /// as transaction single input.
573
+ /// Other remarks:
574
+ /// - Putting the change output as the first transaction output can
575
+ /// save some gas because the output processing loop begins each
576
+ /// iteration by checking whether the given output is the change
577
+ /// thus uses some gas for making the comparison. Once the change
578
+ /// is identified, that check is omitted in further iterations.
579
+ function submitRedemptionProof(
580
+ BridgeState.Storage storage self,
581
+ BitcoinTx.Info calldata redemptionTx,
582
+ BitcoinTx.Proof calldata redemptionProof,
583
+ BitcoinTx.UTXO calldata mainUtxo,
584
+ bytes20 walletPubKeyHash
585
+ ) external {
586
+ // The actual transaction proof is performed here. After that point, we
587
+ // can assume the transaction happened on Bitcoin chain and has
588
+ // a sufficient number of confirmations as determined by
589
+ // `txProofDifficultyFactor` constant.
590
+ bytes32 redemptionTxHash = self.validateProof(
591
+ redemptionTx,
592
+ redemptionProof
593
+ );
594
+
595
+ // Process the redemption transaction input. Specifically, check if it
596
+ // refers to the expected wallet's main UTXO.
597
+ OutboundTx.processWalletOutboundTxInput(
598
+ self,
599
+ redemptionTx.inputVector,
600
+ mainUtxo,
601
+ walletPubKeyHash
602
+ );
603
+
604
+ Wallets.Wallet storage wallet = self.registeredWallets[
605
+ walletPubKeyHash
606
+ ];
607
+
608
+ Wallets.WalletState walletState = wallet.state;
609
+ require(
610
+ walletState == Wallets.WalletState.Live ||
611
+ walletState == Wallets.WalletState.MovingFunds,
612
+ "Wallet must be in Live or MovingFunds state"
613
+ );
614
+
615
+ // Process redemption transaction outputs to extract some info required
616
+ // for further processing.
617
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
618
+ self,
619
+ redemptionTx.outputVector,
620
+ walletPubKeyHash
621
+ );
622
+
623
+ if (outputsInfo.changeValue > 0) {
624
+ // If the change value is grater than zero, it means the change
625
+ // output exists and can be used as new wallet's main UTXO.
626
+ wallet.mainUtxoHash = keccak256(
627
+ abi.encodePacked(
628
+ redemptionTxHash,
629
+ outputsInfo.changeIndex,
630
+ outputsInfo.changeValue
631
+ )
632
+ );
633
+ } else {
634
+ // If the change value is zero, it means the change output doesn't
635
+ // exists and no funds left on the wallet. Delete the main UTXO
636
+ // for that wallet to represent that state in a proper way.
637
+ delete wallet.mainUtxoHash;
638
+ }
639
+
640
+ wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
641
+
642
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
643
+
644
+ self.bank.decreaseBalance(outputsInfo.totalBurnableValue);
645
+ self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);
646
+ }
647
+
648
+ /// @notice Processes the Bitcoin redemption transaction output vector.
649
+ /// It extracts each output and tries to identify it as a pending
650
+ /// redemption request, reported timed out request, or change.
651
+ /// Reverts if one of the outputs cannot be recognized properly.
652
+ /// This function also marks each request as processed by removing
653
+ /// them from `pendingRedemptions` mapping.
654
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
655
+ /// vector. This function assumes vector's structure is valid so it
656
+ /// must be validated using e.g. `BTCUtils.validateVout` function
657
+ /// before it is passed here.
658
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
659
+ // HASH160 over the compressed ECDSA public key) of the wallet which
660
+ /// performed the redemption transaction.
661
+ /// @return info Outcomes of the processing.
662
+ function processRedemptionTxOutputs(
663
+ BridgeState.Storage storage self,
664
+ bytes memory redemptionTxOutputVector,
665
+ bytes20 walletPubKeyHash
666
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
667
+ // Determining the total number of redemption transaction outputs in
668
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
669
+ // docs for more details.
670
+ (
671
+ uint256 outputsCompactSizeUintLength,
672
+ uint256 outputsCount
673
+ ) = redemptionTxOutputVector.parseVarInt();
674
+
675
+ // To determine the first output starting index, we must jump over
676
+ // the compactSize uint which prepends the output vector. One byte
677
+ // must be added because `BtcUtils.parseVarInt` does not include
678
+ // compactSize uint tag in the returned length.
679
+ //
680
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
681
+ // returns `0`, so we jump over one byte of compactSize uint.
682
+ //
683
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
684
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
685
+ // tag byte included) so we need to jump over 1+2 bytes of
686
+ // compactSize uint.
687
+ //
688
+ // Please refer `BTCUtils` library and compactSize uint
689
+ // docs in `BitcoinTx` library for more details.
690
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
691
+
692
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
693
+ // scripts that can be used to lock the change. This is done upfront to
694
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
695
+ //
696
+ // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
697
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
698
+ // - 0x19: Byte length of the entire script
699
+ // - 0x76: OP_DUP
700
+ // - 0xa9: OP_HASH160
701
+ // - 0x14: Byte length of the public key hash
702
+ // - 0x88: OP_EQUALVERIFY
703
+ // - 0xac: OP_CHECKSIG
704
+ // which matches the P2PKH structure as per:
705
+ // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
706
+ bytes32 walletP2PKHScriptKeccak = keccak256(
707
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
708
+ );
709
+ // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
710
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
711
+ // - 0x16: Byte length of the entire script
712
+ // - 0x00: OP_0
713
+ // - 0x14: Byte length of the public key hash
714
+ // which matches the P2WPKH structure as per:
715
+ // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
716
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
717
+ abi.encodePacked(hex"160014", walletPubKeyHash)
718
+ );
719
+
720
+ return
721
+ processRedemptionTxOutputs(
722
+ self,
723
+ redemptionTxOutputVector,
724
+ walletPubKeyHash,
725
+ RedemptionTxOutputsProcessingInfo(
726
+ outputStartingIndex,
727
+ outputsCount,
728
+ walletP2PKHScriptKeccak,
729
+ walletP2WPKHScriptKeccak
730
+ )
731
+ );
732
+ }
733
+
734
+ /// @notice Processes all outputs from the redemption transaction. Tries to
735
+ /// identify output as a change output, pending redemption request
736
+ // or reported redemption. Reverts if one of the outputs cannot be
737
+ /// recognized properly. Marks each request as processed by removing
738
+ /// them from `pendingRedemptions` mapping.
739
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
740
+ /// vector. This function assumes vector's structure is valid so it
741
+ /// must be validated using e.g. `BTCUtils.validateVout` function
742
+ /// before it is passed here.
743
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
744
+ // HASH160 over the compressed ECDSA public key) of the wallet which
745
+ /// performed the redemption transaction.
746
+ /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output
747
+ /// starting index, the number of outputs and possible wallet change
748
+ /// P2PKH and P2WPKH scripts.
749
+ function processRedemptionTxOutputs(
750
+ BridgeState.Storage storage self,
751
+ bytes memory redemptionTxOutputVector,
752
+ bytes20 walletPubKeyHash,
753
+ RedemptionTxOutputsProcessingInfo memory processInfo
754
+ ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {
755
+ // Helper flag indicating whether there was at least one redemption
756
+ // output present (redemption must be either pending or reported as
757
+ // timed out).
758
+ bool redemptionPresent = false;
759
+
760
+ // Outputs processing loop.
761
+ for (uint256 i = 0; i < processInfo.outputsCount; i++) {
762
+ // TODO: Check if we can optimize gas costs by adding
763
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
764
+ // in order to avoid allocating bytes in memory.
765
+ // https://github.com/keep-network/tbtc-v2/issues/257
766
+ uint256 outputLength = redemptionTxOutputVector
767
+ .determineOutputLengthAt(processInfo.outputStartingIndex);
768
+ bytes memory output = redemptionTxOutputVector.slice(
769
+ processInfo.outputStartingIndex,
770
+ outputLength
771
+ );
772
+
773
+ // Extract the value from given output.
774
+ uint64 outputValue = output.extractValue();
775
+ // The output consists of an 8-byte value and a variable length
776
+ // script. To extract that script we slice the output starting from
777
+ // 9th byte until the end.
778
+ bytes memory outputScript = output.slice(8, output.length - 8);
779
+
780
+ if (
781
+ resultInfo.changeValue == 0 &&
782
+ (keccak256(outputScript) ==
783
+ processInfo.walletP2PKHScriptKeccak ||
784
+ keccak256(outputScript) ==
785
+ processInfo.walletP2WPKHScriptKeccak) &&
786
+ outputValue > 0
787
+ ) {
788
+ // If we entered here, that means the change output with a
789
+ // proper non-zero value was found.
790
+ resultInfo.changeIndex = uint32(i);
791
+ resultInfo.changeValue = outputValue;
792
+ } else {
793
+ // If we entered here, that the means the given output is
794
+ // supposed to represent a redemption.
795
+ (
796
+ uint64 burnableValue,
797
+ uint64 treasuryFee
798
+ ) = processNonChangeRedemptionTxOutput(
799
+ self,
800
+ walletPubKeyHash,
801
+ outputScript,
802
+ outputValue
803
+ );
804
+ resultInfo.totalBurnableValue += burnableValue;
805
+ resultInfo.totalTreasuryFee += treasuryFee;
806
+ redemptionPresent = true;
807
+ }
808
+
809
+ // Make the `outputStartingIndex` pointing to the next output by
810
+ // increasing it by current output's length.
811
+ processInfo.outputStartingIndex += outputLength;
812
+ }
813
+
814
+ // Protect against the cases when there is only a single change output
815
+ // referring back to the wallet PKH and just burning main UTXO value
816
+ // for transaction fees.
817
+ require(
818
+ redemptionPresent,
819
+ "Redemption transaction must process at least one redemption"
820
+ );
821
+ }
822
+
823
+ /// @notice Processes a single redemption transaction output. Tries to
824
+ /// identify output as a pending redemption request or reported
825
+ /// redemption timeout. Output script passed to this function must
826
+ /// not be the change output. Such output needs to be identified
827
+ /// separately before calling this function.
828
+ /// Reverts if output is neither requested pending redemption nor
829
+ /// requested and reported timed-out redemption.
830
+ /// This function also marks each pending request as processed by
831
+ /// removing them from `pendingRedemptions` mapping.
832
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
833
+ // HASH160 over the compressed ECDSA public key) of the wallet which
834
+ /// performed the redemption transaction.
835
+ /// @param outputScript Non-change output script to be processed.
836
+ /// @param outputValue Value of the output being processed.
837
+ /// @return burnableValue The value burnable as a result of processing this
838
+ /// single redemption output. This value needs to be summed up with
839
+ /// burnable values of all other outputs to evaluate total burnable
840
+ /// value for the entire redemption transaction. This value is 0
841
+ /// for a timed-out redemption request.
842
+ /// @return treasuryFee The treasury fee from this single redemption output.
843
+ /// This value needs to be summed up with treasury fees of all other
844
+ /// outputs to evaluate the total treasury fee for the entire
845
+ /// redemption transaction. This value is 0 for a timed-out
846
+ /// redemption request.
847
+ function processNonChangeRedemptionTxOutput(
848
+ BridgeState.Storage storage self,
849
+ bytes20 walletPubKeyHash,
850
+ bytes memory outputScript,
851
+ uint64 outputValue
852
+ ) internal returns (uint64 burnableValue, uint64 treasuryFee) {
853
+ // This function should be called only if the given output is
854
+ // supposed to represent a redemption. Build the redemption key
855
+ // to perform that check.
856
+ uint256 redemptionKey = uint256(
857
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
858
+ );
859
+
860
+ if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {
861
+ // If we entered here, that means the output was identified
862
+ // as a pending redemption request.
863
+ RedemptionRequest storage request = self.pendingRedemptions[
864
+ redemptionKey
865
+ ];
866
+ // Compute the request's redeemable amount as the requested
867
+ // amount reduced by the treasury fee. The request's
868
+ // minimal amount is then the redeemable amount reduced by
869
+ // the maximum transaction fee.
870
+ uint64 redeemableAmount = request.requestedAmount -
871
+ request.treasuryFee;
872
+ // Output value must fit between the request's redeemable
873
+ // and minimal amounts to be deemed valid.
874
+ require(
875
+ redeemableAmount - request.txMaxFee <= outputValue &&
876
+ outputValue <= redeemableAmount,
877
+ "Output value is not within the acceptable range of the pending request"
878
+ );
879
+ // Add the redeemable amount to the total burnable value
880
+ // the Bridge will use to decrease its balance in the Bank.
881
+ burnableValue = redeemableAmount;
882
+ // Add the request's treasury fee to the total treasury fee
883
+ // value the Bridge will transfer to the treasury.
884
+ treasuryFee = request.treasuryFee;
885
+ // Request was properly handled so remove its redemption
886
+ // key from the mapping to make it reusable for further
887
+ // requests.
888
+ delete self.pendingRedemptions[redemptionKey];
889
+ } else {
890
+ // If we entered here, the output is not a redemption
891
+ // request but there is still a chance the given output is
892
+ // related to a reported timed out redemption request.
893
+ // If so, check if the output value matches the request
894
+ // amount to confirm this is an overdue request fulfillment
895
+ // then bypass this output and process the subsequent
896
+ // ones. That also means the wallet was already punished
897
+ // for the inactivity. Otherwise, just revert.
898
+ RedemptionRequest storage request = self.timedOutRedemptions[
899
+ redemptionKey
900
+ ];
901
+
902
+ require(
903
+ request.requestedAt != 0,
904
+ "Output is a non-requested redemption"
905
+ );
906
+
907
+ uint64 redeemableAmount = request.requestedAmount -
908
+ request.treasuryFee;
909
+
910
+ require(
911
+ redeemableAmount - request.txMaxFee <= outputValue &&
912
+ outputValue <= redeemableAmount,
913
+ "Output value is not within the acceptable range of the timed out request"
914
+ );
915
+ }
916
+ }
917
+
918
+ /// @notice Notifies that there is a pending redemption request associated
919
+ /// with the given wallet, that has timed out. The redemption
920
+ /// request is identified by the key built as
921
+ /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.
922
+ /// The results of calling this function:
923
+ /// - the pending redemptions value for the wallet will be decreased
924
+ /// by the requested amount (minus treasury fee),
925
+ /// - the tokens taken from the redeemer on redemption request will
926
+ /// be returned to the redeemer,
927
+ /// - the request will be moved from pending redemptions to
928
+ /// timed-out redemptions,
929
+ /// - if the state of the wallet is `Live` or `MovingFunds`, the
930
+ /// wallet operators will be slashed and the notifier will be
931
+ /// rewarded,
932
+ /// - if the state of wallet is `Live`, the wallet will be closed or
933
+ /// marked as `MovingFunds` (depending on the presence or absence
934
+ /// of the wallet's main UTXO) and the wallet will no longer be
935
+ /// marked as the active wallet (if it was marked as such).
936
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet.
937
+ /// @param walletMembersIDs Identifiers of the wallet signing group members.
938
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
939
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH).
940
+ /// @dev Requirements:
941
+ /// - The wallet must be in the Live or MovingFunds or Terminated state,
942
+ /// - The redemption request identified by `walletPubKeyHash` and
943
+ /// `redeemerOutputScript` must exist,
944
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
945
+ /// be exactly the same as the hash stored under `membersIdsHash`
946
+ /// for the given `walletID`. Those IDs are not directly stored
947
+ /// in the contract for gas efficiency purposes but they can be
948
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
949
+ /// events of the `WalletRegistry` contract,
950
+ /// - The amount of time defined by `redemptionTimeout` must have
951
+ /// passed since the redemption was requested (the request must be
952
+ /// timed-out).
953
+ function notifyRedemptionTimeout(
954
+ BridgeState.Storage storage self,
955
+ bytes20 walletPubKeyHash,
956
+ uint32[] calldata walletMembersIDs,
957
+ bytes calldata redeemerOutputScript
958
+ ) external {
959
+ uint256 redemptionKey = uint256(
960
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
961
+ );
962
+ Redemption.RedemptionRequest memory request = self.pendingRedemptions[
963
+ redemptionKey
964
+ ];
965
+
966
+ require(request.requestedAt > 0, "Redemption request does not exist");
967
+ require(
968
+ /* solhint-disable-next-line not-rely-on-time */
969
+ request.requestedAt + self.redemptionTimeout < block.timestamp,
970
+ "Redemption request has not timed out"
971
+ );
972
+
973
+ // Update the wallet's pending redemptions value
974
+ Wallets.Wallet storage wallet = self.registeredWallets[
975
+ walletPubKeyHash
976
+ ];
977
+ wallet.pendingRedemptionsValue -=
978
+ request.requestedAmount -
979
+ request.treasuryFee;
980
+
981
+ require(
982
+ wallet.state == Wallets.WalletState.Live ||
983
+ wallet.state == Wallets.WalletState.MovingFunds ||
984
+ wallet.state == Wallets.WalletState.Terminated,
985
+ "The wallet must be in Live, MovingFunds or Terminated state"
986
+ );
987
+
988
+ // It is worth noting that there is no need to check if
989
+ // `timedOutRedemption` mapping already contains the given redemption
990
+ // key. There is no possibility to re-use a key of a reported timed-out
991
+ // redemption because the wallet responsible for causing the timeout is
992
+ // moved to a state that prevents it to receive new redemption requests.
993
+
994
+ // Move the redemption from pending redemptions to timed-out redemptions
995
+ self.timedOutRedemptions[redemptionKey] = request;
996
+ delete self.pendingRedemptions[redemptionKey];
997
+
998
+ if (
999
+ wallet.state == Wallets.WalletState.Live ||
1000
+ wallet.state == Wallets.WalletState.MovingFunds
1001
+ ) {
1002
+ // Propagate timeout consequences to the wallet
1003
+ self.notifyWalletTimedOutRedemption(walletPubKeyHash);
1004
+
1005
+ // Slash the wallet operators and reward the notifier
1006
+ self.ecdsaWalletRegistry.seize(
1007
+ self.redemptionTimeoutSlashingAmount,
1008
+ self.redemptionTimeoutNotifierRewardMultiplier,
1009
+ msg.sender,
1010
+ wallet.ecdsaWalletID,
1011
+ walletMembersIDs
1012
+ );
1013
+ }
1014
+
1015
+ // slither-disable-next-line reentrancy-events
1016
+ emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
1017
+
1018
+ // Return the requested amount of tokens to the redeemer
1019
+ self.bank.transferBalance(request.redeemer, request.requestedAmount);
1020
+ }
1021
+ }