@keep-network/tbtc-v2 0.1.1-dev.10 → 0.1.1-dev.14

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 (24) hide show
  1. package/artifacts/TBTC.json +18 -18
  2. package/artifacts/TBTCToken.json +18 -18
  3. package/artifacts/VendingMachine.json +19 -19
  4. package/artifacts/solcInputs/{524094faac10a04084fcc411e06dab84.json → 074b94f943fca615dfc6fce3bc4f2e1f.json} +18 -6
  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 +530 -29
  13. package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +4 -0
  14. package/build/contracts/bridge/Bridge.sol/IRelay.json +37 -0
  15. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  16. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  17. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  18. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  19. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  20. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  21. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +2 -2
  22. package/contracts/bridge/BitcoinTx.sol +22 -0
  23. package/contracts/bridge/Bridge.sol +1313 -58
  24. package/package.json +2 -2
@@ -19,9 +19,25 @@ 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
25
 
26
+ import "../bank/Bank.sol";
23
27
  import "./BitcoinTx.sol";
24
28
 
29
+ /// @title Interface for the Bitcoin relay
30
+ /// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay
31
+ /// provides the difficulty of the previous and current epoch. One
32
+ /// difficulty epoch spans 2016 blocks.
33
+ interface IRelay {
34
+ /// @notice Returns the difficulty of the current epoch.
35
+ function getCurrentEpochDifficulty() external view returns (uint256);
36
+
37
+ /// @notice Returns the difficulty of the previous epoch.
38
+ function getPrevEpochDifficulty() external view returns (uint256);
39
+ }
40
+
25
41
  /// @title Bitcoin Bridge
26
42
  /// @notice Bridge manages BTC deposit and redemption flow and is increasing and
27
43
  /// decreasing balances in the Bank as a result of BTC deposit and
@@ -43,13 +59,16 @@ import "./BitcoinTx.sol";
43
59
  /// @dev Bridge is an upgradeable component of the Bank.
