@keep-network/tbtc-v2 0.1.1-dev.4 → 0.1.1-dev.42

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 (60) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/TBTC.json +19 -18
  3. package/artifacts/TBTCToken.json +19 -18
  4. package/artifacts/VendingMachine.json +20 -19
  5. package/artifacts/solcInputs/002940e9cc8128f6629e90620c66cba5.json +215 -0
  6. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  7. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  8. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  9. package/build/contracts/bank/Bank.sol/Bank.json +20 -2
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  11. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  12. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  13. package/build/contracts/bridge/Bridge.sol/Bridge.json +1664 -63
  14. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  15. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +42 -0
  16. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  17. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  18. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  19. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  20. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  21. package/build/contracts/bridge/Fraud.sol/Fraud.json +138 -0
  22. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  23. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  24. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  25. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +30 -0
  26. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  27. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  28. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  29. package/build/contracts/bridge/Redeem.sol/Redeem.json +92 -0
  30. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
  31. package/build/contracts/bridge/Sweep.sol/Sweep.json +30 -0
  32. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  33. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  34. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  35. package/build/contracts/bridge/Wallets.sol/Wallets.json +93 -0
  36. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  37. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  38. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  39. package/build/contracts/vault/IVault.sol/IVault.json +19 -1
  40. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  41. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +36 -18
  42. package/contracts/GovernanceUtils.sol +1 -1
  43. package/contracts/bank/Bank.sol +34 -18
  44. package/contracts/bridge/BitcoinTx.sol +241 -0
  45. package/contracts/bridge/Bridge.sol +942 -123
  46. package/contracts/bridge/BridgeState.sol +251 -0
  47. package/contracts/bridge/Deposit.sol +244 -0
  48. package/contracts/bridge/EcdsaLib.sol +30 -0
  49. package/contracts/bridge/Fraud.sol +455 -0
  50. package/contracts/bridge/IRelay.sol +28 -0
  51. package/contracts/bridge/MovingFunds.sol +278 -0
  52. package/contracts/bridge/Redeem.sol +844 -0
  53. package/contracts/bridge/Sweep.sol +509 -0
  54. package/contracts/bridge/VendingMachine.sol +1 -1
  55. package/contracts/bridge/Wallets.sol +510 -0
  56. package/contracts/token/TBTC.sol +1 -1
  57. package/contracts/vault/IVault.sol +32 -10
  58. package/contracts/vault/TBTCVault.sol +20 -2
  59. package/package.json +28 -24
  60. package/artifacts/solcInputs/d71966212a658480bad5748ad85b1396.json +0 -116
