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

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