44
60
  contract Bridge is Ownable {
45
61
  using BTCUtils for bytes;
62
+ using BTCUtils for uint256;
46
63
  using BytesLib for bytes;
64
+ using ValidateSPV for bytes;
65
+ using ValidateSPV for bytes32;
47
66
 
48
67
  /// @notice Represents data which must be revealed by the depositor during
49
68
  /// deposit reveal.
50
69
  struct RevealInfo {
51
70
  // Index of the funding output belonging to the funding transaction.
52
- uint8 fundingOutputIndex;
71
+ uint32 fundingOutputIndex;
53
72
  // Ethereum depositor address.
54
73
  address depositor;
55
74
  // The blinding factor as 8 bytes. Byte endianness doesn't matter
@@ -74,19 +93,129 @@ contract Bridge is Ownable {
74
93
  }
75
94
 
76
95
  /// @notice Represents tBTC deposit data.
77
- struct DepositInfo {
96
+ struct DepositRequest {
78
97
  // Ethereum depositor address.
79
98
  address depositor;
80
- // Deposit amount in satoshi (8-byte LE). For example:
81
- // 0.0001 BTC = 10000 satoshi = 0x1027000000000000
82
- bytes8 amount;
99
+ // Deposit amount in satoshi.
100
+ uint64 amount;
83
101
  // UNIX timestamp the deposit was revealed at.
84
102
  uint32 revealedAt;
85
103
  // Address of the Bank vault the deposit is routed to.
86
104
  // Optional, can be 0x0.
87
105
  address vault;
106
+ // UNIX timestamp the deposit was swept at. Note this is not the
107
+ // time when the deposit was swept on the Bitcoin chain but actually
108
+ // the time when the sweep proof was delivered to the Ethereum chain.
109
+ uint32 sweptAt;
110
+ }
111
+
112
+ /// @notice Represents a redemption request.
113
+ struct RedemptionRequest {
114
+ // ETH address of the redeemer who created the request.
115
+ address redeemer;
116
+ // Requested TBTC amount in satoshi.
117
+ uint64 requestedAmount;
118
+ // Treasury TBTC fee in satoshi at the moment of request creation.
119
+ uint64 treasuryFee;
120
+ // Transaction maximum BTC fee in satoshi at the moment of request
121
+ // creation.
122
+ uint64 txMaxFee;
123
+ // UNIX timestamp the request was created at.
124
+ uint32 requestedAt;
125
+ }
126
+
127
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
128
+ /// outputs processing.
129
+ struct RedemptionTxOutputsInfo {
130
+ // Total TBTC value in satoshi that should be burned by the Bridge.
131
+ // It includes the total amount of all BTC redeemed in the transaction
132
+ // and the fee paid to BTC miners for the redemption transaction.
133
+ uint64 totalBurnableValue;
134
+ // Total TBTC value in satoshi that should be transferred to
135
+ // the treasury. It is a sum of all treasury fees paid by all
136
+ // redeemers included in the redemption transaction.
137
+ uint64 totalTreasuryFee;
138
+ // Index of the change output. The change output becomes
139
+ // the new main wallet's UTXO.
140
+ uint32 changeIndex;
141
+ // Value in satoshi of the change output.
142
+ uint64 changeValue;
88
143
  }
89
144
 
145
+ /// @notice Represents wallet state:
146
+ enum WalletState {
147
+ /// @dev The wallet is unknown to the Bridge.
148
+ Unknown,
149
+ /// @dev The wallet can sweep deposits and accept redemption requests.
150
+ Active,
151
+ /// @dev The wallet was deemed unhealthy and is expected to move their
152
+ /// outstanding funds to another wallet. The wallet can still
153
+ /// fulfill their pending redemption requests although new
154
+ /// redemption requests and new deposit reveals are not accepted.
155
+ MovingFunds,
156
+ /// @dev The wallet moved or redeemed all their funds and cannot
157
+ /// perform any action.
158
+ Closed,
159
+ /// @dev The wallet committed a fraud that was reported. The wallet is
160
+ /// blocked and can not perform any actions in the Bridge.
161
+ /// Off-chain coordination with the wallet operators is needed to
162
+ /// recover funds.
163
+ Terminated
164
+ }
165
+
166
+ /// @notice Holds information about a wallet.
167
+ struct Wallet {
168
+ // Current state of the wallet.
169
+ WalletState state;
170
+ // The total redeemable value of pending redemption requests targeting
171
+ // that wallet.
172
+ uint64 pendingRedemptionsValue;
173
+ }
174
+
175
+ /// @notice The number of confirmations on the Bitcoin chain required to
176
+ /// successfully evaluate an SPV proof.
177
+ uint256 public immutable txProofDifficultyFactor;
178
+
179
+ /// TODO: Revisit whether it should be governable or not.
180
+ /// @notice Address of the Bank this Bridge belongs to.
181
+ Bank public immutable bank;
182
+
183
+ /// TODO: Make it governable.
184
+ /// @notice Handle to the Bitcoin relay.
185
+ IRelay public immutable relay;
186
+
187
+ /// TODO: Revisit whether it should be governable or not.
188
+ /// @notice Address where the redemptions treasury fees will be sent to.
189
+ /// Treasury takes part in the operators rewarding process.
190
+ address public immutable treasury;
191
+
192
+ /// TODO: Make it governable.
193
+ /// @notice The minimal amount that can be requested for redemption.
194
+ /// Value of this parameter should be always bigger than the sum
195
+ /// of `redemptionTreasuryFee` and `redemptionTxMaxFee` to make
196
+ /// redemptions possible.
197
+ uint64 public redemptionDustThreshold;
198
+
199
+ /// TODO: Make it governable.
200
+ /// @notice Amount of TBTC that is taken from each redemption request and
201
+ /// transferred to the treasury upon successful request finalization.
202
+ uint64 public redemptionTreasuryFee;
203
+
204
+ /// TODO: Make it governable.
205
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
206
+ /// each redemption request being part of the given redemption
207
+ /// transaction. If the maximum BTC transaction fee is exceeded, such
208
+ /// transaction is considered a fraud.
209
+ uint64 public redemptionTxMaxFee;
210
+
211
+ /// TODO: Make it governable.
212
+ /// @notice Time after which the redemption request can be reported as
213
+ /// timed out. It is counted from the moment when the redemption
214
+ /// request was created via `requestRedemption` call. Reported
215
+ /// timed out requests are cancelled and locked TBTC is returned
216
+ /// to the redeemer in full amount.
217
+ uint256 public redemptionTimeout;
218
+
90
219
  /// @notice Indicates if the vault with the given address is trusted or not.
91
220
  /// Depositors can route their revealed deposits only to trusted
92
221
  /// vaults and have trusted vaults notified about new deposits as
@@ -96,20 +225,75 @@ contract Bridge is Ownable {
96
225
  /// address.
97
226
  mapping(address => bool) public isVaultTrusted;
98
227
 
99
- /// @notice Collection of all unswept deposits indexed by
228
+ /// @notice Collection of all revealed deposits indexed by
100
229
  /// keccak256(fundingTxHash | fundingOutputIndex).
101
- /// The fundingTxHash is LE bytes32 and fundingOutputIndex an uint8.
102
- /// This mapping may contain valid and invalid deposits and the
103
- /// wallet is responsible for validating them before attempting to
104
- /// execute a sweep.
230
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
231
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
232
+ /// and invalid deposits and the wallet is responsible for
233
+ /// validating them before attempting to execute a sweep.
234
+ mapping(uint256 => DepositRequest) public deposits;
235
+
236
+ /// @notice Maps the 20-byte wallet public key hash (computed using
237
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to
238
+ /// the latest wallet's main UTXO computed as
239
+ /// keccak256(txHash | txOutputIndex | txOutputValue). The `tx`
240
+ /// prefix refers to the transaction which created that main UTXO.
241
+ /// The txHash is bytes32 (ordered as in Bitcoin internally),
242
+ /// txOutputIndex an uint32, and txOutputValue an uint64 value.
243
+ mapping(bytes20 => bytes32) public mainUtxos;
244
+
245
+ /// @notice Collection of all pending redemption requests indexed by
246
+ /// redemption key built as
247
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
248
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
249
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
250
+ /// public key) and redeemerOutputScript is a Bitcoin script
251
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
252
+ /// redeemed BTC as requested by the redeemer. Requests are added
253
+ /// to this mapping by the `requestRedemption` method (duplicates
254
+ /// not allowed) and are removed by one of the following methods:
255
+ /// - `submitRedemptionProof` in case the request was handled
256
+ /// successfully
257
+ /// - `notifyRedemptionTimeout` in case the request was reported
258
+ /// to be timed out
259
+ /// - `submitRedemptionFraudProof` in case the request was handled
260
+ /// in an fraudulent way amount-wise.
261
+ mapping(uint256 => RedemptionRequest) public pendingRedemptions;
262
+
263
+ /// @notice Collection of all timed out redemptions requests indexed by
264
+ /// redemption key built as
265
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
266
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
267
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
268
+ /// public key) and redeemerOutputScript is the Bitcoin script
269
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
270
+ /// out request. Timed out requests are stored in this mapping to
271
+ /// avoid slashing the wallets multiple times for the same timeout.
272
+ /// Only one method can add to this mapping:
273
+ /// - `notifyRedemptionTimeout` which puts the redemption key
274
+ /// to this mapping basing on a timed out request stored
275
+ /// previously in `pendingRedemptions` mapping.
105
276
  ///
106
- /// TODO: Explore the possibility of storing just a hash of DepositInfo.
107
- mapping(uint256 => DepositInfo) public unswept;
277
+ // TODO: Remove that Slither disable once this variable is used.
278
+ // slither-disable-next-line uninitialized-state
279
+ mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
280
+
281
+ /// @notice Maps the 20-byte wallet public key hash (computed using
282
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to the
283
+ /// basic wallet information like state and pending
284
+ /// redemptions value.
285
+ ///
286
+ // TODO: Remove that Slither disable once this variable is used.
287
+ // slither-disable-next-line uninitialized-state
288
+ mapping(bytes20 => Wallet) public wallets;
289
+
290
+ event VaultStatusUpdated(address indexed vault, bool isTrusted);
108
291
 
109
292
  event DepositRevealed(
110
293
  bytes32 fundingTxHash,
111
- uint8 fundingOutputIndex,
294
+ uint32 fundingOutputIndex,
112
295
  address depositor,
296
+ uint64 amount,
113
297
  bytes8 blindingFactor,
114
298
  bytes20 walletPubKeyHash,
115
299
  bytes20 refundPubKeyHash,
@@ -117,7 +301,48 @@ contract Bridge is Ownable {
117
301
  address vault
118
302
  );
119
303
 
120
- event VaultStatusUpdated(address indexed vault, bool isTrusted);
304
+ event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
305
+
306
+ event RedemptionRequested(
307
+ bytes20 walletPubKeyHash,
308
+ bytes redeemerOutputScript,
309
+ address redeemer,
310
+ uint64 requestedAmount,
311
+ uint64 treasuryFee,
312
+ uint64 txMaxFee
313
+ );
314
+
315
+ event RedemptionsCompleted(
316
+ bytes20 walletPubKeyHash,
317
+ bytes32 redemptionTxHash
318
+ );
319
+
320
+ constructor(
321
+ address _bank,
322
+ address _relay,
323
+ address _treasury,
324
+ uint256 _txProofDifficultyFactor
325
+ ) {
326
+ require(_bank != address(0), "Bank address cannot be zero");
327
+ bank = Bank(_bank);
328
+
329
+ require(_relay != address(0), "Relay address cannot be zero");
330
+ relay = IRelay(_relay);
331
+
332
+ require(_treasury != address(0), "Treasury address cannot be zero");
333
+ treasury = _treasury;
334
+
335
+ txProofDifficultyFactor = _txProofDifficultyFactor;
336
+
337
+ // TODO: Revisit initial values.
338
+ redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
339
+ redemptionTreasuryFee = 100000; // 100000 satoshi
340
+ redemptionTxMaxFee = 1000; // 1000 satoshi
341
+ redemptionTimeout = 172800; // 48 hours
342
+ }
343
+
344
+ // TODO: Add function `onNewWalletCreated` according to discussion:
345
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r809885230
121
346
 
122
347
  /// @notice Allows the Governance to mark the given vault address as trusted
123
348
  /// or no longer trusted. Vaults are not trusted by default.
@@ -179,6 +404,9 @@ contract Bridge is Ownable {
179
404
  "Vault is not trusted"
180
405
  );
181
406
 
407
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
408
+ // TODO: Should we enforce a specific locktime at contract level?
409
+
182
410
  bytes memory expectedScript =
183
411
  abi.encodePacked(
184
412
  hex"14", // Byte length of depositor Ethereum address.
@@ -224,8 +452,7 @@ contract Bridge is Ownable {
224
452
  // P2PKH and P2WPKH, it will fail on the output hash comparison with
225
453
  // the expected locking script hash.
226
454
  require(
227
- keccak256(fundingOutputHash) ==
228
- keccak256(expectedScript.hash160()),
455
+ fundingOutputHash.slice20(0) == expectedScript.hash160View(),
229
456
  "Wrong 20-byte script hash"
230
457
  );
231
458
  } else if (fundingOutputHash.length == 32) {
@@ -252,10 +479,10 @@ contract Bridge is Ownable {
252
479
  fundingTx
253
480
  .locktime
254
481
  )
255
- .hash256();
482
+ .hash256View();
256
483
 
257
- DepositInfo storage deposit =
258
- unswept[
484
+ DepositRequest storage deposit =
485
+ deposits[
259
486
  uint256(
260
487
  keccak256(
261
488
  abi.encodePacked(
@@ -267,15 +494,9 @@ contract Bridge is Ownable {
267
494
  ];
268
495
  require(deposit.revealedAt == 0, "Deposit already revealed");
269
496
 
270
- bytes8 fundingOutputAmount;
271
- /* solhint-disable-next-line no-inline-assembly */
272
- assembly {
273
- // First 8 bytes (little-endian) of the funding output represents
274
- // its value. To take the value, we need to jump over the first
275
- // word determining the array length, load the array, and trim it
276
- // by putting it to a bytes8.
277
- fundingOutputAmount := mload(add(fundingOutput, 32))
278
- }
497
+ uint64 fundingOutputAmount = fundingOutput.extractValue();
498
+
499
+ // TODO: Check the amount against the dust threshold.
279
500
 
280
501
  deposit.amount = fundingOutputAmount;
281
502
  deposit.depositor = reveal.depositor;
@@ -287,6 +508,7 @@ contract Bridge is Ownable {
287
508
  fundingTxHash,
288
509
  reveal.fundingOutputIndex,
289
510
  reveal.depositor,
511
+ fundingOutputAmount,
290
512
  reveal.blindingFactor,
291
513
  reveal.walletPubKeyHash,
292
514
  reveal.refundPubKeyHash,
@@ -306,41 +528,1074 @@ contract Bridge is Ownable {
306
528
  /// during the reveal transaction, minus their fee share.
307
529
  ///
308
530
  /// It is possible to prove the given sweep only one time.
309
- /// @param sweepTx Bitcoin sweep transaction data.
310
- /// @param merkleProof The merkle proof of transaction inclusion in a block.
311
- /// @param txIndexInBlock Transaction index in the block (0-indexed).
312
- /// @param bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
313
- /// lowest height first.
314
- function sweep(
531
+ /// @param sweepTx Bitcoin sweep transaction data
532
+ /// @param sweepProof Bitcoin sweep proof data
533
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
534
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
535
+ /// this parameter is ignored
536
+ /// @dev Requirements:
537
+ /// - `sweepTx` components must match the expected structure. See
538
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
539
+ /// correspond to appropriate Bitcoin transaction fields to produce
540
+ /// a provable transaction hash.
541
+ /// - The `sweepTx` should represent a Bitcoin transaction with 1..n
542
+ /// inputs. If the wallet has no main UTXO, all n inputs should
543
+ /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has
544
+ /// an existing main UTXO, one of the n inputs must point to that
545
+ /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH
546
+ /// revealed deposits UTXOs. That transaction must have only
547
+ /// one P2(W)PKH output locking funds on the 20-byte wallet public
548
+ /// key hash.
549
+ /// - `sweepProof` components must match the expected structure. See
550
+ /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
551
+ /// field must contain a valid number of block headers, not less
552
+ /// than the `txProofDifficultyFactor` contract constant.
553
+ /// - `mainUtxo` components must point to the recent main UTXO
554
+ /// of the given wallet, as currently known on the Ethereum chain.
555
+ /// If there is no main UTXO, this parameter is ignored.
556
+ function submitSweepProof(
315
557
  BitcoinTx.Info calldata sweepTx,
316
- bytes memory merkleProof,
317
- uint256 txIndexInBlock,
318
- bytes memory bitcoinHeaders
558
+ BitcoinTx.Proof calldata sweepProof,
559
+ BitcoinTx.UTXO calldata mainUtxo
560
+ ) external {
561
+ // TODO: Fail early if the function call gets frontrunned. See discussion:
562
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
563
+
564
+ // The actual transaction proof is performed here. After that point, we
565
+ // can assume the transaction happened on Bitcoin chain and has
566
+ // a sufficient number of confirmations as determined by
567
+ // `txProofDifficultyFactor` constant.
568
+ bytes32 sweepTxHash = validateBitcoinTxProof(sweepTx, sweepProof);
569
+
570
+ // Process sweep transaction output and extract its target wallet
571
+ // public key hash and value.
572
+ (bytes20 walletPubKeyHash, uint64 sweepTxOutputValue) =
573
+ processSweepTxOutput(sweepTx.outputVector);
574
+
575
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
576
+
577
+ // Check if the main UTXO for given wallet exists. If so, validate
578
+ // passed main UTXO data against the stored hash and use them for
579
+ // further processing. If no main UTXO exists, use empty data.
580
+ BitcoinTx.UTXO memory resolvedMainUtxo =
581
+ BitcoinTx.UTXO(bytes32(0), 0, 0);
582
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
583
+ if (mainUtxoHash != bytes32(0)) {
584
+ require(
585
+ keccak256(
586
+ abi.encodePacked(
587
+ mainUtxo.txHash,
588
+ mainUtxo.txOutputIndex,
589
+ mainUtxo.txOutputValue
590
+ )
591
+ ) == mainUtxoHash,
592
+ "Invalid main UTXO data"
593
+ );
594
+ resolvedMainUtxo = mainUtxo;
595
+ }
596
+
597
+ // Process sweep transaction inputs and extract their value sum and
598
+ // all information needed to perform deposit bookkeeping.
599
+ (
600
+ uint256 sweepTxInputsValue,
601
+ address[] memory depositors,
602
+ uint256[] memory depositedAmounts
603
+ ) = processSweepTxInputs(sweepTx.inputVector, resolvedMainUtxo);
604
+
605
+ // Compute the sweep transaction fee which is a difference between
606
+ // inputs amounts sum and the output amount.
607
+ // TODO: Check fee against max fee.
608
+ uint256 fee = sweepTxInputsValue - sweepTxOutputValue;
609
+ // Calculate fee share by dividing the total fee by deposits count.
610
+ // TODO: Deal with precision loss by having the last depositor pay
611
+ // the higher fee than others if there is a change, just like it has
612
+ // been proposed for the redemption flow. See:
613
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r800555359.
614
+ uint256 feeShare = fee / depositedAmounts.length;
615
+ // Reduce each deposit amount by fee share value.
616
+ for (uint256 i = 0; i < depositedAmounts.length; i++) {
617
+ // We don't have to check if `feeShare` is bigger than the amount
618
+ // since we have the dust threshold preventing against too small
619
+ // deposits amounts.
620
+ depositedAmounts[i] -= feeShare;
621
+ }
622
+
623
+ // Record this sweep data and assign them to the wallet public key hash
624
+ // as new main UTXO. Transaction output index is always 0 as sweep
625
+ // transaction always contains only one output.
626
+ mainUtxos[walletPubKeyHash] = keccak256(
627
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
628
+ );
629
+
630
+ emit DepositsSwept(walletPubKeyHash, sweepTxHash);
631
+
632
+ // Update depositors balances in the Bank.
633
+ bank.increaseBalances(depositors, depositedAmounts);
634
+
635
+ // TODO: Handle deposits having `vault` set.
636
+ }
637
+
638
+ /// @notice Validates the SPV proof of the Bitcoin transaction.
639
+ /// Reverts in case the validation or proof verification fail.
640
+ /// @param txInfo Bitcoin transaction data
641
+ /// @param proof Bitcoin proof data
642
+ /// @return txHash Proven 32-byte transaction hash.
643
+ function validateBitcoinTxProof(
644
+ BitcoinTx.Info calldata txInfo,
645
+ BitcoinTx.Proof calldata proof
646
+ ) internal view returns (bytes32 txHash) {
647
+ require(
648
+ txInfo.inputVector.validateVin(),
649
+ "Invalid input vector provided"
650
+ );
651
+ require(
652
+ txInfo.outputVector.validateVout(),
653
+ "Invalid output vector provided"
654
+ );
655
+
656
+ txHash = abi
657
+ .encodePacked(
658
+ txInfo
659
+ .version,
660
+ txInfo
661
+ .inputVector,
662
+ txInfo
663
+ .outputVector,
664
+ txInfo
665
+ .locktime
666
+ )
667
+ .hash256View();
668
+
669
+ checkProofFromTxHash(txHash, proof);
670
+
671
+ return txHash;
672
+ }
673
+
674
+ /// @notice Checks the given Bitcoin transaction hash against the SPV proof.
675
+ /// Reverts in case the check fails.
676
+ /// @param txHash 32-byte hash of the checked Bitcoin transaction
677
+ /// @param proof Bitcoin proof data
678
+ function checkProofFromTxHash(
679
+ bytes32 txHash,
680
+ BitcoinTx.Proof calldata proof
681
+ ) internal view {
682
+ require(
683
+ txHash.prove(
684
+ proof.bitcoinHeaders.extractMerkleRootLE(),
685
+ proof.merkleProof,
686
+ proof.txIndexInBlock
687
+ ),
688
+ "Tx merkle proof is not valid for provided header and tx hash"
689
+ );
690
+
691
+ evaluateProofDifficulty(proof.bitcoinHeaders);
692
+ }
693
+
694
+ /// @notice Evaluates the given Bitcoin proof difficulty against the actual
695
+ /// Bitcoin chain difficulty provided by the relay oracle.
696
+ /// Reverts in case the evaluation fails.
697
+ /// @param bitcoinHeaders Bitcoin headers chain being part of the SPV
698
+ /// proof. Used to extract the observed proof difficulty
699
+ function evaluateProofDifficulty(bytes memory bitcoinHeaders)
700
+ internal
701
+ view
702
+ {
703
+ uint256 requestedDiff = 0;
704
+ uint256 currentDiff = relay.getCurrentEpochDifficulty();
705
+ uint256 previousDiff = relay.getPrevEpochDifficulty();
706
+ uint256 firstHeaderDiff =
707
+ bitcoinHeaders.extractTarget().calculateDifficulty();
708
+
709
+ if (firstHeaderDiff == currentDiff) {
710
+ requestedDiff = currentDiff;
711
+ } else if (firstHeaderDiff == previousDiff) {
712
+ requestedDiff = previousDiff;
713
+ } else {
714
+ revert("Not at current or previous difficulty");
715
+ }
716
+
717
+ uint256 observedDiff = bitcoinHeaders.validateHeaderChain();
718
+
719
+ require(
720
+ observedDiff != ValidateSPV.getErrBadLength(),
721
+ "Invalid length of the headers chain"
722
+ );
723
+ require(
724
+ observedDiff != ValidateSPV.getErrInvalidChain(),
725
+ "Invalid headers chain"
726
+ );
727
+ require(
728
+ observedDiff != ValidateSPV.getErrLowWork(),
729
+ "Insufficient work in a header"
730
+ );
731
+
732
+ require(
733
+ observedDiff >= requestedDiff * txProofDifficultyFactor,
734
+ "Insufficient accumulated difficulty in header chain"
735
+ );
736
+ }
737
+
738
+ /// @notice Processes the Bitcoin sweep transaction output vector by
739
+ /// extracting the single output and using it to gain additional
740
+ /// information required for further processing (e.g. value and
741
+ /// wallet public key hash).
742
+ /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.
743
+ /// This function assumes vector's structure is valid so it must be
744
+ /// validated using e.g. `BTCUtils.validateVout` function before
745
+ /// it is passed here
746
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
747
+ /// @return value 8-byte sweep transaction output value.
748
+ function processSweepTxOutput(bytes memory sweepTxOutputVector)
749
+ internal
750
+ pure
751
+ returns (bytes20 walletPubKeyHash, uint64 value)
752
+ {
753
+ // To determine the total number of sweep transaction outputs, we need to
754
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
755
+ // That compactSize uint encodes the number of vector elements using the
756
+ // format presented in:
757
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
758
+ // We don't need asserting the compactSize uint is parseable since it
759
+ // was already checked during `validateVout` validation.
760
+ // See `BitcoinTx.outputVector` docs for more details.
761
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
762
+ require(
763
+ outputsCount == 1,
764
+ "Sweep transaction must have a single output"
765
+ );
766
+
767
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
768
+ value = output.extractValue();
769
+ bytes memory walletPubKeyHashBytes = output.extractHash();
770
+ // The sweep transaction output should always be P2PKH or P2WPKH.
771
+ // In both cases, the wallet public key hash should be 20 bytes length.
772
+ require(
773
+ walletPubKeyHashBytes.length == 20,
774
+ "Wallet public key hash should have 20 bytes"
775
+ );
776
+ /* solhint-disable-next-line no-inline-assembly */
777
+ assembly {
778
+ walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))
779
+ }
780
+
781
+ return (walletPubKeyHash, value);
782
+ }
783
+
784
+ /// @notice Processes the Bitcoin sweep transaction input vector. It
785
+ /// extracts each input and tries to obtain associated deposit or
786
+ /// main UTXO data, depending on the input type. Reverts
787
+ /// if one of the inputs cannot be recognized as a pointer to a
788
+ /// revealed deposit or expected main UTXO.
789
+ /// This function also marks each processed deposit as swept.
790
+ /// @param sweepTxInputVector Bitcoin sweep transaction input vector.
791
+ /// This function assumes vector's structure is valid so it must be
792
+ /// validated using e.g. `BTCUtils.validateVin` function before
793
+ /// it is passed here
794
+ /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO
795
+ /// exists for the given the wallet, this parameter's fields should
796
+ /// be zeroed to bypass the main UTXO validation
797
+ /// @return inputsTotalValue Sum of all inputs values i.e. all deposits and
798
+ /// main UTXO value, if present.
799
+ /// @return depositors Addresses of depositors who performed processed
800
+ /// deposits. Ordered in the same order as deposits inputs in the
801
+ /// input vector. Size of this array is either equal to the
802
+ /// number of inputs (main UTXO doesn't exist) or less by one
803
+ /// (main UTXO exists and is pointed by one of the inputs).
804
+ /// @return depositedAmounts Amounts of deposits corresponding to processed
805
+ /// deposits. Ordered in the same order as deposits inputs in the
806
+ /// input vector. Size of this array is either equal to the
807
+ /// number of inputs (main UTXO doesn't exist) or less by one
808
+ /// (main UTXO exists and is pointed by one of the inputs).
809
+ function processSweepTxInputs(
810
+ bytes memory sweepTxInputVector,
811
+ BitcoinTx.UTXO memory mainUtxo
812
+ )
813
+ internal
814
+ returns (
815
+ uint256 inputsTotalValue,
816
+ address[] memory depositors,
817
+ uint256[] memory depositedAmounts
818
+ )
819
+ {
820
+ // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO
821
+ // for the given wallet doesn't exist and it is not expected to be
822
+ // included in the sweep transaction input vector.
823
+ bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);
824
+ bool mainUtxoFound = false;
825
+
826
+ // Determining the total number of sweep transaction inputs in the same
827
+ // way as for number of outputs. See `BitcoinTx.inputVector` docs for
828
+ // more details.
829
+ (uint256 inputsCompactSizeUintLength, uint256 inputsCount) =
830
+ sweepTxInputVector.parseVarInt();
831
+
832
+ // To determine the first input starting index, we must jump over
833
+ // the compactSize uint which prepends the input vector. One byte
834
+ // must be added because `BtcUtils.parseVarInt` does not include
835
+ // compactSize uint tag in the returned length.
836
+ //
837
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
838
+ // returns `0`, so we jump over one byte of compactSize uint.
839
+ //
840
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
841
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
842
+ // tag byte included) so we need to jump over 1+2 bytes of
843
+ // compactSize uint.
844
+ //
845
+ // Please refer `BTCUtils` library and compactSize uint
846
+ // docs in `BitcoinTx` library for more details.
847
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
848
+
849
+ // Determine the swept deposits count. If main UTXO is NOT expected,
850
+ // all inputs should be deposits. If main UTXO is expected, one input
851
+ // should point to that main UTXO.
852
+ depositors = new address[](
853
+ !mainUtxoExpected ? inputsCount : inputsCount - 1
854
+ );
855
+ depositedAmounts = new uint256[](depositors.length);
856
+
857
+ // Initialize helper variables.
858
+ uint256 processedDepositsCount = 0;
859
+
860
+ // Inputs processing loop.
861
+ for (uint256 i = 0; i < inputsCount; i++) {
862
+ (
863
+ bytes32 outpointTxHash,
864
+ uint32 outpointIndex,
865
+ uint256 inputLength
866
+ ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
867
+
868
+ DepositRequest storage deposit =
869
+ deposits[
870
+ uint256(
871
+ keccak256(
872
+ abi.encodePacked(outpointTxHash, outpointIndex)
873
+ )
874
+ )
875
+ ];
876
+
877
+ if (deposit.revealedAt != 0) {
878
+ // If we entered here, that means the input was identified as
879
+ // a revealed deposit.
880
+ require(deposit.sweptAt == 0, "Deposit already swept");
881
+
882
+ if (processedDepositsCount == depositors.length) {
883
+ // If this condition is true, that means a deposit input
884
+ // took place of an expected main UTXO input.
885
+ // In other words, there is no expected main UTXO
886
+ // input and all inputs come from valid, revealed deposits.
887
+ revert(
888
+ "Expected main UTXO not present in sweep transaction inputs"
889
+ );
890
+ }
891
+
892
+ /* solhint-disable-next-line not-rely-on-time */
893
+ deposit.sweptAt = uint32(block.timestamp);
894
+
895
+ depositors[processedDepositsCount] = deposit.depositor;
896
+ depositedAmounts[processedDepositsCount] = deposit.amount;
897
+ inputsTotalValue += depositedAmounts[processedDepositsCount];
898
+
899
+ processedDepositsCount++;
900
+ } else if (
901
+ mainUtxoExpected != mainUtxoFound &&
902
+ mainUtxo.txHash == outpointTxHash
903
+ ) {
904
+ // If we entered here, that means the input was identified as
905
+ // the expected main UTXO.
906
+ inputsTotalValue += mainUtxo.txOutputValue;
907
+ mainUtxoFound = true;
908
+ } else {
909
+ revert("Unknown input type");
910
+ }
911
+
912
+ // Make the `inputStartingIndex` pointing to the next input by
913
+ // increasing it by current input's length.
914
+ inputStartingIndex += inputLength;
915
+ }
916
+
917
+ // Construction of the input processing loop guarantees that:
918
+ // `processedDepositsCount == depositors.length == depositedAmounts.length`
919
+ // is always true at this point. We just use the first variable
920
+ // to assert the total count of swept deposit is bigger than zero.
921
+ require(
922
+ processedDepositsCount > 0,
923
+ "Sweep transaction must process at least one deposit"
924
+ );
925
+
926
+ // Assert the main UTXO was used as one of current sweep's inputs if
927
+ // it was actually expected.
928
+ require(
929
+ mainUtxoExpected == mainUtxoFound,
930
+ "Expected main UTXO not present in sweep transaction inputs"
931
+ );
932
+
933
+ return (inputsTotalValue, depositors, depositedAmounts);
934
+ }
935
+
936
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
937
+ /// @param inputVector Bitcoin transaction input vector
938
+ /// @param inputStartingIndex Index the given input starts at
939
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
940
+ /// pointed in the given input's outpoint.
941
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
942
+ /// which is pointed in the given input's outpoint.
943
+ /// @return inputLength Byte length of the given input.
944
+ /// @dev This function assumes vector's structure is valid so it must be
945
+ /// validated using e.g. `BTCUtils.validateVin` function before it
946
+ /// is passed here.
947
+ function parseTxInputAt(
948
+ bytes memory inputVector,
949
+ uint256 inputStartingIndex
950
+ )
951
+ internal
952
+ pure
953
+ returns (
954
+ bytes32 outpointTxHash,
955
+ uint32 outpointIndex,
956
+ uint256 inputLength
957
+ )
958
+ {
959
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
960
+
961
+ outpointIndex = BTCUtils.reverseUint32(
962
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
963
+ );
964
+
965
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
966
+
967
+ return (outpointTxHash, outpointIndex, inputLength);
968
+ }
969
+
970
+ /// @notice Requests redemption of the given amount from the specified
971
+ /// wallet to the redeemer Bitcoin output script.
972
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
973
+ // using Bitcoin HASH160 over the compressed ECDSA public key)
974
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
975
+ /// the Ethereum chain
976
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
977
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
978
+ /// redeemed BTC
979
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
980
+ /// that is taken from redeemer's balance in the Bank upon request.
981
+ /// Once the request is handled, the actual amount of BTC locked
982
+ /// on the redeemer output script will be always lower than this value
983
+ /// since the treasury and Bitcoin transaction fees must be incurred.
984
+ /// The minimal amount satisfying the request can be computed as:
985
+ /// `amount - redemptionTreasuryFee - redemptionTxMaxFee`.
986
+ /// Fees values are taken at the moment of request creation.
987
+ /// @dev Requirements:
988
+ /// - Wallet behind `walletPubKeyHash` must be active
989
+ /// - `mainUtxo` components must point to the recent main UTXO
990
+ /// of the given wallet, as currently known on the Ethereum chain.
991
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
992
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
993
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
994
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
995
+ /// used for only one pending request at the same time
996
+ /// - Wallet must have enough Bitcoin balance to proceed the request
997
+ /// - Redeemer must make an allowance in the Bank that the Bridge
998
+ /// contract can spend the given `amount`.
999
+ function requestRedemption(
1000
+ bytes20 walletPubKeyHash,
1001
+ BitcoinTx.UTXO calldata mainUtxo,
1002
+ bytes calldata redeemerOutputScript,
1003
+ uint64 amount
319
1004
  ) external {
320
- // TODO We need to read `fundingTxHash`, `fundingOutputIndex` from
321
- // `sweepTx.inputVector`. We then hash them to obtain deposit
322
- // identifier and read DepositInfo. From DepositInfo we know what
323
- // amount was inferred during deposit reveal transaction and we
324
- // use that amount to update their Bank balance, minus fee.
1005
+ require(
1006
+ wallets[walletPubKeyHash].state == WalletState.Active,
1007
+ "Wallet must be in Active state"
1008
+ );
1009
+
1010
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1011
+ require(
1012
+ mainUtxoHash != bytes32(0),
1013
+ "No main UTXO for the given wallet"
1014
+ );
1015
+ require(
1016
+ keccak256(
1017
+ abi.encodePacked(
1018
+ mainUtxo.txHash,
1019
+ mainUtxo.txOutputIndex,
1020
+ mainUtxo.txOutputValue
1021
+ )
1022
+ ) == mainUtxoHash,
1023
+ "Invalid main UTXO data"
1024
+ );
1025
+
1026
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1027
+ // if it is the oldest one who can handle the request. This will
1028
+ // be suggested by the dApp but may not be respected by users who
1029
+ // interact directly with the contract. Do we need to enforce it
1030
+ // here? One option is not to enforce it, to save on gas, but if
1031
+ // we see this rule is not respected, upgrade Bridge contract to
1032
+ // require it.
1033
+
1034
+ // Validate if redeemer output script is a correct standard type
1035
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1036
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1037
+ // a function extracts the payload properly only from standard outputs
1038
+ // so if it succeeds, we have a guarantee the redeemer output script
1039
+ // is proper. Worth to note `extractHash` ignores the value at all
1040
+ // so this is why we can use 0 safely. This way of validation is the
1041
+ // same as in tBTC v1.
1042
+ bytes memory redeemerOutputScriptPayload =
1043
+ abi.encodePacked(bytes8(0), redeemerOutputScript).extractHash();
1044
+ require(
1045
+ redeemerOutputScriptPayload.length > 0,
1046
+ "Redeemer output script must be a standard type"
1047
+ );
1048
+ // Check if the redeemer output script payload does not point to the
1049
+ // wallet public key hash.
1050
+ require(
1051
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
1052
+ keccak256(redeemerOutputScriptPayload),
1053
+ "Redeemer output script must not point to the wallet PKH"
1054
+ );
1055
+
1056
+ require(
1057
+ amount >= redemptionDustThreshold,
1058
+ "Redemption amount too small"
1059
+ );
1060
+
1061
+ // The redemption key is built on top of the wallet public key hash
1062
+ // and redeemer output script pair. That means there can be only one
1063
+ // request asking for redemption from the given wallet to the given
1064
+ // BTC script at the same time.
1065
+ uint256 redemptionKey =
1066
+ uint256(
1067
+ keccak256(
1068
+ abi.encodePacked(walletPubKeyHash, redeemerOutputScript)
1069
+ )
1070
+ );
1071
+
1072
+ // Check if given redemption key is not used by a pending redemption.
1073
+ // There is no need to check for existence in `timedOutRedemptions`
1074
+ // since the wallet's state is changed to other than Active after
1075
+ // first time out is reported so making new requests is not possible.
1076
+ // slither-disable-next-line incorrect-equality
1077
+ require(
1078
+ pendingRedemptions[redemptionKey].requestedAt == 0,
1079
+ "There is a pending redemption request from this wallet to the same address"
1080
+ );
1081
+
1082
+ uint64 treasuryFee = redemptionTreasuryFee;
1083
+ uint64 txMaxFee = redemptionTxMaxFee;
1084
+
1085
+ // The main wallet UTXO's value doesn't include all pending redemptions.
1086
+ // To determine if the requested redemption can be performed by the
1087
+ // wallet we need to subtract the total value of all pending redemptions
1088
+ // from that wallet's main UTXO value. Given that the treasury fee is
1089
+ // not redeemed from the wallet, we are subtracting it.
1090
+ wallets[walletPubKeyHash].pendingRedemptionsValue +=
1091
+ amount -
1092
+ treasuryFee;
1093
+ require(
1094
+ mainUtxo.txOutputValue >=
1095
+ wallets[walletPubKeyHash].pendingRedemptionsValue,
1096
+ "Insufficient wallet funds"
1097
+ );
1098
+
1099
+ pendingRedemptions[redemptionKey] = RedemptionRequest(
1100
+ msg.sender,
1101
+ amount,
1102
+ treasuryFee,
1103
+ txMaxFee,
1104
+ /* solhint-disable-next-line not-rely-on-time */
1105
+ uint32(block.timestamp)
1106
+ );
1107
+
1108
+ emit RedemptionRequested(
1109
+ walletPubKeyHash,
1110
+ redeemerOutputScript,
1111
+ msg.sender,
1112
+ amount,
1113
+ treasuryFee,
1114
+ txMaxFee
1115
+ );
1116
+
1117
+ bank.transferBalanceFrom(msg.sender, address(this), amount);
1118
+ }
1119
+
1120
+ /// @notice Used by the wallet to prove the BTC redemption transaction
1121
+ /// and to make the necessary bookkeeping. Redemption is only
1122
+ /// accepted if it satisfies SPV proof.
1123
+ ///
1124
+ /// The function is performing Bank balance updates by burning
1125
+ /// the total redeemed Bitcoin amount from Bridge balance and
1126
+ /// transferring the treasury fee sum to the treasury address.
1127
+ ///
1128
+ /// It is possible to prove the given redemption only one time.
1129
+ /// @param redemptionTx Bitcoin redemption transaction data
1130
+ /// @param redemptionProof Bitcoin redemption proof data
1131
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1132
+ /// the Ethereum chain
1133
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1134
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
1135
+ /// performed the redemption transaction
1136
+ /// @dev Requirements:
1137
+ /// - `redemptionTx` components must match the expected structure. See
1138
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
1139
+ /// correspond to appropriate Bitcoin transaction fields to produce
1140
+ /// a provable transaction hash.
1141
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
1142
+ /// exactly 1 input that refers to the wallet's main UTXO. That
1143
+ /// transaction should have 1..n outputs handling existing pending
1144
+ /// redemption requests or pointing to reported timed out requests.
1145
+ /// There can be also 1 optional output representing the
1146
+ /// change and pointing back to the 20-byte wallet public key hash.
1147
+ /// The change should be always present if the redeemed value sum
1148
+ /// is lower than the total wallet's BTC balance.
1149
+ /// - `redemptionProof` components must match the expected structure.
1150
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
1151
+ /// field must contain a valid number of block headers, not less
1152
+ /// than the `txProofDifficultyFactor` contract constant.
1153
+ /// - `mainUtxo` components must point to the recent main UTXO
1154
+ /// of the given wallet, as currently known on the Ethereum chain.
1155
+ /// Additionally, the recent main UTXO on Ethereum must be set.
1156
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
1157
+ /// as transaction single input.
1158
+ /// Other remarks:
1159
+ /// - Putting the change output as the first transaction output can
1160
+ /// save some gas because the output processing loop begins each
1161
+ /// iteration by checking whether the given output is the change
1162
+ /// thus uses some gas for making the comparison. Once the change
1163
+ /// is identified, that check is omitted in further iterations.
1164
+ function submitRedemptionProof(
1165
+ BitcoinTx.Info calldata redemptionTx,
1166
+ BitcoinTx.Proof calldata redemptionProof,
1167
+ BitcoinTx.UTXO calldata mainUtxo,
1168
+ bytes20 walletPubKeyHash
1169
+ ) external {
1170
+ // TODO: Just as for `submitSweepProof`, fail early if the function
1171
+ // call gets frontrunned. See discussion:
1172
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1173
+
1174
+ // The actual transaction proof is performed here. After that point, we
1175
+ // can assume the transaction happened on Bitcoin chain and has
1176
+ // a sufficient number of confirmations as determined by
1177
+ // `txProofDifficultyFactor` constant.
1178
+ bytes32 redemptionTxHash =
1179
+ validateBitcoinTxProof(redemptionTx, redemptionProof);
1180
+
1181
+ // Perform validation of the redemption transaction input. Specifically,
1182
+ // check if it refers to the expected wallet's main UTXO.
1183
+ validateRedemptionTxInput(
1184
+ redemptionTx.inputVector,
1185
+ mainUtxo,
1186
+ walletPubKeyHash
1187
+ );
1188
+
1189
+ WalletState walletState = wallets[walletPubKeyHash].state;
1190
+ require(
1191
+ walletState == WalletState.Active ||
1192
+ walletState == WalletState.MovingFunds,
1193
+ "Wallet must be in Active or MovingFuds state"
1194
+ );
1195
+
1196
+ // Process redemption transaction outputs to extract some info required
1197
+ // for further processing.
1198
+ RedemptionTxOutputsInfo memory outputsInfo =
1199
+ processRedemptionTxOutputs(
1200
+ redemptionTx.outputVector,
1201
+ walletPubKeyHash
1202
+ );
1203
+
1204
+ if (outputsInfo.changeValue > 0) {
1205
+ // If the change value is grater than zero, it means the change
1206
+ // output exists and can be used as new wallet's main UTXO.
1207
+ mainUtxos[walletPubKeyHash] = keccak256(
1208
+ abi.encodePacked(
1209
+ redemptionTxHash,
1210
+ outputsInfo.changeIndex,
1211
+ outputsInfo.changeValue
1212
+ )
1213
+ );
1214
+ } else {
1215
+ // If the change value is zero, it means the change output doesn't
1216
+ // exists and no funds left on the wallet. Delete the main UTXO
1217
+ // for that wallet to represent that state in a proper way.
1218
+ delete mainUtxos[walletPubKeyHash];
1219
+ }
1220
+
1221
+ wallets[walletPubKeyHash].pendingRedemptionsValue -= outputsInfo
1222
+ .totalBurnableValue;
1223
+
1224
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1225
+
1226
+ bank.decreaseBalance(outputsInfo.totalBurnableValue);
1227
+ bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1228
+ }
1229
+
1230
+ /// @notice Validates whether the redemption Bitcoin transaction input
1231
+ /// vector contains a single input referring to the wallet's main
1232
+ /// UTXO. Reverts in case the validation fails.
1233
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1234
+ /// vector. This function assumes vector's structure is valid so it
1235
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1236
+ /// before it is passed here
1237
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1238
+ /// the Ethereum chain.
1239
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1240
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1241
+ /// performed the redemption transaction.
1242
+ function validateRedemptionTxInput(
1243
+ bytes memory redemptionTxInputVector,
1244
+ BitcoinTx.UTXO calldata mainUtxo,
1245
+ bytes20 walletPubKeyHash
1246
+ ) internal view {
1247
+ // Assert that main UTXO for passed wallet exists in storage.
1248
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1249
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1250
+
1251
+ // Assert that passed main UTXO parameter is the same as in storage and
1252
+ // can be used for further processing.
1253
+ require(
1254
+ keccak256(
1255
+ abi.encodePacked(
1256
+ mainUtxo.txHash,
1257
+ mainUtxo.txOutputIndex,
1258
+ mainUtxo.txOutputValue
1259
+ )
1260
+ ) == mainUtxoHash,
1261
+ "Invalid main UTXO data"
1262
+ );
1263
+
1264
+ // Assert that the single redemption transaction input actually
1265
+ // refers to the wallet's main UTXO.
1266
+ (bytes32 redemptionTxOutpointTxHash, uint32 redemptionTxOutpointIndex) =
1267
+ processRedemptionTxInput(redemptionTxInputVector);
1268
+ require(
1269
+ mainUtxo.txHash == redemptionTxOutpointTxHash &&
1270
+ mainUtxo.txOutputIndex == redemptionTxOutpointIndex,
1271
+ "Redemption transaction input must point to the wallet's main UTXO"
1272
+ );
1273
+ }
1274
+
1275
+ /// @notice Processes the Bitcoin redemption transaction input vector. It
1276
+ /// extracts the single input then the transaction hash and output
1277
+ /// index from its outpoint.
1278
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1279
+ /// vector. This function assumes vector's structure is valid so it
1280
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1281
+ /// before it is passed here
1282
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1283
+ /// pointed in the input's outpoint.
1284
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1285
+ /// which is pointed in the input's outpoint.
1286
+ function processRedemptionTxInput(bytes memory redemptionTxInputVector)
1287
+ internal
1288
+ pure
1289
+ returns (bytes32 outpointTxHash, uint32 outpointIndex)
1290
+ {
1291
+ // To determine the total number of redemption transaction inputs,
1292
+ // we need to parse the compactSize uint (VarInt) the input vector is
1293
+ // prepended by. That compactSize uint encodes the number of vector
1294
+ // elements using the format presented in:
1295
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1296
+ // We don't need asserting the compactSize uint is parseable since it
1297
+ // was already checked during `validateVin` validation.
1298
+ // See `BitcoinTx.inputVector` docs for more details.
1299
+ (, uint256 inputsCount) = redemptionTxInputVector.parseVarInt();
1300
+ require(
1301
+ inputsCount == 1,
1302
+ "Redemption transaction must have a single input"
1303
+ );
1304
+
1305
+ bytes memory input = redemptionTxInputVector.extractInputAtIndex(0);
1306
+
1307
+ outpointTxHash = input.extractInputTxIdLE();
1308
+
1309
+ outpointIndex = BTCUtils.reverseUint32(
1310
+ uint32(input.extractTxIndexLE())
1311
+ );
1312
+
1313
+ // There is only one input in the transaction. Input has an outpoint
1314
+ // field that is a reference to the transaction being spent (see
1315
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1316
+ // to spend (`outpointTxHash`) and the index of the specific output
1317
+ // from that transaction (`outpointIndex`).
1318
+ return (outpointTxHash, outpointIndex);
1319
+ }
1320
+
1321
+ /// @notice Processes the Bitcoin redemption transaction output vector.
1322
+ /// It extracts each output and tries to identify it as a pending
1323
+ /// redemption request, reported timed out request, or change.
1324
+ /// Reverts if one of the outputs cannot be recognized properly.
1325
+ /// This function also marks each request as processed by removing
1326
+ /// them from `pendingRedemptions` mapping.
1327
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1328
+ /// vector. This function assumes vector's structure is valid so it
1329
+ /// must be validated using e.g. `BTCUtils.validateVout` function
1330
+ /// before it is passed here
1331
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1332
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1333
+ /// performed the redemption transaction.
1334
+ /// @return info Outcomes of the processing.
1335
+ function processRedemptionTxOutputs(
1336
+ bytes memory redemptionTxOutputVector,
1337
+ bytes20 walletPubKeyHash
1338
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
1339
+ // Determining the total number of redemption transaction outputs in
1340
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
1341
+ // docs for more details.
1342
+ (uint256 outputsCompactSizeUintLength, uint256 outputsCount) =
1343
+ redemptionTxOutputVector.parseVarInt();
1344
+
1345
+ // To determine the first output starting index, we must jump over
1346
+ // the compactSize uint which prepends the output vector. One byte
1347
+ // must be added because `BtcUtils.parseVarInt` does not include
1348
+ // compactSize uint tag in the returned length.
325
1349
  //
326
- // TODO We need to validate if the sum in the output minus the
327
- // amount from the previous wallet balance input minus fees is
328
- // equal to the amount by which Bank balances were increased.
1350
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1351
+ // returns `0`, so we jump over one byte of compactSize uint.
329
1352
  //
330
- // TODO We need to validate `sweepTx.outputVector` to see if the balance
331
- // was not transferred away from the wallet before increasing
332
- // balances in the bank.
1353
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1354
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1355
+ // tag byte included) so we need to jump over 1+2 bytes of
1356
+ // compactSize uint.
333
1357
  //
334
- // TODO Delete deposit from unswept mapping or mark it as swept
335
- // depending on the gas costs. Alternatively, do not allow to
336
- // use the same TX input vector twice. Sweep should be provable
337
- // only one time.
1358
+ // Please refer `BTCUtils` library and compactSize uint
1359
+ // docs in `BitcoinTx` library for more details.
1360
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1361
+
1362
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1363
+ // scripts that can be used to lock the change. This is done upfront to
1364
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
1365
+ //
1366
+ // The P2PKH script has format <0x1976a914> <20-byte PKH> <0x88ac>.
1367
+ bytes32 walletP2PKHScriptKeccak =
1368
+ keccak256(
1369
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1370
+ );
1371
+ // The P2WPKH script has format <0x160014> <20-byte PKH>.
1372
+ bytes32 walletP2WPKHScriptKeccak =
1373
+ keccak256(abi.encodePacked(hex"160014", walletPubKeyHash));
1374
+
1375
+ // Helper variable that counts the number of processed redemption
1376
+ // outputs. Redemptions can be either pending or reported as timed out.
1377
+ // TODO: Revisit the approach with redemptions count according to
1378
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1379
+ uint256 processedRedemptionsCount = 0;
1380
+
1381
+ // Outputs processing loop.
1382
+ for (uint256 i = 0; i < outputsCount; i++) {
1383
+ // TODO: Check if we can optimize gas costs by adding
1384
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1385
+ // in order to avoid allocating bytes in memory.
1386
+ uint256 outputLength =
1387
+ redemptionTxOutputVector.determineOutputLengthAt(
1388
+ outputStartingIndex
1389
+ );
1390
+ bytes memory output =
1391
+ redemptionTxOutputVector.slice(
1392
+ outputStartingIndex,
1393
+ outputLength
1394
+ );
1395
+
1396
+ // Extract the value from given output.
1397
+ uint64 outputValue = output.extractValue();
1398
+ // The output consists of an 8-byte value and a variable length
1399
+ // script. To extract that script we slice the output staring from
1400
+ // 9th byte until the end.
1401
+ bytes memory outputScript = output.slice(8, output.length - 8);
1402
+
1403
+ if (
1404
+ info.changeValue == 0 &&
1405
+ (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1406
+ keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1407
+ outputValue > 0
1408
+ ) {
1409
+ // If we entered here, that means the change output with a
1410
+ // proper non-zero value was found.
1411
+ info.changeIndex = uint32(i);
1412
+ info.changeValue = outputValue;
1413
+ } else {
1414
+ // If we entered here, that the means the given output is
1415
+ // supposed to represent a redemption. Build the redemption key
1416
+ // to perform that check.
1417
+ uint256 redemptionKey =
1418
+ uint256(
1419
+ keccak256(
1420
+ abi.encodePacked(walletPubKeyHash, outputScript)
1421
+ )
1422
+ );
1423
+
1424
+ if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1425
+ // If we entered here, that means the output was identified
1426
+ // as a pending redemption request.
1427
+ RedemptionRequest storage request =
1428
+ pendingRedemptions[redemptionKey];
1429
+ // Compute the request's redeemable amount as the requested
1430
+ // amount reduced by the treasury fee. The request's
1431
+ // minimal amount is then the redeemable amount reduced by
1432
+ // the maximum transaction fee.
1433
+ uint64 redeemableAmount =
1434
+ request.requestedAmount - request.treasuryFee;
1435
+ // Output value must fit between the request's redeemable
1436
+ // and minimal amounts to be deemed valid.
1437
+ require(
1438
+ redeemableAmount - request.txMaxFee <= outputValue &&
1439
+ outputValue <= redeemableAmount,
1440
+ "Output value is not within the acceptable range of the pending request"
1441
+ );
1442
+ // Add the redeemable amount to the total burnable value
1443
+ // the Bridge will use to decrease its balance in the Bank.
1444
+ info.totalBurnableValue += redeemableAmount;
1445
+ // Add the request's treasury fee to the total treasury fee
1446
+ // value the Bridge will transfer to the treasury.
1447
+ info.totalTreasuryFee += request.treasuryFee;
1448
+ // Request was properly handled so remove its redemption
1449
+ // key from the mapping to make it reusable for further
1450
+ // requests.
1451
+ delete pendingRedemptions[redemptionKey];
1452
+
1453
+ processedRedemptionsCount++;
1454
+ } else {
1455
+ // If we entered here, the output is not a redemption
1456
+ // request but there is still a chance the given output is
1457
+ // related to a reported timed out redemption request.
1458
+ // If so, check if the output value matches the request
1459
+ // amount to confirm this is an overdue request fulfillment
1460
+ // then bypass this output and process the subsequent
1461
+ // ones. That also means the wallet was already punished
1462
+ // for the inactivity. Otherwise, just revert.
1463
+ RedemptionRequest storage request =
1464
+ timedOutRedemptions[redemptionKey];
1465
+
1466
+ require(
1467
+ request.requestedAt != 0,
1468
+ "Output is a non-requested redemption"
1469
+ );
1470
+
1471
+ uint64 redeemableAmount =
1472
+ request.requestedAmount - request.treasuryFee;
1473
+
1474
+ require(
1475
+ redeemableAmount - request.txMaxFee <= outputValue &&
1476
+ outputValue <= redeemableAmount,
1477
+ "Output value is not within the acceptable range of the timed out request"
1478
+ );
1479
+
1480
+ processedRedemptionsCount++;
1481
+ }
1482
+ }
1483
+
1484
+ // Make the `outputStartingIndex` pointing to the next output by
1485
+ // increasing it by current output's length.
1486
+ outputStartingIndex += outputLength;
1487
+ }
1488
+
1489
+ // Protect against the cases when there is only a single change output
1490
+ // referring back to the wallet PKH and just burning main UTXO value
1491
+ // for transaction fees.
1492
+ require(
1493
+ processedRedemptionsCount > 0,
1494
+ "Redemption transaction must process at least one redemption"
1495
+ );
1496
+
1497
+ return info;
338
1498
  }
339
1499
 
340
- // TODO It is possible a malicious wallet can sweep deposits that can not
341
- // be later proved on Ethereum. For example, a deposit with
342
- // an incorrect amount revealed. We need to provide a function for honest
343
- // depositors, next to sweep, to prove their swept balances on Ethereum
344
- // selectively, based on deposits they have earlier received.
345
- // (UPDATE PR #90: Is it still the case since amounts are inferred?)
1500
+ // TODO: Function `notifyRedemptionTimeout. That function must:
1501
+ // 1. Take a the `walletPubKey` and `redeemerOutputScript` as params.
1502
+ // 2. Build the redemption key using those params.
1503
+ // 3. Use the redemption key and take the request from
1504
+ // `pendingRedemptions` mapping.
1505
+ // 4. If request doesn't exist in mapping - revert.
1506
+ // 5. If request exits, and is timed out - remove the redemption key
1507
+ // from `pendingRedemptions` and put it to `timedOutRedemptions`
1508
+ // by copying the entire `RedemptionRequest` struct there. No need
1509
+ // to check if `timedOutRedemptions` mapping already contains
1510
+ // that key because `requestRedemption` blocks requests targeting
1511
+ // non-active wallets. Because `notifyRedemptionTimeout` changes
1512
+ // wallet state after first call (point 9), there is no possibility
1513
+ // that the given redemption key could be reported as timed out
1514
+ // multiple times. At the same time, if the given redemption key
1515
+ // was already marked as fraudulent due to an amount-related fraud,
1516
+ // it will not be possible to report a time out on it since it
1517
+ // won't be present in `pendingRedemptions` mapping.
1518
+ // 6. Return the `requestedAmount` to the `redeemer`.
1519
+ // 7. Reduce the `pendingRedemptionsValue` (`wallets` mapping) for
1520
+ // given wallet by request's redeemable amount computed as
1521
+ // `requestedAmount - treasuryFee`.
1522
+ // 8. Punish the wallet, probably by slashing its operators.
1523
+ // 9. Change wallet's state in `wallets` mapping to `MovingFunds` in
1524
+ // order to prevent against new redemption requests hitting
1525
+ // that wallet.
1526
+ // 10. Expect the wallet to transfer its funds to another healthy
1527
+ // wallet (just as in case of failed heartbeat). The wallet is
1528
+ // expected to finish the already queued redemption requests
1529
+ // before moving funds but we are not going to enforce it on-chain.
1530
+
1531
+ // TODO: Function `submitRedemptionFraudProof`
1532
+ //
1533
+ // Deposit and redemption fraud proofs are challenging to implement
1534
+ // and it may happen we will have to rely on the coverage pool
1535
+ // (https://github.com/keep-network/coverage-pools) and DAO to
1536
+ // reimburse unlucky depositors and bring back the balance to the
1537
+ // system in case of a wallet fraud by liquidating a part of the
1538
+ // coverage pool manually.
1539
+ //
1540
+ // The probability of 51-of-100 wallet being fraudulent is negligible:
1541
+ // https://github.com/keep-network/tbtc-v2/blob/main/docs/rfc/rfc-2.adoc#111-group-size-and-threshold
1542
+ // and the coverage pool would be there to bring the balance back in
1543
+ // case we are unlucky and malicious wallet emerges.
1544
+ //
1545
+ // We do not want to slash for a misbehavior that is not provable
1546
+ // on-chain and it is possible to construct such a Bitcoin transaction
1547
+ // that is not provable on Ethereum, see
1548
+ // https://consensys.net/diligence/blog/2020/05/tbtc-navigating-the-cross-chain-conundrum
1549
+ //
1550
+ // The algorithm described below assumes we will be able to prove the
1551
+ // TX on Ethereum which may not always be the case. Consider the steps
1552
+ // below as an idea, and not necessarily how this function will be
1553
+ // implemented because it may happen this function will never be
1554
+ // implemented, given the Bitcoin transaction size problems.
1555
+ //
1556
+ // The algorithm:
1557
+ // 1. Take a `BitcoinTx.Info` and `BitcoinTx.Proof` of the
1558
+ // fraudulent transaction. It should also accept `walletPubKeyHash`
1559
+ // and index of fraudulent output. Probably index of fraudulent
1560
+ // input will be also required if the transaction is supposed
1561
+ // to have a bad input vector.
1562
+ // 2. Perform SPV proof to make sure it occurred on Bitcoin chain.
1563
+ // If not - revert.
1564
+ // 3. Check if wallet state is Active or MovingFunds. If not, revert.
1565
+ // 4. Validate the number of inputs. If there is one input and it
1566
+ // points to the wallet's main UTXO - move to point 5. If there
1567
+ // are multiple inputs and there is wallet's main UTXO in the set,
1568
+ // check if this is a sweep transaction. If it's not a sweep,
1569
+ // consider it as fraudulent and move to point 6.
1570
+ // In all other cases revert the call.
1571
+ // 5. Extract the output and analyze its type. The output is not
1572
+ // a fraud and the call should be reverted ONLY IF one of the
1573
+ // following conditions is true:
1574
+ // - Output is a requested redemption held by `pendingRedemptions`
1575
+ // and output value fulfills the request range. There is an
1576
+ // open question if a misfunded request should be removed
1577
+ // from `pendingRedemptions` (probably yes) and whether the
1578
+ // redeemer should be reimbursed in case of an underfund.
1579
+ // - Output is a timed out redemption held by `timedOutRedemptions`
1580
+ // and output value fulfills the request range.
1581
+ // - Output is a proper change i.e. a single output targeting
1582
+ // the wallet PKH back and having a non-zero value.
1583
+ // - Wallet is in MovingFunds state, the output points to the
1584
+ // expected target wallet, have non-zero value, and is a single
1585
+ // output in the vector.
1586
+ // In all other cases consider the transaction as fraud and
1587
+ // proceed to point 6.
1588
+ // 6. Punish the wallet, probably by severely slashing its operators.
1589
+ // 7. Change wallet's state in `wallets` mapping to `Terminated` in
1590
+ // order to prevent against new redemption requests hitting
1591
+ // that wallet. This also prevents against reporting a fraud
1592
+ // multiple times for one transaction (see point 3) and blocks
1593
+ // submission of sweep and redemption proofs. `Terminated` wallet
1594
+ // is blocked in the Bridge forever. If the fraud was a mistake
1595
+ // done by the wallet and the wallet is still honest deep in its
1596
+ // heart, the wallet can coordinate off-chain to recover the BTC
1597
+ // and donate it to another wallet. If they recover all of the
1598
+ // remaining BTC, DAO might decide to reward them with tokens so
1599
+ // that they can have at least some portion of their slashed
1600
+ // tokens back.
346
1601
  }