@@ -0,0 +1,844 @@
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
+ // TODO: Rename to Redemption. All library names are nouns.
144
+ library Redeem {
145
+ using BridgeState for BridgeState.Storage;
146
+ using Wallets for BridgeState.Storage;
147
+
148
+ using BTCUtils for bytes;
149
+ using BytesLib for bytes;
150
+
151
+ /// @notice Represents a redemption request.
152
+ struct RedemptionRequest {
153
+ // ETH address of the redeemer who created the request.
154
+ address redeemer;
155
+ // Requested TBTC amount in satoshi.
156
+ uint64 requestedAmount;
157
+ // Treasury TBTC fee in satoshi at the moment of request creation.
158
+ uint64 treasuryFee;
159
+ // Transaction maximum BTC fee in satoshi at the moment of request
160
+ // creation.
161
+ uint64 txMaxFee;
162
+ // UNIX timestamp the request was created at.
163
+ uint32 requestedAt;
164
+ }
165
+
166
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
167
+ /// outputs processing.
168
+ struct RedemptionTxOutputsInfo {
169
+ // Total TBTC value in satoshi that should be burned by the Bridge.
170
+ // It includes the total amount of all BTC redeemed in the transaction
171
+ // and the fee paid to BTC miners for the redemption transaction.
172
+ uint64 totalBurnableValue;
173
+ // Total TBTC value in satoshi that should be transferred to
174
+ // the treasury. It is a sum of all treasury fees paid by all
175
+ // redeemers included in the redemption transaction.
176
+ uint64 totalTreasuryFee;
177
+ // Index of the change output. The change output becomes
178
+ // the new main wallet's UTXO.
179
+ uint32 changeIndex;
180
+ // Value in satoshi of the change output.
181
+ uint64 changeValue;
182
+ }
183
+
184
+ /// @notice Represents temporary information needed during the processing of
185
+ /// the redemption Bitcoin transaction outputs. This structure is an
186
+ /// internal one and should not be exported outside of the redemption
187
+ /// transaction processing code.
188
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
189
+ struct RedemptionTxOutputsProcessingInfo {
190
+ // The first output starting index in the transaction.
191
+ uint256 outputStartingIndex;
192
+ // The number of outputs in the transaction.
193
+ uint256 outputsCount;
194
+ // P2PKH script for the wallet. Needed to determine the change output.
195
+ bytes32 walletP2PKHScriptKeccak;
196
+ // P2WPKH script for the wallet. Needed to determine the change output.
197
+ bytes32 walletP2WPKHScriptKeccak;
198
+ }
199
+
200
+ event RedemptionRequested(
201
+ bytes20 walletPubKeyHash,
202
+ bytes redeemerOutputScript,
203
+ address redeemer,
204
+ uint64 requestedAmount,
205
+ uint64 treasuryFee,
206
+ uint64 txMaxFee
207
+ );
208
+
209
+ event RedemptionsCompleted(
210
+ bytes20 walletPubKeyHash,
211
+ bytes32 redemptionTxHash
212
+ );
213
+
214
+ event RedemptionTimedOut(
215
+ bytes20 walletPubKeyHash,
216
+ bytes redeemerOutputScript
217
+ );
218
+
219
+ /// @notice Requests redemption of the given amount from the specified
220
+ /// wallet to the redeemer Bitcoin output script.
221
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
222
+ /// using Bitcoin HASH160 over the compressed ECDSA public key)
223
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
224
+ /// the Ethereum chain
225
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
226
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
227
+ /// redeemed BTC
228
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
229
+ /// that is taken from redeemer's balance in the Bank upon request.
230
+ /// Once the request is handled, the actual amount of BTC locked
231
+ /// on the redeemer output script will be always lower than this value
232
+ /// since the treasury and Bitcoin transaction fees must be incurred.
233
+ /// The minimal amount satisfying the request can be computed as:
234
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
235
+ /// Fees values are taken at the moment of request creation.
236
+ /// @dev Requirements:
237
+ /// - Wallet behind `walletPubKeyHash` must be live
238
+ /// - `mainUtxo` components must point to the recent main UTXO
239
+ /// of the given wallet, as currently known on the Ethereum chain.
240
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
241
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
242
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
243
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
244
+ /// used for only one pending request at the same time
245
+ /// - Wallet must have enough Bitcoin balance to proceed the request
246
+ /// - Redeemer must make an allowance in the Bank that the Bridge
247
+ /// contract can spend the given `amount`.
248
+ function requestRedemption(
249
+ BridgeState.Storage storage self,
250
+ bytes20 walletPubKeyHash,
251
+ BitcoinTx.UTXO calldata mainUtxo,
252
+ bytes calldata redeemerOutputScript,
253
+ uint64 amount
254
+ ) external {
255
+ Wallets.Wallet storage wallet = self.registeredWallets[
256
+ walletPubKeyHash
257
+ ];
258
+
259
+ require(
260
+ wallet.state == Wallets.WalletState.Live,
261
+ "Wallet must be in Live state"
262
+ );
263
+
264
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
265
+ require(
266
+ mainUtxoHash != bytes32(0),
267
+ "No main UTXO for the given wallet"
268
+ );
269
+ require(
270
+ keccak256(
271
+ abi.encodePacked(
272
+ mainUtxo.txHash,
273
+ mainUtxo.txOutputIndex,
274
+ mainUtxo.txOutputValue
275
+ )
276
+ ) == mainUtxoHash,
277
+ "Invalid main UTXO data"
278
+ );
279
+
280
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
281
+ // if it is the oldest one who can handle the request. This will
282
+ // be suggested by the dApp but may not be respected by users who
283
+ // interact directly with the contract. Do we need to enforce it
284
+ // here? One option is not to enforce it, to save on gas, but if
285
+ // we see this rule is not respected, upgrade Bridge contract to
286
+ // require it.
287
+
288
+ // Validate if redeemer output script is a correct standard type
289
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
290
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
291
+ // a function extracts the payload properly only from standard outputs
292
+ // so if it succeeds, we have a guarantee the redeemer output script
293
+ // is proper. Worth to note `extractHash` ignores the value at all
294
+ // so this is why we can use 0 safely. This way of validation is the
295
+ // same as in tBTC v1.
296
+ bytes memory redeemerOutputScriptPayload = abi
297
+ .encodePacked(bytes8(0), redeemerOutputScript)
298
+ .extractHash();
299
+ require(
300
+ redeemerOutputScriptPayload.length > 0,
301
+ "Redeemer output script must be a standard type"
302
+ );
303
+ // Check if the redeemer output script payload does not point to the
304
+ // wallet public key hash.
305
+ require(
306
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
307
+ keccak256(redeemerOutputScriptPayload),
308
+ "Redeemer output script must not point to the wallet PKH"
309
+ );
310
+
311
+ require(
312
+ amount >= self.redemptionDustThreshold,
313
+ "Redemption amount too small"
314
+ );
315
+
316
+ // The redemption key is built on top of the wallet public key hash
317
+ // and redeemer output script pair. That means there can be only one
318
+ // request asking for redemption from the given wallet to the given
319
+ // BTC script at the same time.
320
+ uint256 redemptionKey = uint256(
321
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
322
+ );
323
+
324
+ // Check if given redemption key is not used by a pending redemption.
325
+ // There is no need to check for existence in `timedOutRedemptions`
326
+ // since the wallet's state is changed to other than Live after
327
+ // first time out is reported so making new requests is not possible.
328
+ // slither-disable-next-line incorrect-equality
329
+ require(
330
+ self.pendingRedemptions[redemptionKey].requestedAt == 0,
331
+ "There is a pending redemption request from this wallet to the same address"
332
+ );
333
+
334
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
335
+ // since the `redemptionDustThreshold` should force that condition
336
+ // to be always true.
337
+ uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0
338
+ ? amount / self.redemptionTreasuryFeeDivisor
339
+ : 0;
340
+ uint64 txMaxFee = self.redemptionTxMaxFee;
341
+
342
+ // The main wallet UTXO's value doesn't include all pending redemptions.
343
+ // To determine if the requested redemption can be performed by the
344
+ // wallet we need to subtract the total value of all pending redemptions
345
+ // from that wallet's main UTXO value. Given that the treasury fee is
346
+ // not redeemed from the wallet, we are subtracting it.
347
+ wallet.pendingRedemptionsValue += amount - treasuryFee;
348
+ require(
349
+ mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
350
+ "Insufficient wallet funds"
351
+ );
352
+
353
+ self.pendingRedemptions[redemptionKey] = RedemptionRequest(
354
+ msg.sender,
355
+ amount,
356
+ treasuryFee,
357
+ txMaxFee,
358
+ /* solhint-disable-next-line not-rely-on-time */
359
+ uint32(block.timestamp)
360
+ );
361
+
362
+ emit RedemptionRequested(
363
+ walletPubKeyHash,
364
+ redeemerOutputScript,
365
+ msg.sender,
366
+ amount,
367
+ treasuryFee,
368
+ txMaxFee
369
+ );
370
+
371
+ self.bank.transferBalanceFrom(msg.sender, address(this), amount);
372
+ }
373
+
374
+ /// @notice Used by the wallet to prove the BTC redemption transaction
375
+ /// and to make the necessary bookkeeping. Redemption is only
376
+ /// accepted if it satisfies SPV proof.
377
+ ///
378
+ /// The function is performing Bank balance updates by burning
379
+ /// the total redeemed Bitcoin amount from Bridge balance and
380
+ /// transferring the treasury fee sum to the treasury address.
381
+ ///
382
+ /// It is possible to prove the given redemption only one time.
383
+ /// @param redemptionTx Bitcoin redemption transaction data
384
+ /// @param redemptionProof Bitcoin redemption proof data
385
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
386
+ /// the Ethereum chain
387
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
388
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
389
+ /// performed the redemption transaction
390
+ /// @dev Requirements:
391
+ /// - `redemptionTx` components must match the expected structure. See
392
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
393
+ /// correspond to appropriate Bitcoin transaction fields to produce
394
+ /// a provable transaction hash.
395
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
396
+ /// exactly 1 input that refers to the wallet's main UTXO. That
397
+ /// transaction should have 1..n outputs handling existing pending
398
+ /// redemption requests or pointing to reported timed out requests.
399
+ /// There can be also 1 optional output representing the
400
+ /// change and pointing back to the 20-byte wallet public key hash.
401
+ /// The change should be always present if the redeemed value sum
402
+ /// is lower than the total wallet's BTC balance.
403
+ /// - `redemptionProof` components must match the expected structure.
404
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
405
+ /// field must contain a valid number of block headers, not less
406
+ /// than the `txProofDifficultyFactor` contract constant.
407
+ /// - `mainUtxo` components must point to the recent main UTXO
408
+ /// of the given wallet, as currently known on the Ethereum chain.
409
+ /// Additionally, the recent main UTXO on Ethereum must be set.
410
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
411
+ /// as transaction single input.
412
+ /// Other remarks:
413
+ /// - Putting the change output as the first transaction output can
414
+ /// save some gas because the output processing loop begins each
415
+ /// iteration by checking whether the given output is the change
416
+ /// thus uses some gas for making the comparison. Once the change
417
+ /// is identified, that check is omitted in further iterations.
418
+ function submitRedemptionProof(
419
+ BridgeState.Storage storage self,
420
+ BitcoinTx.Info calldata redemptionTx,
421
+ BitcoinTx.Proof calldata redemptionProof,
422
+ BitcoinTx.UTXO calldata mainUtxo,
423
+ bytes20 walletPubKeyHash
424
+ ) external {
425
+ // TODO: Just as for `submitSweepProof`, fail early if the function
426
+ // call gets frontrunned. See discussion:
427
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
428
+
429
+ // The actual transaction proof is performed here. After that point, we
430
+ // can assume the transaction happened on Bitcoin chain and has
431
+ // a sufficient number of confirmations as determined by
432
+ // `txProofDifficultyFactor` constant.
433
+ bytes32 redemptionTxHash = BitcoinTx.validateProof(
434
+ redemptionTx,
435
+ redemptionProof,
436
+ self.proofDifficultyContext()
437
+ );
438
+
439
+ // Process the redemption transaction input. Specifically, check if it
440
+ // refers to the expected wallet's main UTXO.
441
+ OutboundTx.processWalletOutboundTxInput(
442
+ self,
443
+ redemptionTx.inputVector,
444
+ mainUtxo,
445
+ walletPubKeyHash
446
+ );
447
+
448
+ Wallets.Wallet storage wallet = self.registeredWallets[
449
+ walletPubKeyHash
450
+ ];
451
+
452
+ Wallets.WalletState walletState = wallet.state;
453
+ require(
454
+ walletState == Wallets.WalletState.Live ||
455
+ walletState == Wallets.WalletState.MovingFunds,
456
+ "Wallet must be in Live or MovingFunds state"
457
+ );
458
+
459
+ // Process redemption transaction outputs to extract some info required
460
+ // for further processing.
461
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
462
+ self,
463
+ redemptionTx.outputVector,
464
+ walletPubKeyHash
465
+ );
466
+
467
+ if (outputsInfo.changeValue > 0) {
468
+ // If the change value is grater than zero, it means the change
469
+ // output exists and can be used as new wallet's main UTXO.
470
+ wallet.mainUtxoHash = keccak256(
471
+ abi.encodePacked(
472
+ redemptionTxHash,
473
+ outputsInfo.changeIndex,
474
+ outputsInfo.changeValue
475
+ )
476
+ );
477
+ } else {
478
+ // If the change value is zero, it means the change output doesn't
479
+ // exists and no funds left on the wallet. Delete the main UTXO
480
+ // for that wallet to represent that state in a proper way.
481
+ delete wallet.mainUtxoHash;
482
+ }
483
+
484
+ wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
485
+
486
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
487
+
488
+ self.bank.decreaseBalance(outputsInfo.totalBurnableValue);
489
+ self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);
490
+ }
491
+
492
+ /// @notice Processes the Bitcoin redemption transaction output vector.
493
+ /// It extracts each output and tries to identify it as a pending
494
+ /// redemption request, reported timed out request, or change.
495
+ /// Reverts if one of the outputs cannot be recognized properly.
496
+ /// This function also marks each request as processed by removing
497
+ /// them from `pendingRedemptions` mapping.
498
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
499
+ /// vector. This function assumes vector's structure is valid so it
500
+ /// must be validated using e.g. `BTCUtils.validateVout` function
501
+ /// before it is passed here
502
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
503
+ // HASH160 over the compressed ECDSA public key) of the wallet which
504
+ /// performed the redemption transaction.
505
+ /// @return info Outcomes of the processing.
506
+ function processRedemptionTxOutputs(
507
+ BridgeState.Storage storage self,
508
+ bytes memory redemptionTxOutputVector,
509
+ bytes20 walletPubKeyHash
510
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
511
+ // Determining the total number of redemption transaction outputs in
512
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
513
+ // docs for more details.
514
+ (
515
+ uint256 outputsCompactSizeUintLength,
516
+ uint256 outputsCount
517
+ ) = redemptionTxOutputVector.parseVarInt();
518
+
519
+ // To determine the first output starting index, we must jump over
520
+ // the compactSize uint which prepends the output vector. One byte
521
+ // must be added because `BtcUtils.parseVarInt` does not include
522
+ // compactSize uint tag in the returned length.
523
+ //
524
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
525
+ // returns `0`, so we jump over one byte of compactSize uint.
526
+ //
527
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
528
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
529
+ // tag byte included) so we need to jump over 1+2 bytes of
530
+ // compactSize uint.
531
+ //
532
+ // Please refer `BTCUtils` library and compactSize uint
533
+ // docs in `BitcoinTx` library for more details.
534
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
535
+
536
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
537
+ // scripts that can be used to lock the change. This is done upfront to
538
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
539
+ //
540
+ // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
541
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
542
+ // - 0x19: Byte length of the entire script
543
+ // - 0x76: OP_DUP
544
+ // - 0xa9: OP_HASH160
545
+ // - 0x14: Byte length of the public key hash
546
+ // - 0x88: OP_EQUALVERIFY
547
+ // - 0xac: OP_CHECKSIG
548
+ // which matches the P2PKH structure as per:
549
+ // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
550
+ bytes32 walletP2PKHScriptKeccak = keccak256(
551
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
552
+ );
553
+ // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
554
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
555
+ // - 0x16: Byte length of the entire script
556
+ // - 0x00: OP_0
557
+ // - 0x14: Byte length of the public key hash
558
+ // which matches the P2WPKH structure as per:
559
+ // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
560
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
561
+ abi.encodePacked(hex"160014", walletPubKeyHash)
562
+ );
563
+
564
+ return
565
+ processRedemptionTxOutputs(
566
+ self,
567
+ redemptionTxOutputVector,
568
+ walletPubKeyHash,
569
+ RedemptionTxOutputsProcessingInfo(
570
+ outputStartingIndex,
571
+ outputsCount,
572
+ walletP2PKHScriptKeccak,
573
+ walletP2WPKHScriptKeccak
574
+ )
575
+ );
576
+ }
577
+
578
+ /// @notice Processes all outputs from the redemption transaction. Tries to
579
+ /// identify output as a change output, pending redemption request
580
+ // or reported redemption. Reverts if one of the outputs cannot be
581
+ /// recognized properly. Marks each request as processed by removing
582
+ /// them from `pendingRedemptions` mapping.
583
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
584
+ /// vector. This function assumes vector's structure is valid so it
585
+ /// must be validated using e.g. `BTCUtils.validateVout` function
586
+ /// before it is passed here
587
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
588
+ // HASH160 over the compressed ECDSA public key) of the wallet which
589
+ /// performed the redemption transaction.
590
+ /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output
591
+ /// starting index, the number of outputs and possible wallet change
592
+ /// P2PKH and P2WPKH scripts.
593
+ function processRedemptionTxOutputs(
594
+ BridgeState.Storage storage self,
595
+ bytes memory redemptionTxOutputVector,
596
+ bytes20 walletPubKeyHash,
597
+ RedemptionTxOutputsProcessingInfo memory processInfo
598
+ ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {
599
+ // Helper variable that counts the number of processed redemption
600
+ // outputs. Redemptions can be either pending or reported as timed out.
601
+ // TODO: Revisit the approach with redemptions count according to
602
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
603
+ uint256 processedRedemptionsCount = 0;
604
+
605
+ // Outputs processing loop.
606
+ for (uint256 i = 0; i < processInfo.outputsCount; i++) {
607
+ // TODO: Check if we can optimize gas costs by adding
608
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
609
+ // in order to avoid allocating bytes in memory.
610
+ uint256 outputLength = redemptionTxOutputVector
611
+ .determineOutputLengthAt(processInfo.outputStartingIndex);
612
+ bytes memory output = redemptionTxOutputVector.slice(
613
+ processInfo.outputStartingIndex,
614
+ outputLength
615
+ );
616
+
617
+ // Extract the value from given output.
618
+ uint64 outputValue = output.extractValue();
619
+ // The output consists of an 8-byte value and a variable length
620
+ // script. To extract that script we slice the output starting from
621
+ // 9th byte until the end.
622
+ bytes memory outputScript = output.slice(8, output.length - 8);
623
+
624
+ if (
625
+ resultInfo.changeValue == 0 &&
626
+ (keccak256(outputScript) ==
627
+ processInfo.walletP2PKHScriptKeccak ||
628
+ keccak256(outputScript) ==
629
+ processInfo.walletP2WPKHScriptKeccak) &&
630
+ outputValue > 0
631
+ ) {
632
+ // If we entered here, that means the change output with a
633
+ // proper non-zero value was found.
634
+ resultInfo.changeIndex = uint32(i);
635
+ resultInfo.changeValue = outputValue;
636
+ } else {
637
+ // If we entered here, that the means the given output is
638
+ // supposed to represent a redemption.
639
+ (
640
+ uint64 burnableValue,
641
+ uint64 treasuryFee
642
+ ) = processNonChangeRedemptionTxOutput(
643
+ self,
644
+ walletPubKeyHash,
645
+ outputScript,
646
+ outputValue
647
+ );
648
+ resultInfo.totalBurnableValue += burnableValue;
649
+ resultInfo.totalTreasuryFee += treasuryFee;
650
+ processedRedemptionsCount++;
651
+ }
652
+
653
+ // Make the `outputStartingIndex` pointing to the next output by
654
+ // increasing it by current output's length.
655
+ processInfo.outputStartingIndex += outputLength;
656
+ }
657
+
658
+ // Protect against the cases when there is only a single change output
659
+ // referring back to the wallet PKH and just burning main UTXO value
660
+ // for transaction fees.
661
+ require(
662
+ processedRedemptionsCount > 0,
663
+ "Redemption transaction must process at least one redemption"
664
+ );
665
+ }
666
+
667
+ /// @notice Processes a single redemption transaction output. Tries to
668
+ /// identify output as a pending redemption request or reported
669
+ /// redemption timeout. Output script passed to this function must
670
+ /// not be the change output. Such output needs to be identified
671
+ /// separately before calling this function.
672
+ /// Reverts if output is neither requested pending redemption nor
673
+ /// requested and reported timed-out redemption.
674
+ /// This function also marks each pending request as processed by
675
+ /// removing them from `pendingRedemptions` mapping.
676
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
677
+ // HASH160 over the compressed ECDSA public key) of the wallet which
678
+ /// performed the redemption transaction.
679
+ /// @param outputScript Non-change output script to be processed
680
+ /// @param outputValue Value of the output being processed
681
+ /// @return burnableValue The value burnable as a result of processing this
682
+ /// single redemption output. This value needs to be summed up with
683
+ /// burnable values of all other outputs to evaluate total burnable
684
+ /// value for the entire redemption transaction. This value is 0
685
+ /// for a timed-out redemption request.
686
+ /// @return treasuryFee The treasury fee from this single redemption output.
687
+ /// This value needs to be summed up with treasury fees of all other
688
+ /// outputs to evaluate the total treasury fee for the entire
689
+ /// redemption transaction. This value is 0 for a timed-out
690
+ /// redemption request.
691
+ function processNonChangeRedemptionTxOutput(
692
+ BridgeState.Storage storage self,
693
+ bytes20 walletPubKeyHash,
694
+ bytes memory outputScript,
695
+ uint64 outputValue
696
+ ) internal returns (uint64 burnableValue, uint64 treasuryFee) {
697
+ // This function should be called only if the given output is
698
+ // supposed to represent a redemption. Build the redemption key
699
+ // to perform that check.
700
+ uint256 redemptionKey = uint256(
701
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
702
+ );
703
+
704
+ if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {
705
+ // If we entered here, that means the output was identified
706
+ // as a pending redemption request.
707
+ RedemptionRequest storage request = self.pendingRedemptions[
708
+ redemptionKey
709
+ ];
710
+ // Compute the request's redeemable amount as the requested
711
+ // amount reduced by the treasury fee. The request's
712
+ // minimal amount is then the redeemable amount reduced by
713
+ // the maximum transaction fee.
714
+ uint64 redeemableAmount = request.requestedAmount -
715
+ request.treasuryFee;
716
+ // Output value must fit between the request's redeemable
717
+ // and minimal amounts to be deemed valid.
718
+ require(
719
+ redeemableAmount - request.txMaxFee <= outputValue &&
720
+ outputValue <= redeemableAmount,
721
+ "Output value is not within the acceptable range of the pending request"
722
+ );
723
+ // Add the redeemable amount to the total burnable value
724
+ // the Bridge will use to decrease its balance in the Bank.
725
+ burnableValue = redeemableAmount;
726
+ // Add the request's treasury fee to the total treasury fee
727
+ // value the Bridge will transfer to the treasury.
728
+ treasuryFee = request.treasuryFee;
729
+ // Request was properly handled so remove its redemption
730
+ // key from the mapping to make it reusable for further
731
+ // requests.
732
+ delete self.pendingRedemptions[redemptionKey];
733
+ } else {
734
+ // If we entered here, the output is not a redemption
735
+ // request but there is still a chance the given output is
736
+ // related to a reported timed out redemption request.
737
+ // If so, check if the output value matches the request
738
+ // amount to confirm this is an overdue request fulfillment
739
+ // then bypass this output and process the subsequent
740
+ // ones. That also means the wallet was already punished
741
+ // for the inactivity. Otherwise, just revert.
742
+ RedemptionRequest storage request = self.timedOutRedemptions[
743
+ redemptionKey
744
+ ];
745
+
746
+ require(
747
+ request.requestedAt != 0,
748
+ "Output is a non-requested redemption"
749
+ );
750
+
751
+ uint64 redeemableAmount = request.requestedAmount -
752
+ request.treasuryFee;
753
+
754
+ require(
755
+ redeemableAmount - request.txMaxFee <= outputValue &&
756
+ outputValue <= redeemableAmount,
757
+ "Output value is not within the acceptable range of the timed out request"
758
+ );
759
+ }
760
+ }
761
+
762
+ /// @notice Notifies that there is a pending redemption request associated
763
+ /// with the given wallet, that has timed out. The redemption
764
+ /// request is identified by the key built as
765
+ /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.
766
+ /// The results of calling this function: the pending redemptions
767
+ /// value for the wallet will be decreased by the requested amount
768
+ /// (minus treasury fee), the tokens taken from the redeemer on
769
+ /// redemption request will be returned to the redeemer, the request
770
+ /// will be moved from pending redemptions to timed-out redemptions.
771
+ /// If the state of the wallet is `Live` or `MovingFunds`, the
772
+ /// wallet operators will be slashed.
773
+ /// Additionally, if the state of wallet is `Live`, the wallet will
774
+ /// be closed or marked as `MovingFunds` (depending on the presence
775
+ /// or absence of the wallet's main UTXO) and the wallet will no
776
+ /// longer be marked as the active wallet (if it was marked as such).
777
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
778
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
779
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH)
780
+ /// @dev Requirements:
781
+ /// - The redemption request identified by `walletPubKeyHash` and
782
+ /// `redeemerOutputScript` must exist
783
+ /// - The amount of time defined by `redemptionTimeout` must have
784
+ /// passed since the redemption was requested (the request must be
785
+ /// timed-out).
786
+ function notifyRedemptionTimeout(
787
+ BridgeState.Storage storage self,
788
+ bytes20 walletPubKeyHash,
789
+ bytes calldata redeemerOutputScript
790
+ ) external {
791
+ uint256 redemptionKey = uint256(
792
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
793
+ );
794
+ Redeem.RedemptionRequest memory request = self.pendingRedemptions[
795
+ redemptionKey
796
+ ];
797
+
798
+ require(request.requestedAt > 0, "Redemption request does not exist");
799
+ require(
800
+ /* solhint-disable-next-line not-rely-on-time */
801
+ request.requestedAt + self.redemptionTimeout < block.timestamp,
802
+ "Redemption request has not timed out"
803
+ );
804
+
805
+ // Update the wallet's pending redemptions value
806
+ Wallets.Wallet storage wallet = self.registeredWallets[
807
+ walletPubKeyHash
808
+ ];
809
+ wallet.pendingRedemptionsValue -=
810
+ request.requestedAmount -
811
+ request.treasuryFee;
812
+
813
+ require(
814
+ // TODO: Allow the wallets in `Closing` state when the state is added
815
+ wallet.state == Wallets.WalletState.Live ||
816
+ wallet.state == Wallets.WalletState.MovingFunds ||
817
+ wallet.state == Wallets.WalletState.Terminated,
818
+ "The wallet must be in Live, MovingFunds or Terminated state"
819
+ );
820
+
821
+ // It is worth noting that there is no need to check if
822
+ // `timedOutRedemption` mapping already contains the given redemption
823
+ // key. There is no possibility to re-use a key of a reported timed-out
824
+ // redemption because the wallet responsible for causing the timeout is
825
+ // moved to a state that prevents it to receive new redemption requests.
826
+
827
+ // Move the redemption from pending redemptions to timed-out redemptions
828
+ self.timedOutRedemptions[redemptionKey] = request;
829
+ delete self.pendingRedemptions[redemptionKey];
830
+
831
+ if (
832
+ wallet.state == Wallets.WalletState.Live ||
833
+ wallet.state == Wallets.WalletState.MovingFunds
834
+ ) {
835
+ // Propagate timeout consequences to the wallet
836
+ self.notifyWalletTimedOutRedemption(walletPubKeyHash);
837
+ }
838
+
839
+ emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
840
+
841
+ // Return the requested amount of tokens to the redeemer
842
+ self.bank.transferBalance(request.redeemer, request.requestedAmount);
843
+ }
844
+ }