@keep-network/tbtc-v2 0.1.1-dev.55 → 0.1.1-dev.58

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 (72) hide show
  1. package/artifacts/Bank.json +3 -3
  2. package/artifacts/Bridge.json +716 -197
  3. package/artifacts/Deposit.json +9 -9
  4. package/artifacts/DepositSweep.json +76 -0
  5. package/artifacts/EcdsaDkgValidator.json +1 -1
  6. package/artifacts/EcdsaInactivity.json +1 -1
  7. package/artifacts/Fraud.json +9 -9
  8. package/artifacts/KeepRegistry.json +1 -1
  9. package/artifacts/KeepStake.json +2 -2
  10. package/artifacts/KeepToken.json +2 -2
  11. package/artifacts/KeepTokenStaking.json +1 -1
  12. package/artifacts/MovingFunds.json +77 -11
  13. package/artifacts/NuCypherStakingEscrow.json +1 -1
  14. package/artifacts/NuCypherToken.json +2 -2
  15. package/artifacts/RandomBeaconStub.json +1 -1
  16. package/artifacts/Redemption.json +9 -9
  17. package/artifacts/ReimbursementPool.json +2 -2
  18. package/artifacts/Relay.json +9 -9
  19. package/artifacts/SortitionPool.json +2 -2
  20. package/artifacts/T.json +2 -2
  21. package/artifacts/TBTC.json +3 -3
  22. package/artifacts/TBTCToken.json +3 -3
  23. package/artifacts/TokenStaking.json +1 -1
  24. package/artifacts/TokenholderGovernor.json +9 -9
  25. package/artifacts/TokenholderTimelock.json +8 -8
  26. package/artifacts/VendingMachine.json +10 -10
  27. package/artifacts/VendingMachineKeep.json +1 -1
  28. package/artifacts/VendingMachineNuCypher.json +1 -1
  29. package/artifacts/WalletRegistry.json +2 -2
  30. package/artifacts/WalletRegistryGovernance.json +2 -2
  31. package/artifacts/Wallets.json +9 -9
  32. package/artifacts/solcInputs/{6d69fc514efd874ebb1cb86b04981772.json → 452e42f1afe94d8639a5bf98bed9e151.json} +10 -10
  33. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  34. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  35. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  36. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  37. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  38. package/build/contracts/bridge/Bridge.sol/Bridge.json +375 -103
  39. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  40. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +26 -2
  41. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  42. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  43. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +4 -0
  44. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +30 -0
  45. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  46. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
  47. package/build/contracts/bridge/Fraud.sol/Fraud.json +2 -2
  48. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
  49. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
  50. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +46 -2
  51. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
  52. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +2 -2
  53. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
  54. package/build/contracts/bridge/Redemption.sol/Redemption.json +2 -2
  55. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  56. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  57. package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
  58. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  59. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  60. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  61. package/contracts/bridge/BitcoinTx.sol +69 -0
  62. package/contracts/bridge/Bridge.sol +175 -8
  63. package/contracts/bridge/BridgeState.sol +85 -3
  64. package/contracts/bridge/{Sweep.sol → DepositSweep.sol} +30 -18
  65. package/contracts/bridge/MovingFunds.sol +586 -76
  66. package/contracts/bridge/Wallets.sol +2 -0
  67. package/deploy/05_deploy_bridge.ts +5 -2
  68. package/export.json +479 -56
  69. package/package.json +1 -1
  70. package/artifacts/Sweep.json +0 -76
  71. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +0 -4
  72. package/build/contracts/bridge/Sweep.sol/Sweep.json +0 -30
@@ -31,6 +31,9 @@ import "./Wallets.sol";
31
31
  /// funds to other wallets in the Bridge. The wallet needs to commit to
32
32
  /// which other Live wallets it is moving the funds to and then, provide an
33
33
  /// SPV proof of moving funds to the previously committed wallets.
