@keep-network/tbtc-v2 0.1.1-dev.13 → 0.1.1-dev.16

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 (29) hide show
  1. package/artifacts/TBTC.json +11 -11
  2. package/artifacts/TBTCToken.json +11 -11
  3. package/artifacts/VendingMachine.json +18 -18
  4. package/artifacts/solcInputs/{ae2bc16e265d94d570ec143fe628377f.json → 3d68045732e072924745a5b701f4ad2a.json} +18 -12
  5. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  6. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  7. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  8. package/build/contracts/bank/Bank.sol/Bank.json +2 -2
  9. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  11. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  12. package/build/contracts/bridge/Bridge.sol/Bridge.json +365 -2
  13. package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +1 -1
  14. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  15. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  16. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  17. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  18. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  19. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  20. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +2 -2
  21. package/contracts/GovernanceUtils.sol +1 -1
  22. package/contracts/bank/Bank.sol +18 -17
  23. package/contracts/bridge/BitcoinTx.sol +3 -2
  24. package/contracts/bridge/Bridge.sol +912 -127
  25. package/contracts/bridge/VendingMachine.sol +1 -1
  26. package/contracts/token/TBTC.sol +1 -1
  27. package/contracts/vault/IVault.sol +1 -1
  28. package/contracts/vault/TBTCVault.sol +1 -1
  29. package/package.json +6 -7
@@ -13,15 +13,13 @@
13
13
  // ▐████▌ ▐████▌
14
14
  // ▐████▌ ▐████▌
15
15
 
16
- pragma solidity 0.8.4;
16
+ pragma solidity ^0.8.9;
17
17
 
18
18
  import "@openzeppelin/contracts/access/Ownable.sol";
19
19
 
20
20
  import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
21
21
  import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
22
- import {
23
- ValidateSPV
24
- } from "@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol";
22
+ import {ValidateSPV} from "@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol";
25
23
 
26
24
  import "../bank/Bank.sol";
27
25
  import "./BitcoinTx.sol";
@@ -93,7 +91,7 @@ contract Bridge is Ownable {
93
91
  }
94
92
 
95
93
  /// @notice Represents tBTC deposit data.