34
+ /// Once the proof is submitted, all target wallets are supposed to
35
+ /// sweep the received UTXOs with their own main UTXOs in order to
36
+ /// update their BTC balances.
34
37
  library MovingFunds {
35
38
  using BridgeState for BridgeState.Storage;
36
39
  using Wallets for BridgeState.Storage;
@@ -39,6 +42,51 @@ library MovingFunds {
39
42
  using BTCUtils for bytes;
40
43
  using BytesLib for bytes;
41
44
 
45
+ /// @notice Represents temporary information needed during the processing
46
+ /// of the moving funds Bitcoin transaction outputs. This structure
47
+ /// is an internal one and should not be exported outside of the
48
+ /// moving funds transaction processing code.
49
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
50
+ struct MovingFundsTxOutputsProcessingInfo {
51
+ // 32-byte hash of the moving funds Bitcoin transaction.
52
+ bytes32 movingFundsTxHash;
53
+ // Output vector of the moving funds Bitcoin transaction. It is
54
+ // assumed the vector's structure is valid so it must be validated
55
+ // using e.g. `BTCUtils.validateVout` function before being used
56
+ // during the processing. The validation is usually done as part
57
+ // of the `BitcoinTx.validateProof` call that checks the SPV proof.
58
+ bytes movingFundsTxOutputVector;
59
+ }
60
+
61
+ /// @notice Represents moved funds sweep request state.
62
+ enum MovedFundsSweepRequestState {
63
+ /// @dev The request is unknown to the Bridge.
64
+ Unknown,
65
+ /// @dev Request is pending and can become either processed or timed out.
66
+ Pending,
67
+ /// @dev Request was processed by the target wallet.
68
+ Processed,
69
+ /// @dev Request was not processed in the given time window and
70
+ /// the timeout was reported.
71
+ TimedOut
72
+ }
73
+
74
+ /// @notice Represents a moved funds sweep request. The request is
75
+ /// registered in `submitMovingFundsProof` where we know funds
76
+ /// have been moved to the target wallet and the only step left is
77
+ /// to have the target wallet sweep them.
78
+ struct MovedFundsSweepRequest {
79
+ // 20-byte public key hash of the wallet supposed to sweep the UTXO
80
+ // representing the received funds with their own main UTXO
81
+ bytes20 walletPubKeyHash;
82
+ // Value of the received funds.
83
+ uint64 value;
84
+ // UNIX timestamp the request was created at.
85
+ uint32 createdAt;
86
+ // The current state of the request.
87
+ MovedFundsSweepRequestState state;
88
+ }
89
+
42
90
  event MovingFundsCommitmentSubmitted(
43
91
  bytes20 walletPubKeyHash,
44
92
  bytes20[] targetWallets,
@@ -54,6 +102,14 @@ library MovingFunds {
54
102
 
55
103
  event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);
56
104
 
105
+ event MovedFundsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
106
+
107
+ event MovedFundsSweepTimedOut(
108
+ bytes20 walletPubKeyHash,
109
+ bytes32 movingFundsTxHash,
110
+ uint32 movingFundsTxOutputIndex
111
+ );
112
+
57
113
  /// @notice Submits the moving funds target wallets commitment.
58
114
  /// Once all requirements are met, that function registers the
59
115
  /// target wallets commitment and opens the way for moving funds
@@ -70,6 +126,7 @@ library MovingFunds {
70
126
  /// @dev Requirements:
71
127
  /// - The source wallet must be in the MovingFunds state
72
128
  /// - The source wallet must not have pending redemption requests
129
+ /// - The source wallet must not have pending moved funds sweep requests
73
130
  /// - The source wallet must not have submitted its commitment already
74
131
  /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
75
132
  /// be exactly the same as the hash stored under `membersIdsHash`
@@ -115,6 +172,11 @@ library MovingFunds {
115
172
  "Source wallet must handle all pending redemptions first"
116
173
  );
117
174
 
175
+ require(
176
+ wallet.pendingMovedFundsSweepRequestsCount == 0,
177
+ "Source wallet must handle all pending moved funds sweep requests first"
178
+ );
179
+
118
180
  require(
119
181
  wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),
120
182
  "Target wallets commitment already submitted"
@@ -263,7 +325,13 @@ library MovingFunds {
263
325
  (
264
326
  bytes32 targetWalletsHash,
265
327
  uint256 outputsTotalValue
266
- ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);
328
+ ) = processMovingFundsTxOutputs(
329
+ self,
330
+ MovingFundsTxOutputsProcessingInfo(
331
+ movingFundsTxHash,
332
+ movingFundsTx.outputVector
333
+ )
334
+ );
267
335
 
268
336
  require(
269
337
  mainUtxo.txOutputValue - outputsTotalValue <=
@@ -278,10 +346,8 @@ library MovingFunds {
278
346
 
279
347
  /// @notice Processes the moving funds Bitcoin transaction output vector
280
348
  /// and extracts information required for further processing.
281
- /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output
282
- /// vector. This function assumes vector's structure is valid so it
283
- /// must be validated using e.g. `BTCUtils.validateVout` function
284
- /// before it is passed here
349
+ /// @param processInfo Processing info containing the moving funds tx
350
+ /// hash and output vector.
285
351
  /// @return targetWalletsHash keccak256 hash over the list of actual
286
352
  /// target wallets used in the transaction.
287
353
  /// @return outputsTotalValue Sum of all outputs values.
@@ -290,18 +356,17 @@ library MovingFunds {
290
356
  /// be validated by the caller as stated in their parameter doc.
291
357
  /// - Each output must refer to a 20-byte public key hash.
292
358
  /// - The total outputs value must be evenly divided over all outputs.
293
- function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)
294
- internal
295
- pure
296
- returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)
297
- {
359
+ function processMovingFundsTxOutputs(
360
+ BridgeState.Storage storage self,
361
+ MovingFundsTxOutputsProcessingInfo memory processInfo
362
+ ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {
298
363
  // Determining the total number of Bitcoin transaction outputs in
299
364
  // the same way as for number of inputs. See `BitcoinTx.outputVector`
300
365
  // docs for more details.
301
366
  (
302
367
  uint256 outputsCompactSizeUintLength,
303
368
  uint256 outputsCount
304
- ) = movingFundsTxOutputVector.parseVarInt();
369
+ ) = processInfo.movingFundsTxOutputVector.parseVarInt();
305
370
 
306
371
  // To determine the first output starting index, we must jump over
307
372
  // the compactSize uint which prepends the output vector. One byte
@@ -323,85 +388,64 @@ library MovingFunds {
323
388
  bytes20[] memory targetWallets = new bytes20[](outputsCount);
324
389
  uint64[] memory outputsValues = new uint64[](outputsCount);
325
390
 
326
- // Outputs processing loop.
327
- for (uint256 i = 0; i < outputsCount; i++) {
328
- uint256 outputLength = movingFundsTxOutputVector
391
+ // Outputs processing loop. Note that the `outputIndex` must be
392
+ // `uint32` to build proper `movedFundsSweepRequests` keys.
393
+ for (
394
+ uint32 outputIndex = 0;
395
+ outputIndex < outputsCount;
396
+ outputIndex++
397
+ ) {
398
+ uint256 outputLength = processInfo
399
+ .movingFundsTxOutputVector
329
400
  .determineOutputLengthAt(outputStartingIndex);
330
401
 
331
- bytes memory output = movingFundsTxOutputVector.slice(
402
+ bytes memory output = processInfo.movingFundsTxOutputVector.slice(
332
403
  outputStartingIndex,
333
404
  outputLength
334
405
  );
335
406
 
336
- // Extract the output script payload.
337
- bytes memory targetWalletPubKeyHashBytes = output.extractHash();
338
- // Output script payload must refer to a known wallet public key
339
- // hash which is always 20-byte.
340
- require(
341
- targetWalletPubKeyHashBytes.length == 20,
342
- "Target wallet public key hash must have 20 bytes"
343
- );
344
-
345
- bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes
346
- .slice20(0);
347
-
348
- // The next step is making sure that the 20-byte public key hash
349
- // is actually used in the right context of a P2PKH or P2WPKH
350
- // output. To do so, we must extract the full script from the output
351
- // and compare with the expected P2PKH and P2WPKH scripts
352
- // referring to that 20-byte public key hash. The output consists
353
- // of an 8-byte value and a variable length script. To extract the
354
- // script we slice the output starting from 9th byte until the end.
355
- bytes32 outputScriptKeccak = keccak256(
356
- output.slice(8, output.length - 8)
357
- );
358
- // Build the expected P2PKH script which has the following byte
359
- // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to
360
- // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
361
- // - 0x19: Byte length of the entire script
362
- // - 0x76: OP_DUP
363
- // - 0xa9: OP_HASH160
364
- // - 0x14: Byte length of the public key hash
365
- // - 0x88: OP_EQUALVERIFY
366
- // - 0xac: OP_CHECKSIG
367
- // which matches the P2PKH structure as per:
368
- // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
369
- bytes32 targetWalletP2PKHScriptKeccak = keccak256(
370
- abi.encodePacked(
371
- hex"1976a914",
372
- targetWalletPubKeyHash,
373
- hex"88ac"
374
- )
375
- );
376
- // Build the expected P2WPKH script which has the following format:
377
- // <0x160014> <20-byte PKH>. According to
378
- // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
379
- // - 0x16: Byte length of the entire script
380
- // - 0x00: OP_0
381
- // - 0x14: Byte length of the public key hash
382
- // which matches the P2WPKH structure as per:
383
- // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
384
- bytes32 targetWalletP2WPKHScriptKeccak = keccak256(
385
- abi.encodePacked(hex"160014", targetWalletPubKeyHash)
386
- );
387
- // Make sure the actual output script matches either the P2PKH
388
- // or P2WPKH format.
389
- require(
390
- outputScriptKeccak == targetWalletP2PKHScriptKeccak ||
391
- outputScriptKeccak == targetWalletP2WPKHScriptKeccak,
392
- "Output must be P2PKH or P2WPKH"
393
- );
407
+ bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);
394
408
 
395
409
  // Add the wallet public key hash to the list that will be used
396
410
  // to build the result list hash. There is no need to check if
397
411
  // given output is a change here because the actual target wallet
398
412
  // list must be exactly the same as the pre-committed target wallet
399
413
  // list which is guaranteed to be valid.
400
- targetWallets[i] = targetWalletPubKeyHash;
414
+ targetWallets[outputIndex] = targetWalletPubKeyHash;
401
415
 
402
416
  // Extract the value from given output.
403
- outputsValues[i] = output.extractValue();
404
- outputsTotalValue += outputsValues[i];
417
+ outputsValues[outputIndex] = output.extractValue();
418
+ outputsTotalValue += outputsValues[outputIndex];
419
+
420
+ // Register a moved funds sweep request that must be handled
421
+ // by the target wallet. The target wallet must sweep the
422
+ // received funds with their own main UTXO in order to update
423
+ // their BTC balance. Worth noting there is no need to check
424
+ // if the sweep request already exists in the system because
425
+ // the moving funds wallet is moved to the Closing state after
426
+ // submitting the moving funds proof so there is no possibility
427
+ // to submit the proof again and register the sweep request twice.
428
+ self.movedFundsSweepRequests[
429
+ uint256(
430
+ keccak256(
431
+ abi.encodePacked(
432
+ processInfo.movingFundsTxHash,
433
+ outputIndex
434
+ )
435
+ )
436
+ )
437
+ ] = MovedFundsSweepRequest(
438
+ targetWalletPubKeyHash,
439
+ outputsValues[outputIndex],
440
+ /* solhint-disable-next-line not-rely-on-time */
441
+ uint32(block.timestamp),
442
+ MovedFundsSweepRequestState.Pending
443
+ );
444
+ // We added a new moved funds sweep request for the target wallet
445
+ // so we must increment their request counter.
446
+ self
447
+ .registeredWallets[targetWalletPubKeyHash]
448
+ .pendingMovedFundsSweepRequestsCount++;
405
449
 
406
450
  // Make the `outputStartingIndex` pointing to the next output by
407
451
  // increasing it by current output's length.
@@ -521,4 +565,470 @@ library MovingFunds {
521
565
  // slither-disable-next-line reentrancy-events
522
566
  emit MovingFundsBelowDustReported(walletPubKeyHash);
523
567
  }
568
+
569
+ /// @notice Used by the wallet to prove the BTC moved funds sweep
570
+ /// transaction and to make the necessary state changes. Moved
571
+ /// funds sweep is only accepted if it satisfies SPV proof.
572
+ ///
573
+ /// The function validates the sweep transaction structure by
574
+ /// checking if it actually spends the moved funds UTXO and the
575
+ /// sweeping wallet's main UTXO (optionally), and if it locks the
576
+ /// value on the sweeping wallet's 20-byte public key hash using a
577
+ /// reasonable transaction fee. If all preconditions are
578
+ /// met, this function updates the sweeping wallet main UTXO, thus
579
+ /// their BTC balance.
580
+ ///
581
+ /// It is possible to prove the given sweep transaction only
582
+ /// one time.
583
+ /// @param sweepTx Bitcoin sweep funds transaction data
584
+ /// @param sweepProof Bitcoin sweep funds proof data
585
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently
586
+ /// known on the Ethereum chain
587
+ /// @dev Requirements:
588
+ /// - `sweepTx` components must match the expected structure. See
589
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
590
+ /// correspond to appropriate Bitcoin transaction fields to produce
591
+ /// a provable transaction hash.
592
+ /// - The `sweepTx` should represent a Bitcoin transaction with
593
+ /// the first input pointing to a wallet's sweep Pending request and,
594
+ /// optionally, the second input pointing to the wallet's main UTXO,
595
+ /// if the sweeping wallet has a main UTXO set. There should be only
596
+ /// one output locking funds on the sweeping wallet 20-byte public
597
+ /// key hash.
598
+ /// - `sweepProof` components must match the expected structure.
599
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
600
+ /// field must contain a valid number of block headers, not less
601
+ /// than the `txProofDifficultyFactor` contract constant.
602
+ /// - `mainUtxo` components must point to the recent main UTXO
603
+ /// of the sweeping wallet, as currently known on the Ethereum chain.
604
+ /// If there is no main UTXO, this parameter is ignored.
605
+ /// - The sweeping wallet must be in the Live or MovingFunds state.
606
+ /// - The total Bitcoin transaction fee must be lesser or equal
607
+ /// to `movedFundsSweepTxMaxTotalFee` governable parameter.
608
+ function submitMovedFundsSweepProof(
609
+ BridgeState.Storage storage self,
610
+ BitcoinTx.Info calldata sweepTx,
611
+ BitcoinTx.Proof calldata sweepProof,
612
+ BitcoinTx.UTXO calldata mainUtxo
613
+ ) external {
614
+ // The actual transaction proof is performed here. After that point, we
615
+ // can assume the transaction happened on Bitcoin chain and has
616
+ // a sufficient number of confirmations as determined by
617
+ // `txProofDifficultyFactor` constant.
618
+ bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);
619
+
620
+ (
621
+ bytes20 walletPubKeyHash,
622
+ uint64 sweepTxOutputValue
623
+ ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);
624
+
625
+ (
626
+ Wallets.Wallet storage wallet,
627
+ BitcoinTx.UTXO memory resolvedMainUtxo
628
+ ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);
629
+
630
+ uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(
631
+ self,
632
+ sweepTx.inputVector,
633
+ resolvedMainUtxo,
634
+ walletPubKeyHash
635
+ );
636
+
637
+ require(
638
+ sweepTxInputsTotalValue - sweepTxOutputValue <=
639
+ self.movedFundsSweepTxMaxTotalFee,
640
+ "Transaction fee is too high"
641
+ );
642
+
643
+ // Use the sweep transaction output as the new sweeping wallet's main UTXO.
644
+ // Transaction output index is always 0 as sweep transaction always
645
+ // contains only one output.
646
+ wallet.mainUtxoHash = keccak256(
647
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
648
+ );
649
+
650
+ // slither-disable-next-line reentrancy-events
651
+ emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);
652
+ }
653
+
654
+ /// @notice Processes the Bitcoin moved funds sweep transaction output vector
655
+ /// by extracting the single output and using it to gain additional
656
+ /// information required for further processing (e.g. value and
657
+ /// wallet public key hash).
658
+ /// @param sweepTxOutputVector Bitcoin moved funds sweep transaction output
659
+ /// vector.
660
+ /// This function assumes vector's structure is valid so it must be
661
+ /// validated using e.g. `BTCUtils.validateVout` function before
662
+ /// it is passed here
663
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
664
+ /// @return value 8-byte moved funds sweep transaction output value.
665
+ /// @dev Requirements:
666
+ /// - Output vector must contain only one output
667
+ /// - The single output must be of P2PKH or P2WPKH type and lock the
668
+ /// funds on a 20-byte public key hash
669
+ function processMovedFundsSweepTxOutput(
670
+ BridgeState.Storage storage self,
671
+ bytes memory sweepTxOutputVector
672
+ ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {
673
+ // To determine the total number of sweep transaction outputs, we need to
674
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
675
+ // That compactSize uint encodes the number of vector elements using the
676
+ // format presented in:
677
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
678
+ // We don't need asserting the compactSize uint is parseable since it
679
+ // was already checked during `validateVout` validation performed as
680
+ // part of the `BitcoinTx.validateProof` call.
681
+ // See `BitcoinTx.outputVector` docs for more details.
682
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
683
+ require(
684
+ outputsCount == 1,
685
+ "Moved funds sweep transaction must have a single output"
686
+ );
687
+
688
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
689
+ walletPubKeyHash = self.extractPubKeyHash(output);
690
+ value = output.extractValue();
691
+
692
+ return (walletPubKeyHash, value);
693
+ }
694
+
695
+ /// @notice Resolves sweeping wallet based on the provided wallet public key
696
+ /// hash. Validates the wallet state and current main UTXO, as
697
+ /// currently known on the Ethereum chain.
698
+ /// @param walletPubKeyHash public key hash of the wallet proving the sweep
699
+ /// Bitcoin transaction.
700
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
701
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
702
+ /// this parameter is ignored
703
+ /// @return wallet Data of the sweeping wallet.
704
+ /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet
705
+ /// resolved by cross-checking the `mainUtxo` parameter with
706
+ /// the chain state. If the validation went well, this is the
707
+ /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.
708
+ /// @dev Requirements:
709
+ /// - Sweeping wallet must be either in Live or MovingFunds state.
710
+ /// - If the main UTXO of the sweeping wallet exists in the storage,
711
+ /// the passed `mainUTXO` parameter must be equal to the stored one.
712
+ function resolveMovedFundsSweepingWallet(
713
+ BridgeState.Storage storage self,
714
+ bytes20 walletPubKeyHash,
715
+ BitcoinTx.UTXO calldata mainUtxo
716
+ )
717
+ internal
718
+ view
719
+ returns (
720
+ Wallets.Wallet storage wallet,
721
+ BitcoinTx.UTXO memory resolvedMainUtxo
722
+ )
723
+ {
724
+ wallet = self.registeredWallets[walletPubKeyHash];
725
+
726
+ Wallets.WalletState walletState = wallet.state;
727
+ require(
728
+ walletState == Wallets.WalletState.Live ||
729
+ walletState == Wallets.WalletState.MovingFunds,
730
+ "Wallet must be in Live or MovingFunds state"
731
+ );
732
+
733
+ // Check if the main UTXO for given wallet exists. If so, validate
734
+ // passed main UTXO data against the stored hash and use them for
735
+ // further processing. If no main UTXO exists, use empty data.
736
+ resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);
737
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
738
+ if (mainUtxoHash != bytes32(0)) {
739
+ require(
740
+ keccak256(
741
+ abi.encodePacked(
742
+ mainUtxo.txHash,
743
+ mainUtxo.txOutputIndex,
744
+ mainUtxo.txOutputValue
745
+ )
746
+ ) == mainUtxoHash,
747
+ "Invalid main UTXO data"
748
+ );
749
+ resolvedMainUtxo = mainUtxo;
750
+ }
751
+ }
752
+
753
+ /// @notice Processes the Bitcoin moved funds sweep transaction input vector.
754
+ /// It extracts the first input and tries to match it with one of
755
+ /// the moved funds sweep requests targeting the sweeping wallet.
756
+ /// If the sweep request is an existing Pending request, this
757
+ /// function marks it as Processed. If the sweeping wallet has a
758
+ /// main UTXO, this function extracts the second input, makes sure
759
+ /// it refers to the wallet main UTXO, and marks that main UTXO as
760
+ /// correctly spent.
761
+ /// @param sweepTxInputVector Bitcoin moved funds sweep transaction input vector.
762
+ /// This function assumes vector's structure is valid so it must be
763
+ /// validated using e.g. `BTCUtils.validateVin` function before
764
+ /// it is passed here
765
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO. If no main UTXO
766
+ /// exists for the given the wallet, this parameter's fields should
767
+ /// be zeroed to bypass the main UTXO validation
768
+ /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet
769
+ /// @return inputsTotalValue Total inputs value sum.
770
+ /// @dev Requirements:
771
+ /// - The input vector must consist of one mandatory and one optional
772
+ /// input.
773
+ /// - The mandatory input must be the first input in the vector
774
+ /// - The mandatory input must point to a Pending moved funds sweep
775
+ /// request that is targeted to the sweeping wallet
776
+ /// - The optional output must be the second input in the vector
777
+ /// - The optional input is required if the sweeping wallet has a
778
+ /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,
779
+ /// that input must point the the sweeping wallet main UTXO.
780
+ function processMovedFundsSweepTxInputs(
781
+ BridgeState.Storage storage self,
782
+ bytes memory sweepTxInputVector,
783
+ BitcoinTx.UTXO memory mainUtxo,
784
+ bytes20 walletPubKeyHash
785
+ ) internal returns (uint256 inputsTotalValue) {
786
+ // To determine the total number of Bitcoin transaction inputs,
787
+ // we need to parse the compactSize uint (VarInt) the input vector is
788
+ // prepended by. That compactSize uint encodes the number of vector
789
+ // elements using the format presented in:
790
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
791
+ // We don't need asserting the compactSize uint is parseable since it
792
+ // was already checked during `validateVin` validation performed as
793
+ // part of the `BitcoinTx.validateProof` call.
794
+ // See `BitcoinTx.inputVector` docs for more details.
795
+ (
796
+ uint256 inputsCompactSizeUintLength,
797
+ uint256 inputsCount
798
+ ) = sweepTxInputVector.parseVarInt();
799
+
800
+ // To determine the first input starting index, we must jump over
801
+ // the compactSize uint which prepends the input vector. One byte
802
+ // must be added because `BtcUtils.parseVarInt` does not include
803
+ // compactSize uint tag in the returned length.
804
+ //
805
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
806
+ // returns `0`, so we jump over one byte of compactSize uint.
807
+ //
808
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
809
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
810
+ // tag byte included) so we need to jump over 1+2 bytes of
811
+ // compactSize uint.
812
+ //
813
+ // Please refer `BTCUtils` library and compactSize uint
814
+ // docs in `BitcoinTx` library for more details.
815
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
816
+
817
+ // We always expect the first input to be the swept UTXO. Additionally,
818
+ // if the sweeping wallet has a main UTXO, that main UTXO should be
819
+ // pointed by the second input.
820
+ require(
821
+ inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),
822
+ "Moved funds sweep transaction must have a proper inputs count"
823
+ );
824
+
825
+ // Parse the first input and extract its outpoint tx hash and index.
826
+ (
827
+ bytes32 firstInputOutpointTxHash,
828
+ uint32 firstInputOutpointIndex,
829
+ uint256 firstInputLength
830
+ ) = parseMovedFundsSweepTxInputAt(
831
+ sweepTxInputVector,
832
+ inputStartingIndex
833
+ );
834
+
835
+ // Build the request key and fetch the corresponding moved funds sweep
836
+ // request from contract storage.
837
+ MovedFundsSweepRequest storage sweepRequest = self
838
+ .movedFundsSweepRequests[
839
+ uint256(
840
+ keccak256(
841
+ abi.encodePacked(
842
+ firstInputOutpointTxHash,
843
+ firstInputOutpointIndex
844
+ )
845
+ )
846
+ )
847
+ ];
848
+
849
+ require(
850
+ sweepRequest.state == MovedFundsSweepRequestState.Pending,
851
+ "Sweep request must be in Pending state"
852
+ );
853
+ // We must check if the wallet extracted from the moved funds sweep
854
+ // transaction output is truly the owner of the sweep request connected
855
+ // with the swept UTXO. This is needed to prevent a case when a wallet
856
+ // handles its own sweep request but locks the funds on another
857
+ // wallet public key hash.
858
+ require(
859
+ sweepRequest.walletPubKeyHash == walletPubKeyHash,
860
+ "Sweep request belongs to another wallet"
861
+ );
862
+ // If the validation passed, the sweep request must be marked as
863
+ // processed and its value should be counted into the total inputs
864
+ // value sum.
865
+ sweepRequest.state = MovedFundsSweepRequestState.Processed;
866
+ inputsTotalValue += sweepRequest.value;
867
+
868
+ self
869
+ .registeredWallets[walletPubKeyHash]
870
+ .pendingMovedFundsSweepRequestsCount--;
871
+
872
+ // If the main UTXO for the sweeping wallet exists, it must be processed.
873
+ if (mainUtxo.txHash != bytes32(0)) {
874
+ // The second input is supposed to point to that sweeping wallet
875
+ // main UTXO. We need to parse that input.
876
+ (
877
+ bytes32 secondInputOutpointTxHash,
878
+ uint32 secondInputOutpointIndex,
879
+
880
+ ) = parseMovedFundsSweepTxInputAt(
881
+ sweepTxInputVector,
882
+ inputStartingIndex + firstInputLength
883
+ );
884
+ // Make sure the second input refers to the sweeping wallet main UTXO.
885
+ require(
886
+ mainUtxo.txHash == secondInputOutpointTxHash &&
887
+ mainUtxo.txOutputIndex == secondInputOutpointIndex,
888
+ "Second input must point to the wallet's main UTXO"
889
+ );
890
+
891
+ // If the validation passed, count the main UTXO value into the
892
+ // total inputs value sum.
893
+ inputsTotalValue += mainUtxo.txOutputValue;
894
+
895
+ // Main UTXO used as an input, mark it as spent. This is needed
896
+ // to defend against fraud challenges referring to this main UTXO.
897
+ self.spentMainUTXOs[
898
+ uint256(
899
+ keccak256(
900
+ abi.encodePacked(
901
+ secondInputOutpointTxHash,
902
+ secondInputOutpointIndex
903
+ )
904
+ )
905
+ )
906
+ ] = true;
907
+ }
908
+
909
+ return inputsTotalValue;
910
+ }
911
+
912
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
913
+ /// @param inputVector Bitcoin transaction input vector
914
+ /// @param inputStartingIndex Index the given input starts at
915
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
916
+ /// pointed in the given input's outpoint.
917
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
918
+ /// which is pointed in the given input's outpoint.
919
+ /// @return inputLength Byte length of the given input.
920
+ /// @dev This function assumes vector's structure is valid so it must be
921
+ /// validated using e.g. `BTCUtils.validateVin` function before it
922
+ /// is passed here.
923
+ function parseMovedFundsSweepTxInputAt(
924
+ bytes memory inputVector,
925
+ uint256 inputStartingIndex
926
+ )
927
+ internal
928
+ pure
929
+ returns (
930
+ bytes32 outpointTxHash,
931
+ uint32 outpointIndex,
932
+ uint256 inputLength
933
+ )
934
+ {
935
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
936
+
937
+ outpointIndex = BTCUtils.reverseUint32(
938
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
939
+ );
940
+
941
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
942
+
943
+ return (outpointTxHash, outpointIndex, inputLength);
944
+ }
945
+
946
+ /// @notice Notifies about a timed out moved funds sweep process. If the
947
+ /// wallet is not terminated yet, that function terminates
948
+ /// the wallet and slashes signing group members as a result.
949
+ /// Marks the given sweep request as TimedOut.
950
+ /// @param movingFundsTxHash 32-byte hash of the moving funds transaction
951
+ /// that caused the sweep request to be created
952
+ /// @param movingFundsTxOutputIndex Index of the moving funds transaction
953
+ /// output that is subject of the sweep request.
954
+ /// @param walletMembersIDs Identifiers of the wallet signing group members
955
+ /// @dev Requirements:
956
+ /// - The moved funds sweep request must be in the Pending state
957
+ /// - The moved funds sweep timeout must be actually exceeded
958
+ /// - The wallet must be either in the Live or MovingFunds or
959
+ /// Terminated state
960
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
961
+ /// be exactly the same as the hash stored under `membersIdsHash`
962
+ /// for the given `walletID`. Those IDs are not directly stored
963
+ /// in the contract for gas efficiency purposes but they can be
964
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
965
+ /// events of the `WalletRegistry` contract
966
+ function notifyMovedFundsSweepTimeout(
967
+ BridgeState.Storage storage self,
968
+ bytes32 movingFundsTxHash,
969
+ uint32 movingFundsTxOutputIndex,
970
+ uint32[] calldata walletMembersIDs
971
+ ) external {
972
+ MovedFundsSweepRequest storage sweepRequest = self
973
+ .movedFundsSweepRequests[
974
+ uint256(
975
+ keccak256(
976
+ abi.encodePacked(
977
+ movingFundsTxHash,
978
+ movingFundsTxOutputIndex
979
+ )
980
+ )
981
+ )
982
+ ];
983
+
984
+ require(
985
+ sweepRequest.state == MovedFundsSweepRequestState.Pending,
986
+ "Sweep request must be in Pending state"
987
+ );
988
+
989
+ require(
990
+ /* solhint-disable-next-line not-rely-on-time */
991
+ block.timestamp >
992
+ sweepRequest.createdAt + self.movedFundsSweepTimeout,
993
+ "Sweep request has not timed out yet"
994
+ );
995
+
996
+ bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;
997
+ Wallets.Wallet storage wallet = self.registeredWallets[
998
+ walletPubKeyHash
999
+ ];
1000
+ Wallets.WalletState walletState = wallet.state;
1001
+
1002
+ require(
1003
+ walletState == Wallets.WalletState.Live ||
1004
+ walletState == Wallets.WalletState.MovingFunds ||
1005
+ walletState == Wallets.WalletState.Terminated,
1006
+ "ECDSA wallet must be in Live or MovingFunds or Terminated state"
1007
+ );
1008
+
1009
+ sweepRequest.state = MovedFundsSweepRequestState.TimedOut;
1010
+ wallet.pendingMovedFundsSweepRequestsCount--;
1011
+
1012
+ if (
1013
+ walletState == Wallets.WalletState.Live ||
1014
+ walletState == Wallets.WalletState.MovingFunds
1015
+ ) {
1016
+ self.terminateWallet(walletPubKeyHash);
1017
+
1018
+ self.ecdsaWalletRegistry.seize(
1019
+ self.movedFundsSweepTimeoutSlashingAmount,
1020
+ self.movedFundsSweepTimeoutNotifierRewardMultiplier,
1021
+ msg.sender,
1022
+ wallet.ecdsaWalletID,
1023
+ walletMembersIDs
1024
+ );
1025
+ }
1026
+
1027
+ // slither-disable-next-line reentrancy-events
1028
+ emit MovedFundsSweepTimedOut(
1029
+ walletPubKeyHash,
1030
+ movingFundsTxHash,
1031
+ movingFundsTxOutputIndex
1032
+ );
1033
+ }
524
1034
  }