96
- struct DepositInfo {
94
+ struct DepositRequest {
97
95
  // Ethereum depositor address.
98
96
  address depositor;
99
97
  // Deposit amount in satoshi.
@@ -109,18 +107,113 @@ contract Bridge is Ownable {
109
107
  uint32 sweptAt;
110
108
  }
111
109
 
110
+ /// @notice Represents a redemption request.
111
+ struct RedemptionRequest {
112
+ // ETH address of the redeemer who created the request.
113
+ address redeemer;
114
+ // Requested TBTC amount in satoshi.
115
+ uint64 requestedAmount;
116
+ // Treasury TBTC fee in satoshi at the moment of request creation.
117
+ uint64 treasuryFee;
118
+ // Transaction maximum BTC fee in satoshi at the moment of request
119
+ // creation.
120
+ uint64 txMaxFee;
121
+ // UNIX timestamp the request was created at.
122
+ uint32 requestedAt;
123
+ }
124
+
125
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
126
+ /// outputs processing.
127
+ struct RedemptionTxOutputsInfo {
128
+ // Total TBTC value in satoshi that should be burned by the Bridge.
129
+ // It includes the total amount of all BTC redeemed in the transaction
130
+ // and the fee paid to BTC miners for the redemption transaction.
131
+ uint64 totalBurnableValue;
132
+ // Total TBTC value in satoshi that should be transferred to
133
+ // the treasury. It is a sum of all treasury fees paid by all
134
+ // redeemers included in the redemption transaction.
135
+ uint64 totalTreasuryFee;
136
+ // Index of the change output. The change output becomes
137
+ // the new main wallet's UTXO.
138
+ uint32 changeIndex;
139
+ // Value in satoshi of the change output.
140
+ uint64 changeValue;
141
+ }
142
+
143
+ /// @notice Represents wallet state:
144
+ enum WalletState {
145
+ /// @dev The wallet is unknown to the Bridge.
146
+ Unknown,
147
+ /// @dev The wallet can sweep deposits and accept redemption requests.
148
+ Active,
149
+ /// @dev The wallet was deemed unhealthy and is expected to move their
150
+ /// outstanding funds to another wallet. The wallet can still
151
+ /// fulfill their pending redemption requests although new
152
+ /// redemption requests and new deposit reveals are not accepted.
153
+ MovingFunds,
154
+ /// @dev The wallet moved or redeemed all their funds and cannot
155
+ /// perform any action.
156
+ Closed,
157
+ /// @dev The wallet committed a fraud that was reported. The wallet is
158
+ /// blocked and can not perform any actions in the Bridge.
159
+ /// Off-chain coordination with the wallet operators is needed to
160
+ /// recover funds.
161
+ Terminated
162
+ }
163
+
164
+ /// @notice Holds information about a wallet.
165
+ struct Wallet {
166
+ // Current state of the wallet.
167
+ WalletState state;
168
+ // The total redeemable value of pending redemption requests targeting
169
+ // that wallet.
170
+ uint64 pendingRedemptionsValue;
171
+ }
172
+
112
173
  /// @notice The number of confirmations on the Bitcoin chain required to
113
174
  /// successfully evaluate an SPV proof.
114
175
  uint256 public immutable txProofDifficultyFactor;
115
176
 
116
- // TODO: Revisit whether it should be updatable or not.
177
+ /// TODO: Revisit whether it should be governable or not.
117
178
  /// @notice Address of the Bank this Bridge belongs to.
118
179
  Bank public immutable bank;
119
180
 
120
- /// TODO: Make it updatable.
181
+ /// TODO: Make it governable.
121
182
  /// @notice Handle to the Bitcoin relay.
122
183
  IRelay public immutable relay;
123
184
 
185
+ /// TODO: Revisit whether it should be governable or not.
186
+ /// @notice Address where the redemptions treasury fees will be sent to.
187
+ /// Treasury takes part in the operators rewarding process.
188
+ address public immutable treasury;
189
+
190
+ /// TODO: Make it governable.
191
+ /// @notice The minimal amount that can be requested for redemption.
192
+ /// Value of this parameter should be always bigger than the sum
193
+ /// of `redemptionTreasuryFee` and `redemptionTxMaxFee` to make
194
+ /// redemptions possible.
195
+ uint64 public redemptionDustThreshold;
196
+
197
+ /// TODO: Make it governable.
198
+ /// @notice Amount of TBTC that is taken from each redemption request and
199
+ /// transferred to the treasury upon successful request finalization.
200
+ uint64 public redemptionTreasuryFee;
201
+
202
+ /// TODO: Make it governable.
203
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
204
+ /// each redemption request being part of the given redemption
205
+ /// transaction. If the maximum BTC transaction fee is exceeded, such
206
+ /// transaction is considered a fraud.
207
+ uint64 public redemptionTxMaxFee;
208
+
209
+ /// TODO: Make it governable.
210
+ /// @notice Time after which the redemption request can be reported as
211
+ /// timed out. It is counted from the moment when the redemption
212
+ /// request was created via `requestRedemption` call. Reported
213
+ /// timed out requests are cancelled and locked TBTC is returned
214
+ /// to the redeemer in full amount.
215
+ uint256 public redemptionTimeout;
216
+
124
217
  /// @notice Indicates if the vault with the given address is trusted or not.
125
218
  /// Depositors can route their revealed deposits only to trusted
126
219
  /// vaults and have trusted vaults notified about new deposits as
@@ -132,18 +225,66 @@ contract Bridge is Ownable {
132
225
 
133
226
  /// @notice Collection of all revealed deposits indexed by
134
227
  /// keccak256(fundingTxHash | fundingOutputIndex).
135
- /// The fundingTxHash is LE bytes32 and fundingOutputIndex an uint32.
136
- /// This mapping may contain valid and invalid deposits and the
137
- /// wallet is responsible for validating them before attempting to
138
- /// execute a sweep.
139
- mapping(uint256 => DepositInfo) public deposits;
140
-
141
- /// @notice Maps the wallet public key hash (computed using HASH160 opcode)
142
- /// to the latest wallet's main UTXO computed as
228
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
229
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
230
+ /// and invalid deposits and the wallet is responsible for
231
+ /// validating them before attempting to execute a sweep.
232
+ mapping(uint256 => DepositRequest) public deposits;
233
+
234
+ /// @notice Maps the 20-byte wallet public key hash (computed using
235
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to
236
+ /// the latest wallet's main UTXO computed as
143
237
  /// keccak256(txHash | txOutputIndex | txOutputValue). The `tx`
144
238
  /// prefix refers to the transaction which created that main UTXO.
239
+ /// The txHash is bytes32 (ordered as in Bitcoin internally),
240
+ /// txOutputIndex an uint32, and txOutputValue an uint64 value.
145
241
  mapping(bytes20 => bytes32) public mainUtxos;
146
242
 
243
+ /// @notice Collection of all pending redemption requests indexed by
244
+ /// redemption key built as
245
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
246
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
247
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
248
+ /// public key) and redeemerOutputScript is a Bitcoin script
249
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
250
+ /// redeemed BTC as requested by the redeemer. Requests are added
251
+ /// to this mapping by the `requestRedemption` method (duplicates
252
+ /// not allowed) and are removed by one of the following methods:
253
+ /// - `submitRedemptionProof` in case the request was handled
254
+ /// successfully
255
+ /// - `notifyRedemptionTimeout` in case the request was reported
256
+ /// to be timed out
257
+ /// - `submitRedemptionFraudProof` in case the request was handled
258
+ /// in an fraudulent way amount-wise.
259
+ mapping(uint256 => RedemptionRequest) public pendingRedemptions;
260
+
261
+ /// @notice Collection of all timed out redemptions requests indexed by
262
+ /// redemption key built as
263
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
264
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
265
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
266
+ /// public key) and redeemerOutputScript is the Bitcoin script
267
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
268
+ /// out request. Timed out requests are stored in this mapping to
269
+ /// avoid slashing the wallets multiple times for the same timeout.
270
+ /// Only one method can add to this mapping:
271
+ /// - `notifyRedemptionTimeout` which puts the redemption key
272
+ /// to this mapping basing on a timed out request stored
273
+ /// previously in `pendingRedemptions` mapping.
274
+ ///
275
+ // TODO: Remove that Slither disable once this variable is used.
276
+ // slither-disable-next-line uninitialized-state
277
+ mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
278
+
279
+ /// @notice Maps the 20-byte wallet public key hash (computed using
280
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to the
281
+ /// basic wallet information like state and pending
282
+ /// redemptions value.
283
+ ///
284
+ // TODO: Remove that Slither disable once this variable is used.
285
+ // slither-disable-next-line uninitialized-state
286
+ mapping(bytes20 => Wallet) public wallets;
287
+
147
288
  event VaultStatusUpdated(address indexed vault, bool isTrusted);
148
289
 
149
290
  event DepositRevealed(
@@ -160,9 +301,24 @@ contract Bridge is Ownable {
160
301
 
161
302
  event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
162
303
 
304
+ event RedemptionRequested(
305
+ bytes20 walletPubKeyHash,
306
+ bytes redeemerOutputScript,
307
+ address redeemer,
308
+ uint64 requestedAmount,
309
+ uint64 treasuryFee,
310
+ uint64 txMaxFee
311
+ );
312
+
313
+ event RedemptionsCompleted(
314
+ bytes20 walletPubKeyHash,
315
+ bytes32 redemptionTxHash
316
+ );
317
+
163
318
  constructor(
164
319
  address _bank,
165
320
  address _relay,
321
+ address _treasury,
166
322
  uint256 _txProofDifficultyFactor
167
323
  ) {
168
324
  require(_bank != address(0), "Bank address cannot be zero");
@@ -171,9 +327,21 @@ contract Bridge is Ownable {
171
327
  require(_relay != address(0), "Relay address cannot be zero");
172
328
  relay = IRelay(_relay);
173
329
 
330
+ require(_treasury != address(0), "Treasury address cannot be zero");
331
+ treasury = _treasury;
332
+
174
333
  txProofDifficultyFactor = _txProofDifficultyFactor;
334
+
335
+ // TODO: Revisit initial values.
336
+ redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
337
+ redemptionTreasuryFee = 100000; // 100000 satoshi
338
+ redemptionTxMaxFee = 1000; // 1000 satoshi
339
+ redemptionTimeout = 172800; // 48 hours
175
340
  }
176
341
 
342
+ // TODO: Add function `onNewWalletCreated` according to discussion:
343
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r809885230
344
+
177
345
  /// @notice Allows the Governance to mark the given vault address as trusted
178
346
  /// or no longer trusted. Vaults are not trusted by default.
179
347
  /// Trusted vault must meet the following criteria:
@@ -234,39 +402,40 @@ contract Bridge is Ownable {
234
402
  "Vault is not trusted"
235
403
  );
236
404
 
237
- bytes memory expectedScript =
238
- abi.encodePacked(
239
- hex"14", // Byte length of depositor Ethereum address.
240
- reveal.depositor,
241
- hex"75", // OP_DROP
242
- hex"08", // Byte length of blinding factor value.
243
- reveal.blindingFactor,
244
- hex"75", // OP_DROP
245
- hex"76", // OP_DUP
246
- hex"a9", // OP_HASH160
247
- hex"14", // Byte length of a compressed Bitcoin public key hash.
248
- reveal.walletPubKeyHash,
249
- hex"87", // OP_EQUAL
250
- hex"63", // OP_IF
251
- hex"ac", // OP_CHECKSIG
252
- hex"67", // OP_ELSE
253
- hex"76", // OP_DUP
254
- hex"a9", // OP_HASH160
255
- hex"14", // Byte length of a compressed Bitcoin public key hash.
256
- reveal.refundPubKeyHash,
257
- hex"88", // OP_EQUALVERIFY
258
- hex"04", // Byte length of refund locktime value.
259
- reveal.refundLocktime,
260
- hex"b1", // OP_CHECKLOCKTIMEVERIFY
261
- hex"75", // OP_DROP
262
- hex"ac", // OP_CHECKSIG
263
- hex"68" // OP_ENDIF
264
- );
405
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
406
+ // TODO: Should we enforce a specific locktime at contract level?
265
407
 
266
- bytes memory fundingOutput =
267
- fundingTx.outputVector.extractOutputAtIndex(
268
- reveal.fundingOutputIndex
269
- );
408
+ bytes memory expectedScript = abi.encodePacked(
409
+ hex"14", // Byte length of depositor Ethereum address.
410
+ reveal.depositor,
411
+ hex"75", // OP_DROP
412
+ hex"08", // Byte length of blinding factor value.
413
+ reveal.blindingFactor,
414
+ hex"75", // OP_DROP
415
+ hex"76", // OP_DUP
416
+ hex"a9", // OP_HASH160
417
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
418
+ reveal.walletPubKeyHash,
419
+ hex"87", // OP_EQUAL
420
+ hex"63", // OP_IF
421
+ hex"ac", // OP_CHECKSIG
422
+ hex"67", // OP_ELSE
423
+ hex"76", // OP_DUP
424
+ hex"a9", // OP_HASH160
425
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
426
+ reveal.refundPubKeyHash,
427
+ hex"88", // OP_EQUALVERIFY
428
+ hex"04", // Byte length of refund locktime value.
429
+ reveal.refundLocktime,
430
+ hex"b1", // OP_CHECKLOCKTIMEVERIFY
431
+ hex"75", // OP_DROP
432
+ hex"ac", // OP_CHECKSIG
433
+ hex"68" // OP_ENDIF
434
+ );
435
+
436
+ bytes memory fundingOutput = fundingTx
437
+ .outputVector
438
+ .extractOutputAtIndex(reveal.fundingOutputIndex);
270
439
  bytes memory fundingOutputHash = fundingOutput.extractHash();
271
440
 
272
441
  if (fundingOutputHash.length == 20) {
@@ -294,31 +463,22 @@ contract Bridge is Ownable {
294
463
  }
295
464
 
296
465
  // Resulting TX hash is in native Bitcoin little-endian format.
297
- bytes32 fundingTxHash =
298
- abi
299
- .encodePacked(
300
- fundingTx
301
- .version,
302
- fundingTx
303
- .inputVector,
304
- fundingTx
305
- .outputVector,
306
- fundingTx
307
- .locktime
466
+ bytes32 fundingTxHash = abi
467
+ .encodePacked(
468
+ fundingTx.version,
469
+ fundingTx.inputVector,
470
+ fundingTx.outputVector,
471
+ fundingTx.locktime
308
472
  )
309
- .hash256View();
473
+ .hash256View();
310
474
 
311
- DepositInfo storage deposit =
312
- deposits[
313
- uint256(
314
- keccak256(
315
- abi.encodePacked(
316
- fundingTxHash,
317
- reveal.fundingOutputIndex
318
- )
319
- )
475
+ DepositRequest storage deposit = deposits[
476
+ uint256(
477
+ keccak256(
478
+ abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)
320
479
  )
321
- ];
480
+ )
481
+ ];
322
482
  require(deposit.revealedAt == 0, "Deposit already revealed");
323
483
 
324
484
  uint64 fundingOutputAmount = fundingOutput.extractValue();
@@ -392,20 +552,25 @@ contract Bridge is Ownable {
392
552
  // can assume the transaction happened on Bitcoin chain and has
393
553
  // a sufficient number of confirmations as determined by
394
554
  // `txProofDifficultyFactor` constant.
395
- bytes32 sweepTxHash = validateSweepTxProof(sweepTx, sweepProof);
555
+ bytes32 sweepTxHash = validateBitcoinTxProof(sweepTx, sweepProof);
396
556
 
397
557
  // Process sweep transaction output and extract its target wallet
398
558
  // public key hash and value.
399
- (bytes20 walletPubKeyHash, uint64 sweepTxOutputValue) =
400
- processSweepTxOutput(sweepTx.outputVector);
559
+ (
560
+ bytes20 walletPubKeyHash,
561
+ uint64 sweepTxOutputValue
562
+ ) = processSweepTxOutput(sweepTx.outputVector);
401
563
 
402
564
  // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
403
565
 
404
566
  // Check if the main UTXO for given wallet exists. If so, validate
405
567
  // passed main UTXO data against the stored hash and use them for
406
568
  // further processing. If no main UTXO exists, use empty data.
407
- BitcoinTx.UTXO memory resolvedMainUtxo =
408
- BitcoinTx.UTXO(bytes32(0), 0, 0);
569
+ BitcoinTx.UTXO memory resolvedMainUtxo = BitcoinTx.UTXO(
570
+ bytes32(0),
571
+ 0,
572
+ 0
573
+ );
409
574
  bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
410
575
  if (mainUtxoHash != bytes32(0)) {
411
576
  require(
@@ -462,40 +627,36 @@ contract Bridge is Ownable {
462
627
  // TODO: Handle deposits having `vault` set.
463
628
  }
464
629
 
465
- /// @notice Validates the SPV proof of the Bitcoin sweep transaction.
630
+ /// @notice Validates the SPV proof of the Bitcoin transaction.
466
631
  /// Reverts in case the validation or proof verification fail.
467
- /// @param sweepTx Bitcoin sweep transaction data
468
- /// @param sweepProof Bitcoin sweep proof data
469
- /// @return sweepTxHash Proven 32-byte sweep transaction hash.
470
- function validateSweepTxProof(
471
- BitcoinTx.Info calldata sweepTx,
472
- BitcoinTx.Proof calldata sweepProof
473
- ) internal view returns (bytes32 sweepTxHash) {
632
+ /// @param txInfo Bitcoin transaction data
633
+ /// @param proof Bitcoin proof data
634
+ /// @return txHash Proven 32-byte transaction hash.
635
+ function validateBitcoinTxProof(
636
+ BitcoinTx.Info calldata txInfo,
637
+ BitcoinTx.Proof calldata proof
638
+ ) internal view returns (bytes32 txHash) {
474
639
  require(
475
- sweepTx.inputVector.validateVin(),
640
+ txInfo.inputVector.validateVin(),
476
641
  "Invalid input vector provided"
477
642
  );
478
643
  require(
479
- sweepTx.outputVector.validateVout(),
644
+ txInfo.outputVector.validateVout(),
480
645
  "Invalid output vector provided"
481
646
  );
482
647
 
483
- sweepTxHash = abi
648
+ txHash = abi
484
649
  .encodePacked(
485
- sweepTx
486
- .version,
487
- sweepTx
488
- .inputVector,
489
- sweepTx
490
- .outputVector,
491
- sweepTx
492
- .locktime
493
- )
650
+ txInfo.version,
651
+ txInfo.inputVector,
652
+ txInfo.outputVector,
653
+ txInfo.locktime
654
+ )
494
655
  .hash256View();
495
656
 
496
- checkProofFromTxHash(sweepTxHash, sweepProof);
657
+ checkProofFromTxHash(txHash, proof);
497
658
 
498
- return sweepTxHash;
659
+ return txHash;
499
660
  }
500
661
 
501
662
  /// @notice Checks the given Bitcoin transaction hash against the SPV proof.
@@ -530,8 +691,9 @@ contract Bridge is Ownable {
530
691
  uint256 requestedDiff = 0;
531
692
  uint256 currentDiff = relay.getCurrentEpochDifficulty();
532
693
  uint256 previousDiff = relay.getPrevEpochDifficulty();
533
- uint256 firstHeaderDiff =
534
- bitcoinHeaders.extractTarget().calculateDifficulty();
694
+ uint256 firstHeaderDiff = bitcoinHeaders
695
+ .extractTarget()
696
+ .calculateDifficulty();
535
697
 
536
698
  if (firstHeaderDiff == currentDiff) {
537
699
  requestedDiff = currentDiff;
@@ -653,8 +815,10 @@ contract Bridge is Ownable {
653
815
  // Determining the total number of sweep transaction inputs in the same
654
816
  // way as for number of outputs. See `BitcoinTx.inputVector` docs for
655
817
  // more details.
656
- (uint256 inputsCompactSizeUintLength, uint256 inputsCount) =
657
- sweepTxInputVector.parseVarInt();
818
+ (
819
+ uint256 inputsCompactSizeUintLength,
820
+ uint256 inputsCount
821
+ ) = sweepTxInputVector.parseVarInt();
658
822
 
659
823
  // To determine the first input starting index, we must jump over
660
824
  // the compactSize uint which prepends the input vector. One byte
@@ -686,20 +850,17 @@ contract Bridge is Ownable {
686
850
 
687
851
  // Inputs processing loop.
688
852
  for (uint256 i = 0; i < inputsCount; i++) {
689
- // Check if we are at the end of the input vector.
690
- if (inputStartingIndex >= sweepTxInputVector.length) {
691
- break;
692
- }
853
+ (
854
+ bytes32 outpointTxHash,
855
+ uint32 outpointIndex,
856
+ uint256 inputLength
857
+ ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
693
858
 
694
- (bytes32 inputTxHash, uint32 inputTxIndex, uint256 inputLength) =
695
- parseTxInputAt(sweepTxInputVector, inputStartingIndex);
696
-
697
- DepositInfo storage deposit =
698
- deposits[
699
- uint256(
700
- keccak256(abi.encodePacked(inputTxHash, inputTxIndex))
701
- )
702
- ];
859
+ DepositRequest storage deposit = deposits[
860
+ uint256(
861
+ keccak256(abi.encodePacked(outpointTxHash, outpointIndex))
862
+ )
863
+ ];
703
864
 
704
865
  if (deposit.revealedAt != 0) {
705
866
  // If we entered here, that means the input was identified as
@@ -726,7 +887,7 @@ contract Bridge is Ownable {
726
887
  processedDepositsCount++;
727
888
  } else if (
728
889
  mainUtxoExpected != mainUtxoFound &&
729
- mainUtxo.txHash == inputTxHash
890
+ mainUtxo.txHash == outpointTxHash
730
891
  ) {
731
892
  // If we entered here, that means the input was identified as
732
893
  // the expected main UTXO.
@@ -763,9 +924,9 @@ contract Bridge is Ownable {
763
924
  /// @notice Parses a Bitcoin transaction input starting at the given index.
764
925
  /// @param inputVector Bitcoin transaction input vector
765
926
  /// @param inputStartingIndex Index the given input starts at
766
- /// @return inputTxHash 32-byte hash of the Bitcoin transaction which is
927
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
767
928
  /// pointed in the given input's outpoint.
768
- /// @return inputTxIndex 4-byte index of the Bitcoin transaction output
929
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
769
930
  /// which is pointed in the given input's outpoint.
770
931
  /// @return inputLength Byte length of the given input.
771
932
  /// @dev This function assumes vector's structure is valid so it must be
@@ -778,26 +939,650 @@ contract Bridge is Ownable {
778
939
  internal
779
940
  pure
780
941
  returns (
781
- bytes32 inputTxHash,
782
- uint32 inputTxIndex,
942
+ bytes32 outpointTxHash,
943
+ uint32 outpointIndex,
783
944
  uint256 inputLength
784
945
  )
785
946
  {
786
- inputTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
947
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
787
948
 
788
- inputTxIndex = BTCUtils.reverseUint32(
949
+ outpointIndex = BTCUtils.reverseUint32(
789
950
  uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
790
951
  );
791
952
 
792
953
  inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
793
954
 
794
- return (inputTxHash, inputTxIndex, inputLength);
955
+ return (outpointTxHash, outpointIndex, inputLength);
956
+ }
957
+
958
+ /// @notice Requests redemption of the given amount from the specified
959
+ /// wallet to the redeemer Bitcoin output script.
960
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
961
+ // using Bitcoin HASH160 over the compressed ECDSA public key)
962
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
963
+ /// the Ethereum chain
964
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
965
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
966
+ /// redeemed BTC
967
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
968
+ /// that is taken from redeemer's balance in the Bank upon request.
969
+ /// Once the request is handled, the actual amount of BTC locked
970
+ /// on the redeemer output script will be always lower than this value
971
+ /// since the treasury and Bitcoin transaction fees must be incurred.
972
+ /// The minimal amount satisfying the request can be computed as:
973
+ /// `amount - redemptionTreasuryFee - redemptionTxMaxFee`.
974
+ /// Fees values are taken at the moment of request creation.
975
+ /// @dev Requirements:
976
+ /// - Wallet behind `walletPubKeyHash` must be active
977
+ /// - `mainUtxo` components must point to the recent main UTXO
978
+ /// of the given wallet, as currently known on the Ethereum chain.
979
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
980
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
981
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
982
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
983
+ /// used for only one pending request at the same time
984
+ /// - Wallet must have enough Bitcoin balance to proceed the request
985
+ /// - Redeemer must make an allowance in the Bank that the Bridge
986
+ /// contract can spend the given `amount`.
987
+ function requestRedemption(
988
+ bytes20 walletPubKeyHash,
989
+ BitcoinTx.UTXO calldata mainUtxo,
990
+ bytes calldata redeemerOutputScript,
991
+ uint64 amount
992
+ ) external {
993
+ require(
994
+ wallets[walletPubKeyHash].state == WalletState.Active,
995
+ "Wallet must be in Active state"
996
+ );
997
+
998
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
999
+ require(
1000
+ mainUtxoHash != bytes32(0),
1001
+ "No main UTXO for the given wallet"
1002
+ );
1003
+ require(
1004
+ keccak256(
1005
+ abi.encodePacked(
1006
+ mainUtxo.txHash,
1007
+ mainUtxo.txOutputIndex,
1008
+ mainUtxo.txOutputValue
1009
+ )
1010
+ ) == mainUtxoHash,
1011
+ "Invalid main UTXO data"
1012
+ );
1013
+
1014
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1015
+ // if it is the oldest one who can handle the request. This will
1016
+ // be suggested by the dApp but may not be respected by users who
1017
+ // interact directly with the contract. Do we need to enforce it
1018
+ // here? One option is not to enforce it, to save on gas, but if
1019
+ // we see this rule is not respected, upgrade Bridge contract to
1020
+ // require it.
1021
+
1022
+ // Validate if redeemer output script is a correct standard type
1023
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1024
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1025
+ // a function extracts the payload properly only from standard outputs
1026
+ // so if it succeeds, we have a guarantee the redeemer output script
1027
+ // is proper. Worth to note `extractHash` ignores the value at all
1028
+ // so this is why we can use 0 safely. This way of validation is the
1029
+ // same as in tBTC v1.
1030
+ bytes memory redeemerOutputScriptPayload = abi
1031
+ .encodePacked(bytes8(0), redeemerOutputScript)
1032
+ .extractHash();
1033
+ require(
1034
+ redeemerOutputScriptPayload.length > 0,
1035
+ "Redeemer output script must be a standard type"
1036
+ );
1037
+ // Check if the redeemer output script payload does not point to the
1038
+ // wallet public key hash.
1039
+ require(
1040
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
1041
+ keccak256(redeemerOutputScriptPayload),
1042
+ "Redeemer output script must not point to the wallet PKH"
1043
+ );
1044
+
1045
+ require(
1046
+ amount >= redemptionDustThreshold,
1047
+ "Redemption amount too small"
1048
+ );
1049
+
1050
+ // The redemption key is built on top of the wallet public key hash
1051
+ // and redeemer output script pair. That means there can be only one
1052
+ // request asking for redemption from the given wallet to the given
1053
+ // BTC script at the same time.
1054
+ uint256 redemptionKey = uint256(
1055
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1056
+ );
1057
+
1058
+ // Check if given redemption key is not used by a pending redemption.
1059
+ // There is no need to check for existence in `timedOutRedemptions`
1060
+ // since the wallet's state is changed to other than Active after
1061
+ // first time out is reported so making new requests is not possible.
1062
+ // slither-disable-next-line incorrect-equality
1063
+ require(
1064
+ pendingRedemptions[redemptionKey].requestedAt == 0,
1065
+ "There is a pending redemption request from this wallet to the same address"
1066
+ );
1067
+
1068
+ uint64 treasuryFee = redemptionTreasuryFee;
1069
+ uint64 txMaxFee = redemptionTxMaxFee;
1070
+
1071
+ // The main wallet UTXO's value doesn't include all pending redemptions.
1072
+ // To determine if the requested redemption can be performed by the
1073
+ // wallet we need to subtract the total value of all pending redemptions
1074
+ // from that wallet's main UTXO value. Given that the treasury fee is
1075
+ // not redeemed from the wallet, we are subtracting it.
1076
+ wallets[walletPubKeyHash].pendingRedemptionsValue +=
1077
+ amount -
1078
+ treasuryFee;
1079
+ require(
1080
+ mainUtxo.txOutputValue >=
1081
+ wallets[walletPubKeyHash].pendingRedemptionsValue,
1082
+ "Insufficient wallet funds"
1083
+ );
1084
+
1085
+ pendingRedemptions[redemptionKey] = RedemptionRequest(
1086
+ msg.sender,
1087
+ amount,
1088
+ treasuryFee,
1089
+ txMaxFee,
1090
+ /* solhint-disable-next-line not-rely-on-time */
1091
+ uint32(block.timestamp)
1092
+ );
1093
+
1094
+ emit RedemptionRequested(
1095
+ walletPubKeyHash,
1096
+ redeemerOutputScript,
1097
+ msg.sender,
1098
+ amount,
1099
+ treasuryFee,
1100
+ txMaxFee
1101
+ );
1102
+
1103
+ bank.transferBalanceFrom(msg.sender, address(this), amount);
1104
+ }
1105
+
1106
+ /// @notice Used by the wallet to prove the BTC redemption transaction
1107
+ /// and to make the necessary bookkeeping. Redemption is only
1108
+ /// accepted if it satisfies SPV proof.
1109
+ ///
1110
+ /// The function is performing Bank balance updates by burning
1111
+ /// the total redeemed Bitcoin amount from Bridge balance and
1112
+ /// transferring the treasury fee sum to the treasury address.
1113
+ ///
1114
+ /// It is possible to prove the given redemption only one time.
1115
+ /// @param redemptionTx Bitcoin redemption transaction data
1116
+ /// @param redemptionProof Bitcoin redemption proof data
1117
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1118
+ /// the Ethereum chain
1119
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1120
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
1121
+ /// performed the redemption transaction
1122
+ /// @dev Requirements:
1123
+ /// - `redemptionTx` components must match the expected structure. See
1124
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
1125
+ /// correspond to appropriate Bitcoin transaction fields to produce
1126
+ /// a provable transaction hash.
1127
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
1128
+ /// exactly 1 input that refers to the wallet's main UTXO. That
1129
+ /// transaction should have 1..n outputs handling existing pending
1130
+ /// redemption requests or pointing to reported timed out requests.
1131
+ /// There can be also 1 optional output representing the
1132
+ /// change and pointing back to the 20-byte wallet public key hash.
1133
+ /// The change should be always present if the redeemed value sum
1134
+ /// is lower than the total wallet's BTC balance.
1135
+ /// - `redemptionProof` components must match the expected structure.
1136
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
1137
+ /// field must contain a valid number of block headers, not less
1138
+ /// than the `txProofDifficultyFactor` contract constant.
1139
+ /// - `mainUtxo` components must point to the recent main UTXO
1140
+ /// of the given wallet, as currently known on the Ethereum chain.
1141
+ /// Additionally, the recent main UTXO on Ethereum must be set.
1142
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
1143
+ /// as transaction single input.
1144
+ /// Other remarks:
1145
+ /// - Putting the change output as the first transaction output can
1146
+ /// save some gas because the output processing loop begins each
1147
+ /// iteration by checking whether the given output is the change
1148
+ /// thus uses some gas for making the comparison. Once the change
1149
+ /// is identified, that check is omitted in further iterations.
1150
+ function submitRedemptionProof(
1151
+ BitcoinTx.Info calldata redemptionTx,
1152
+ BitcoinTx.Proof calldata redemptionProof,
1153
+ BitcoinTx.UTXO calldata mainUtxo,
1154
+ bytes20 walletPubKeyHash
1155
+ ) external {
1156
+ // TODO: Just as for `submitSweepProof`, fail early if the function
1157
+ // call gets frontrunned. See discussion:
1158
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1159
+
1160
+ // The actual transaction proof is performed here. After that point, we
1161
+ // can assume the transaction happened on Bitcoin chain and has
1162
+ // a sufficient number of confirmations as determined by
1163
+ // `txProofDifficultyFactor` constant.
1164
+ bytes32 redemptionTxHash = validateBitcoinTxProof(
1165
+ redemptionTx,
1166
+ redemptionProof
1167
+ );
1168
+
1169
+ // Perform validation of the redemption transaction input. Specifically,
1170
+ // check if it refers to the expected wallet's main UTXO.
1171
+ validateRedemptionTxInput(
1172
+ redemptionTx.inputVector,
1173
+ mainUtxo,
1174
+ walletPubKeyHash
1175
+ );
1176
+
1177
+ WalletState walletState = wallets[walletPubKeyHash].state;
1178
+ require(
1179
+ walletState == WalletState.Active ||
1180
+ walletState == WalletState.MovingFunds,
1181
+ "Wallet must be in Active or MovingFuds state"
1182
+ );
1183
+
1184
+ // Process redemption transaction outputs to extract some info required
1185
+ // for further processing.
1186
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
1187
+ redemptionTx.outputVector,
1188
+ walletPubKeyHash
1189
+ );
1190
+
1191
+ if (outputsInfo.changeValue > 0) {
1192
+ // If the change value is grater than zero, it means the change
1193
+ // output exists and can be used as new wallet's main UTXO.
1194
+ mainUtxos[walletPubKeyHash] = keccak256(
1195
+ abi.encodePacked(
1196
+ redemptionTxHash,
1197
+ outputsInfo.changeIndex,
1198
+ outputsInfo.changeValue
1199
+ )
1200
+ );
1201
+ } else {
1202
+ // If the change value is zero, it means the change output doesn't
1203
+ // exists and no funds left on the wallet. Delete the main UTXO
1204
+ // for that wallet to represent that state in a proper way.
1205
+ delete mainUtxos[walletPubKeyHash];
1206
+ }
1207
+
1208
+ wallets[walletPubKeyHash].pendingRedemptionsValue -= outputsInfo
1209
+ .totalBurnableValue;
1210
+
1211
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1212
+
1213
+ bank.decreaseBalance(outputsInfo.totalBurnableValue);
1214
+ bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1215
+ }
1216
+
1217
+ /// @notice Validates whether the redemption Bitcoin transaction input
1218
+ /// vector contains a single input referring to the wallet's main
1219
+ /// UTXO. Reverts in case the validation fails.
1220
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1221
+ /// vector. This function assumes vector's structure is valid so it
1222
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1223
+ /// before it is passed here
1224
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1225
+ /// the Ethereum chain.
1226
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1227
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1228
+ /// performed the redemption transaction.
1229
+ function validateRedemptionTxInput(
1230
+ bytes memory redemptionTxInputVector,
1231
+ BitcoinTx.UTXO calldata mainUtxo,
1232
+ bytes20 walletPubKeyHash
1233
+ ) internal view {
1234
+ // Assert that main UTXO for passed wallet exists in storage.
1235
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1236
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1237
+
1238
+ // Assert that passed main UTXO parameter is the same as in storage and
1239
+ // can be used for further processing.
1240
+ require(
1241
+ keccak256(
1242
+ abi.encodePacked(
1243
+ mainUtxo.txHash,
1244
+ mainUtxo.txOutputIndex,
1245
+ mainUtxo.txOutputValue
1246
+ )
1247
+ ) == mainUtxoHash,
1248
+ "Invalid main UTXO data"
1249
+ );
1250
+
1251
+ // Assert that the single redemption transaction input actually
1252
+ // refers to the wallet's main UTXO.
1253
+ (
1254
+ bytes32 redemptionTxOutpointTxHash,
1255
+ uint32 redemptionTxOutpointIndex
1256
+ ) = processRedemptionTxInput(redemptionTxInputVector);
1257
+ require(
1258
+ mainUtxo.txHash == redemptionTxOutpointTxHash &&
1259
+ mainUtxo.txOutputIndex == redemptionTxOutpointIndex,
1260
+ "Redemption transaction input must point to the wallet's main UTXO"
1261
+ );
1262
+ }
1263
+
1264
+ /// @notice Processes the Bitcoin redemption transaction input vector. It
1265
+ /// extracts the single input then the transaction hash and output
1266
+ /// index from its outpoint.
1267
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1268
+ /// vector. This function assumes vector's structure is valid so it
1269
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1270
+ /// before it is passed here
1271
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1272
+ /// pointed in the input's outpoint.
1273
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1274
+ /// which is pointed in the input's outpoint.
1275
+ function processRedemptionTxInput(bytes memory redemptionTxInputVector)
1276
+ internal
1277
+ pure
1278
+ returns (bytes32 outpointTxHash, uint32 outpointIndex)
1279
+ {
1280
+ // To determine the total number of redemption transaction inputs,
1281
+ // we need to parse the compactSize uint (VarInt) the input vector is
1282
+ // prepended by. That compactSize uint encodes the number of vector
1283
+ // elements using the format presented in:
1284
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1285
+ // We don't need asserting the compactSize uint is parseable since it
1286
+ // was already checked during `validateVin` validation.
1287
+ // See `BitcoinTx.inputVector` docs for more details.
1288
+ (, uint256 inputsCount) = redemptionTxInputVector.parseVarInt();
1289
+ require(
1290
+ inputsCount == 1,
1291
+ "Redemption transaction must have a single input"
1292
+ );
1293
+
1294
+ bytes memory input = redemptionTxInputVector.extractInputAtIndex(0);
1295
+
1296
+ outpointTxHash = input.extractInputTxIdLE();
1297
+
1298
+ outpointIndex = BTCUtils.reverseUint32(
1299
+ uint32(input.extractTxIndexLE())
1300
+ );
1301
+
1302
+ // There is only one input in the transaction. Input has an outpoint
1303
+ // field that is a reference to the transaction being spent (see
1304
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1305
+ // to spend (`outpointTxHash`) and the index of the specific output
1306
+ // from that transaction (`outpointIndex`).
1307
+ return (outpointTxHash, outpointIndex);
1308
+ }
1309
+
1310
+ /// @notice Processes the Bitcoin redemption transaction output vector.
1311
+ /// It extracts each output and tries to identify it as a pending
1312
+ /// redemption request, reported timed out request, or change.
1313
+ /// Reverts if one of the outputs cannot be recognized properly.
1314
+ /// This function also marks each request as processed by removing
1315
+ /// them from `pendingRedemptions` mapping.
1316
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1317
+ /// vector. This function assumes vector's structure is valid so it
1318
+ /// must be validated using e.g. `BTCUtils.validateVout` function
1319
+ /// before it is passed here
1320
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1321
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1322
+ /// performed the redemption transaction.
1323
+ /// @return info Outcomes of the processing.
1324
+ function processRedemptionTxOutputs(
1325
+ bytes memory redemptionTxOutputVector,
1326
+ bytes20 walletPubKeyHash
1327
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
1328
+ // Determining the total number of redemption transaction outputs in
1329
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
1330
+ // docs for more details.
1331
+ (
1332
+ uint256 outputsCompactSizeUintLength,
1333
+ uint256 outputsCount
1334
+ ) = redemptionTxOutputVector.parseVarInt();
1335
+
1336
+ // To determine the first output starting index, we must jump over
1337
+ // the compactSize uint which prepends the output vector. One byte
1338
+ // must be added because `BtcUtils.parseVarInt` does not include
1339
+ // compactSize uint tag in the returned length.
1340
+ //
1341
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1342
+ // returns `0`, so we jump over one byte of compactSize uint.
1343
+ //
1344
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1345
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1346
+ // tag byte included) so we need to jump over 1+2 bytes of
1347
+ // compactSize uint.
1348
+ //
1349
+ // Please refer `BTCUtils` library and compactSize uint
1350
+ // docs in `BitcoinTx` library for more details.
1351
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1352
+
1353
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1354
+ // scripts that can be used to lock the change. This is done upfront to
1355
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
1356
+ //
1357
+ // The P2PKH script has format <0x1976a914> <20-byte PKH> <0x88ac>.
1358
+ bytes32 walletP2PKHScriptKeccak = keccak256(
1359
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1360
+ );
1361
+ // The P2WPKH script has format <0x160014> <20-byte PKH>.
1362
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
1363
+ abi.encodePacked(hex"160014", walletPubKeyHash)
1364
+ );
1365
+
1366
+ // Helper variable that counts the number of processed redemption
1367
+ // outputs. Redemptions can be either pending or reported as timed out.
1368
+ // TODO: Revisit the approach with redemptions count according to
1369
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1370
+ uint256 processedRedemptionsCount = 0;
1371
+
1372
+ // Outputs processing loop.
1373
+ for (uint256 i = 0; i < outputsCount; i++) {
1374
+ // TODO: Check if we can optimize gas costs by adding
1375
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1376
+ // in order to avoid allocating bytes in memory.
1377
+ uint256 outputLength = redemptionTxOutputVector
1378
+ .determineOutputLengthAt(outputStartingIndex);
1379
+ bytes memory output = redemptionTxOutputVector.slice(
1380
+ outputStartingIndex,
1381
+ outputLength
1382
+ );
1383
+
1384
+ // Extract the value from given output.
1385
+ uint64 outputValue = output.extractValue();
1386
+ // The output consists of an 8-byte value and a variable length
1387
+ // script. To extract that script we slice the output staring from
1388
+ // 9th byte until the end.
1389
+ bytes memory outputScript = output.slice(8, output.length - 8);
1390
+
1391
+ if (
1392
+ info.changeValue == 0 &&
1393
+ (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1394
+ keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1395
+ outputValue > 0
1396
+ ) {
1397
+ // If we entered here, that means the change output with a
1398
+ // proper non-zero value was found.
1399
+ info.changeIndex = uint32(i);
1400
+ info.changeValue = outputValue;
1401
+ } else {
1402
+ // If we entered here, that the means the given output is
1403
+ // supposed to represent a redemption. Build the redemption key
1404
+ // to perform that check.
1405
+ uint256 redemptionKey = uint256(
1406
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
1407
+ );
1408
+
1409
+ if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1410
+ // If we entered here, that means the output was identified
1411
+ // as a pending redemption request.
1412
+ RedemptionRequest storage request = pendingRedemptions[
1413
+ redemptionKey
1414
+ ];
1415
+ // Compute the request's redeemable amount as the requested
1416
+ // amount reduced by the treasury fee. The request's
1417
+ // minimal amount is then the redeemable amount reduced by
1418
+ // the maximum transaction fee.
1419
+ uint64 redeemableAmount = request.requestedAmount -
1420
+ request.treasuryFee;
1421
+ // Output value must fit between the request's redeemable
1422
+ // and minimal amounts to be deemed valid.
1423
+ require(
1424
+ redeemableAmount - request.txMaxFee <= outputValue &&
1425
+ outputValue <= redeemableAmount,
1426
+ "Output value is not within the acceptable range of the pending request"
1427
+ );
1428
+ // Add the redeemable amount to the total burnable value
1429
+ // the Bridge will use to decrease its balance in the Bank.
1430
+ info.totalBurnableValue += redeemableAmount;
1431
+ // Add the request's treasury fee to the total treasury fee
1432
+ // value the Bridge will transfer to the treasury.
1433
+ info.totalTreasuryFee += request.treasuryFee;
1434
+ // Request was properly handled so remove its redemption
1435
+ // key from the mapping to make it reusable for further
1436
+ // requests.
1437
+ delete pendingRedemptions[redemptionKey];
1438
+
1439
+ processedRedemptionsCount++;
1440
+ } else {
1441
+ // If we entered here, the output is not a redemption
1442
+ // request but there is still a chance the given output is
1443
+ // related to a reported timed out redemption request.
1444
+ // If so, check if the output value matches the request
1445
+ // amount to confirm this is an overdue request fulfillment
1446
+ // then bypass this output and process the subsequent
1447
+ // ones. That also means the wallet was already punished
1448
+ // for the inactivity. Otherwise, just revert.
1449
+ RedemptionRequest storage request = timedOutRedemptions[
1450
+ redemptionKey
1451
+ ];
1452
+
1453
+ require(
1454
+ request.requestedAt != 0,
1455
+ "Output is a non-requested redemption"
1456
+ );
1457
+
1458
+ uint64 redeemableAmount = request.requestedAmount -
1459
+ request.treasuryFee;
1460
+
1461
+ require(
1462
+ redeemableAmount - request.txMaxFee <= outputValue &&
1463
+ outputValue <= redeemableAmount,
1464
+ "Output value is not within the acceptable range of the timed out request"
1465
+ );
1466
+
1467
+ processedRedemptionsCount++;
1468
+ }
1469
+ }
1470
+
1471
+ // Make the `outputStartingIndex` pointing to the next output by
1472
+ // increasing it by current output's length.
1473
+ outputStartingIndex += outputLength;
1474
+ }
1475
+
1476
+ // Protect against the cases when there is only a single change output
1477
+ // referring back to the wallet PKH and just burning main UTXO value
1478
+ // for transaction fees.
1479
+ require(
1480
+ processedRedemptionsCount > 0,
1481
+ "Redemption transaction must process at least one redemption"
1482
+ );
1483
+
1484
+ return info;
795
1485
  }
796
1486
 
797
- // TODO It is possible a malicious wallet can sweep deposits that can not
798
- // be later proved on Ethereum. For example, a deposit with
799
- // an incorrect amount revealed. We need to provide a function for honest
800
- // depositors, next to sweep, to prove their swept balances on Ethereum
801
- // selectively, based on deposits they have earlier received.
802
- // (UPDATE PR #90: Is it still the case since amounts are inferred?)
1487
+ // TODO: Function `notifyRedemptionTimeout. That function must:
1488
+ // 1. Take a the `walletPubKey` and `redeemerOutputScript` as params.
1489
+ // 2. Build the redemption key using those params.
1490
+ // 3. Use the redemption key and take the request from
1491
+ // `pendingRedemptions` mapping.
1492
+ // 4. If request doesn't exist in mapping - revert.
1493
+ // 5. If request exits, and is timed out - remove the redemption key
1494
+ // from `pendingRedemptions` and put it to `timedOutRedemptions`
1495
+ // by copying the entire `RedemptionRequest` struct there. No need
1496
+ // to check if `timedOutRedemptions` mapping already contains
1497
+ // that key because `requestRedemption` blocks requests targeting
1498
+ // non-active wallets. Because `notifyRedemptionTimeout` changes
1499
+ // wallet state after first call (point 9), there is no possibility
1500
+ // that the given redemption key could be reported as timed out
1501
+ // multiple times. At the same time, if the given redemption key
1502
+ // was already marked as fraudulent due to an amount-related fraud,
1503
+ // it will not be possible to report a time out on it since it
1504
+ // won't be present in `pendingRedemptions` mapping.
1505
+ // 6. Return the `requestedAmount` to the `redeemer`.
1506
+ // 7. Reduce the `pendingRedemptionsValue` (`wallets` mapping) for
1507
+ // given wallet by request's redeemable amount computed as
1508
+ // `requestedAmount - treasuryFee`.
1509
+ // 8. Punish the wallet, probably by slashing its operators.
1510
+ // 9. Change wallet's state in `wallets` mapping to `MovingFunds` in
1511
+ // order to prevent against new redemption requests hitting
1512
+ // that wallet.
1513
+ // 10. Expect the wallet to transfer its funds to another healthy
1514
+ // wallet (just as in case of failed heartbeat). The wallet is
1515
+ // expected to finish the already queued redemption requests
1516
+ // before moving funds but we are not going to enforce it on-chain.
1517
+
1518
+ // TODO: Function `submitRedemptionFraudProof`
1519
+ //
1520
+ // Deposit and redemption fraud proofs are challenging to implement
1521
+ // and it may happen we will have to rely on the coverage pool
1522
+ // (https://github.com/keep-network/coverage-pools) and DAO to
1523
+ // reimburse unlucky depositors and bring back the balance to the
1524
+ // system in case of a wallet fraud by liquidating a part of the
1525
+ // coverage pool manually.
1526
+ //
1527
+ // The probability of 51-of-100 wallet being fraudulent is negligible:
1528
+ // https://github.com/keep-network/tbtc-v2/blob/main/docs/rfc/rfc-2.adoc#111-group-size-and-threshold
1529
+ // and the coverage pool would be there to bring the balance back in
1530
+ // case we are unlucky and malicious wallet emerges.
1531
+ //
1532
+ // We do not want to slash for a misbehavior that is not provable
1533
+ // on-chain and it is possible to construct such a Bitcoin transaction
1534
+ // that is not provable on Ethereum, see
1535
+ // https://consensys.net/diligence/blog/2020/05/tbtc-navigating-the-cross-chain-conundrum
1536
+ //
1537
+ // The algorithm described below assumes we will be able to prove the
1538
+ // TX on Ethereum which may not always be the case. Consider the steps
1539
+ // below as an idea, and not necessarily how this function will be
1540
+ // implemented because it may happen this function will never be
1541
+ // implemented, given the Bitcoin transaction size problems.
1542
+ //
1543
+ // The algorithm:
1544
+ // 1. Take a `BitcoinTx.Info` and `BitcoinTx.Proof` of the
1545
+ // fraudulent transaction. It should also accept `walletPubKeyHash`
1546
+ // and index of fraudulent output. Probably index of fraudulent
1547
+ // input will be also required if the transaction is supposed
1548
+ // to have a bad input vector.
1549
+ // 2. Perform SPV proof to make sure it occurred on Bitcoin chain.
1550
+ // If not - revert.
1551
+ // 3. Check if wallet state is Active or MovingFunds. If not, revert.
1552
+ // 4. Validate the number of inputs. If there is one input and it
1553
+ // points to the wallet's main UTXO - move to point 5. If there
1554
+ // are multiple inputs and there is wallet's main UTXO in the set,
1555
+ // check if this is a sweep transaction. If it's not a sweep,
1556
+ // consider it as fraudulent and move to point 6.
1557
+ // In all other cases revert the call.
1558
+ // 5. Extract the output and analyze its type. The output is not
1559
+ // a fraud and the call should be reverted ONLY IF one of the
1560
+ // following conditions is true:
1561
+ // - Output is a requested redemption held by `pendingRedemptions`
1562
+ // and output value fulfills the request range. There is an
1563
+ // open question if a misfunded request should be removed
1564
+ // from `pendingRedemptions` (probably yes) and whether the
1565
+ // redeemer should be reimbursed in case of an underfund.
1566
+ // - Output is a timed out redemption held by `timedOutRedemptions`
1567
+ // and output value fulfills the request range.
1568
+ // - Output is a proper change i.e. a single output targeting
1569
+ // the wallet PKH back and having a non-zero value.
1570
+ // - Wallet is in MovingFunds state, the output points to the
1571
+ // expected target wallet, have non-zero value, and is a single
1572
+ // output in the vector.
1573
+ // In all other cases consider the transaction as fraud and
1574
+ // proceed to point 6.
1575
+ // 6. Punish the wallet, probably by severely slashing its operators.
1576
+ // 7. Change wallet's state in `wallets` mapping to `Terminated` in
1577
+ // order to prevent against new redemption requests hitting
1578
+ // that wallet. This also prevents against reporting a fraud
1579
+ // multiple times for one transaction (see point 3) and blocks
1580
+ // submission of sweep and redemption proofs. `Terminated` wallet
1581
+ // is blocked in the Bridge forever. If the fraud was a mistake
1582
+ // done by the wallet and the wallet is still honest deep in its
1583
+ // heart, the wallet can coordinate off-chain to recover the BTC
1584
+ // and donate it to another wallet. If they recover all of the
1585
+ // remaining BTC, DAO might decide to reward them with tokens so
1586
+ // that they can have at least some portion of their slashed
1587
+ // tokens back.
803
1588
  }