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

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 (70) hide show
  1. package/artifacts/Bank.json +3 -3
  2. package/artifacts/Bridge.json +515 -191
  3. package/artifacts/Deposit.json +7 -7
  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 +7 -7
  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 +40 -10
  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 → 5dd2a7c685770548b7ea9ce25e179326.json} +9 -9
  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 +266 -103
  39. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  40. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +8 -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/{Sweep.sol/Sweep.json → DepositSweep.sol/DepositSweep.json} +4 -4
  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 +21 -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 +90 -8
  63. package/contracts/bridge/BridgeState.sol +34 -3
  64. package/contracts/bridge/{Sweep.sol → DepositSweep.sol} +30 -18
  65. package/contracts/bridge/MovingFunds.sol +469 -76
  66. package/deploy/05_deploy_bridge.ts +5 -2
  67. package/export.json +313 -56
  68. package/package.json +1 -1
  69. package/artifacts/Sweep.json +0 -76
  70. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +0 -4
@@ -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,38 @@ 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 a moved funds sweep request. The request is
62
+ /// registered in `submitMovingFundsProof` where we know funds
63
+ /// have been moved to the target wallet and the only step left is
64
+ /// to have the target wallet sweep them.
65
+ struct MovedFundsSweepRequest {
66
+ // 20-byte public key hash of the wallet supposed to sweep the UTXO
67
+ // representing the received funds with their own main UTXO
68
+ bytes20 walletPubKeyHash;
69
+ // Value of the received funds.
70
+ uint64 value;
71
+ // UNIX timestamp the request was created at.
72
+ uint32 createdAt;
73
+ // UNIX timestamp the funds were swept at.
74
+ uint32 sweptAt;
75
+ }
76
+
42
77
  event MovingFundsCommitmentSubmitted(
43
78
  bytes20 walletPubKeyHash,
44
79
  bytes20[] targetWallets,
@@ -54,6 +89,8 @@ library MovingFunds {
54
89
 
55
90
  event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);
56
91
 
92
+ event MovedFundsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
93
+
57
94
  /// @notice Submits the moving funds target wallets commitment.
58
95
  /// Once all requirements are met, that function registers the
59
96
  /// target wallets commitment and opens the way for moving funds
@@ -263,7 +300,13 @@ library MovingFunds {
263
300
  (
264
301
  bytes32 targetWalletsHash,
265
302
  uint256 outputsTotalValue
266
- ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);
303
+ ) = processMovingFundsTxOutputs(
304
+ self,
305
+ MovingFundsTxOutputsProcessingInfo(
306
+ movingFundsTxHash,
307
+ movingFundsTx.outputVector
308
+ )
309
+ );
267
310
 
268
311
  require(
269
312
  mainUtxo.txOutputValue - outputsTotalValue <=
@@ -278,10 +321,8 @@ library MovingFunds {
278
321
 
279
322
  /// @notice Processes the moving funds Bitcoin transaction output vector
280
323
  /// 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
324
+ /// @param processInfo Processing info containing the moving funds tx
325
+ /// hash and output vector.
285
326
  /// @return targetWalletsHash keccak256 hash over the list of actual
286
327
  /// target wallets used in the transaction.
287
328
  /// @return outputsTotalValue Sum of all outputs values.
@@ -290,18 +331,17 @@ library MovingFunds {
290
331
  /// be validated by the caller as stated in their parameter doc.
291
332
  /// - Each output must refer to a 20-byte public key hash.
292
333
  /// - 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
- {
334
+ function processMovingFundsTxOutputs(
335
+ BridgeState.Storage storage self,
336
+ MovingFundsTxOutputsProcessingInfo memory processInfo
337
+ ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {
298
338
  // Determining the total number of Bitcoin transaction outputs in
299
339
  // the same way as for number of inputs. See `BitcoinTx.outputVector`
300
340
  // docs for more details.
301
341
  (
302
342
  uint256 outputsCompactSizeUintLength,
303
343
  uint256 outputsCount
304
- ) = movingFundsTxOutputVector.parseVarInt();
344
+ ) = processInfo.movingFundsTxOutputVector.parseVarInt();
305
345
 
306
346
  // To determine the first output starting index, we must jump over
307
347
  // the compactSize uint which prepends the output vector. One byte
@@ -323,85 +363,59 @@ library MovingFunds {
323
363
  bytes20[] memory targetWallets = new bytes20[](outputsCount);
324
364
  uint64[] memory outputsValues = new uint64[](outputsCount);
325
365
 
326
- // Outputs processing loop.
327
- for (uint256 i = 0; i < outputsCount; i++) {
328
- uint256 outputLength = movingFundsTxOutputVector
366
+ // Outputs processing loop. Note that the `outputIndex` must be
367
+ // `uint32` to build proper `movedFundsSweepRequests` keys.
368
+ for (
369
+ uint32 outputIndex = 0;
370
+ outputIndex < outputsCount;
371
+ outputIndex++
372
+ ) {
373
+ uint256 outputLength = processInfo
374
+ .movingFundsTxOutputVector
329
375
  .determineOutputLengthAt(outputStartingIndex);
330
376
 
331
- bytes memory output = movingFundsTxOutputVector.slice(
377
+ bytes memory output = processInfo.movingFundsTxOutputVector.slice(
332
378
  outputStartingIndex,
333
379
  outputLength
334
380
  );
335
381
 
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
- );
382
+ bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);
394
383
 
395
384
  // Add the wallet public key hash to the list that will be used
396
385
  // to build the result list hash. There is no need to check if
397
386
  // given output is a change here because the actual target wallet
398
387
  // list must be exactly the same as the pre-committed target wallet
399
388
  // list which is guaranteed to be valid.
400
- targetWallets[i] = targetWalletPubKeyHash;
389
+ targetWallets[outputIndex] = targetWalletPubKeyHash;
401
390
 
402
391
  // Extract the value from given output.
403
- outputsValues[i] = output.extractValue();
404
- outputsTotalValue += outputsValues[i];
392
+ outputsValues[outputIndex] = output.extractValue();
393
+ outputsTotalValue += outputsValues[outputIndex];
394
+
395
+ // Register a moved funds sweep request that must be handled
396
+ // by the target wallet. The target wallet must sweep the
397
+ // received funds with their own main UTXO in order to update
398
+ // their BTC balance. Worth noting there is no need to check
399
+ // if the sweep request already exists in the system because
400
+ // the moving funds wallet is moved to the Closing state after
401
+ // submitting the moving funds proof so there is no possibility
402
+ // to submit the proof again and register the sweep request twice.
403
+ self.movedFundsSweepRequests[
404
+ uint256(
405
+ keccak256(
406
+ abi.encodePacked(
407
+ processInfo.movingFundsTxHash,
408
+ outputIndex
409
+ )
410
+ )
411
+ )
412
+ ] = MovedFundsSweepRequest(
413
+ targetWalletPubKeyHash,
414
+ outputsValues[outputIndex],
415
+ /* solhint-disable-next-line not-rely-on-time */
416
+ uint32(block.timestamp),
417
+ 0
418
+ );
405
419
 
406
420
  // Make the `outputStartingIndex` pointing to the next output by
407
421
  // increasing it by current output's length.
@@ -521,4 +535,383 @@ library MovingFunds {
521
535
  // slither-disable-next-line reentrancy-events
522
536
  emit MovingFundsBelowDustReported(walletPubKeyHash);
523
537
  }
538
+
539
+ /// @notice Used by the wallet to prove the BTC moved funds sweep
540
+ /// transaction and to make the necessary state changes. Moved
541
+ /// funds sweep is only accepted if it satisfies SPV proof.
542
+ ///
543
+ /// The function validates the sweep transaction structure by
544
+ /// checking if it actually spends the moved funds UTXO and the
545
+ /// sweeping wallet's main UTXO (optionally), and if it locks the
546
+ /// value on the sweeping wallet's 20-byte public key hash using a
547
+ /// reasonable transaction fee. If all preconditions are
548
+ /// met, this function updates the sweeping wallet main UTXO, thus
549
+ /// their BTC balance.
550
+ ///
551
+ /// It is possible to prove the given sweep transaction only
552
+ /// one time.
553
+ /// @param sweepTx Bitcoin sweep funds transaction data
554
+ /// @param sweepProof Bitcoin sweep funds proof data
555
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently
556
+ /// known on the Ethereum chain
557
+ /// @dev Requirements:
558
+ /// - `sweepTx` components must match the expected structure. See
559
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
560
+ /// correspond to appropriate Bitcoin transaction fields to produce
561
+ /// a provable transaction hash.
562
+ /// - The `sweepTx` should represent a Bitcoin transaction with
563
+ /// the first input pointing to a wallet's sweep request and,
564
+ /// optionally, the second input pointing to the wallet's main UTXO,
565
+ /// if the sweeping wallet has a main UTXO set. There should be only
566
+ /// one output locking funds on the sweeping wallet 20-byte public
567
+ /// key hash.
568
+ /// - `sweepProof` components must match the expected structure.
569
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
570
+ /// field must contain a valid number of block headers, not less
571
+ /// than the `txProofDifficultyFactor` contract constant.
572
+ /// - `mainUtxo` components must point to the recent main UTXO
573
+ /// of the sweeping wallet, as currently known on the Ethereum chain.
574
+ /// If there is no main UTXO, this parameter is ignored.
575
+ /// - The sweeping wallet must be in the Live or MovingFunds state.
576
+ /// - The total Bitcoin transaction fee must be lesser or equal
577
+ /// to `movedFundsSweepTxMaxTotalFee` governable parameter.
578
+ function submitMovedFundsSweepProof(
579
+ BridgeState.Storage storage self,
580
+ BitcoinTx.Info calldata sweepTx,
581
+ BitcoinTx.Proof calldata sweepProof,
582
+ BitcoinTx.UTXO calldata mainUtxo
583
+ ) external {
584
+ // The actual transaction proof is performed here. After that point, we
585
+ // can assume the transaction happened on Bitcoin chain and has
586
+ // a sufficient number of confirmations as determined by
587
+ // `txProofDifficultyFactor` constant.
588
+ bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);
589
+
590
+ (
591
+ bytes20 walletPubKeyHash,
592
+ uint64 sweepTxOutputValue
593
+ ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);
594
+
595
+ (
596
+ Wallets.Wallet storage wallet,
597
+ BitcoinTx.UTXO memory resolvedMainUtxo
598
+ ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);
599
+
600
+ uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(
601
+ self,
602
+ sweepTx.inputVector,
603
+ resolvedMainUtxo,
604
+ walletPubKeyHash
605
+ );
606
+
607
+ require(
608
+ sweepTxInputsTotalValue - sweepTxOutputValue <=
609
+ self.movedFundsSweepTxMaxTotalFee,
610
+ "Transaction fee is too high"
611
+ );
612
+
613
+ // Use the sweep transaction output as the new sweeping wallet's main UTXO.
614
+ // Transaction output index is always 0 as sweep transaction always
615
+ // contains only one output.
616
+ wallet.mainUtxoHash = keccak256(
617
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
618
+ );
619
+
620
+ // slither-disable-next-line reentrancy-events
621
+ emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);
622
+ }
623
+
624
+ /// @notice Processes the Bitcoin moved funds sweep transaction output vector
625
+ /// by extracting the single output and using it to gain additional
626
+ /// information required for further processing (e.g. value and
627
+ /// wallet public key hash).
628
+ /// @param sweepTxOutputVector Bitcoin moved funds sweep transaction output
629
+ /// vector.
630
+ /// This function assumes vector's structure is valid so it must be
631
+ /// validated using e.g. `BTCUtils.validateVout` function before
632
+ /// it is passed here
633
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
634
+ /// @return value 8-byte moved funds sweep transaction output value.
635
+ /// @dev Requirements:
636
+ /// - Output vector must contain only one output
637
+ /// - The single output must be of P2PKH or P2WPKH type and lock the
638
+ /// funds on a 20-byte public key hash
639
+ function processMovedFundsSweepTxOutput(
640
+ BridgeState.Storage storage self,
641
+ bytes memory sweepTxOutputVector
642
+ ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {
643
+ // To determine the total number of sweep transaction outputs, we need to
644
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
645
+ // That compactSize uint encodes the number of vector elements using the
646
+ // format presented in:
647
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
648
+ // We don't need asserting the compactSize uint is parseable since it
649
+ // was already checked during `validateVout` validation performed as
650
+ // part of the `BitcoinTx.validateProof` call.
651
+ // See `BitcoinTx.outputVector` docs for more details.
652
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
653
+ require(
654
+ outputsCount == 1,
655
+ "Moved funds sweep transaction must have a single output"
656
+ );
657
+
658
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
659
+ walletPubKeyHash = self.extractPubKeyHash(output);
660
+ value = output.extractValue();
661
+
662
+ return (walletPubKeyHash, value);
663
+ }
664
+
665
+ /// @notice Resolves sweeping wallet based on the provided wallet public key
666
+ /// hash. Validates the wallet state and current main UTXO, as
667
+ /// currently known on the Ethereum chain.
668
+ /// @param walletPubKeyHash public key hash of the wallet proving the sweep
669
+ /// Bitcoin transaction.
670
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
671
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
672
+ /// this parameter is ignored
673
+ /// @return wallet Data of the sweeping wallet.
674
+ /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet
675
+ /// resolved by cross-checking the `mainUtxo` parameter with
676
+ /// the chain state. If the validation went well, this is the
677
+ /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.
678
+ /// @dev Requirements:
679
+ /// - Sweeping wallet must be either in Live or MovingFunds state.
680
+ /// - If the main UTXO of the sweeping wallet exists in the storage,
681
+ /// the passed `mainUTXO` parameter must be equal to the stored one.
682
+ function resolveMovedFundsSweepingWallet(
683
+ BridgeState.Storage storage self,
684
+ bytes20 walletPubKeyHash,
685
+ BitcoinTx.UTXO calldata mainUtxo
686
+ )
687
+ internal
688
+ view
689
+ returns (
690
+ Wallets.Wallet storage wallet,
691
+ BitcoinTx.UTXO memory resolvedMainUtxo
692
+ )
693
+ {
694
+ wallet = self.registeredWallets[walletPubKeyHash];
695
+
696
+ Wallets.WalletState walletState = wallet.state;
697
+ require(
698
+ walletState == Wallets.WalletState.Live ||
699
+ walletState == Wallets.WalletState.MovingFunds,
700
+ "Wallet must be in Live or MovingFunds state"
701
+ );
702
+
703
+ // Check if the main UTXO for given wallet exists. If so, validate
704
+ // passed main UTXO data against the stored hash and use them for
705
+ // further processing. If no main UTXO exists, use empty data.
706
+ resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);
707
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
708
+ if (mainUtxoHash != bytes32(0)) {
709
+ require(
710
+ keccak256(
711
+ abi.encodePacked(
712
+ mainUtxo.txHash,
713
+ mainUtxo.txOutputIndex,
714
+ mainUtxo.txOutputValue
715
+ )
716
+ ) == mainUtxoHash,
717
+ "Invalid main UTXO data"
718
+ );
719
+ resolvedMainUtxo = mainUtxo;
720
+ }
721
+ }
722
+
723
+ /// @notice Processes the Bitcoin moved funds sweep transaction input vector.
724
+ /// It extracts the first input and tries to match it with one of
725
+ /// the moved funds sweep requests targeting the sweeping wallet.
726
+ /// If the sweep request is found and not yet processed, this
727
+ /// function marks it as processed. If the sweeping wallet has a
728
+ /// main UTXO, this function extracts the second input, makes sure
729
+ /// it refers to the wallet main UTXO, and marks that main UTXO as
730
+ /// correctly spent.
731
+ /// @param sweepTxInputVector Bitcoin moved funds sweep transaction input vector.
732
+ /// This function assumes vector's structure is valid so it must be
733
+ /// validated using e.g. `BTCUtils.validateVin` function before
734
+ /// it is passed here
735
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO. If no main UTXO
736
+ /// exists for the given the wallet, this parameter's fields should
737
+ /// be zeroed to bypass the main UTXO validation
738
+ /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet
739
+ /// @return inputsTotalValue Total inputs value sum.
740
+ /// @dev Requirements:
741
+ /// - The input vector must consist of one mandatory and one optional
742
+ /// input.
743
+ /// - The mandatory input must be the first input in the vector
744
+ /// - The mandatory input must point to a known moved funds sweep
745
+ /// request that is not processed yet and is targeted to the sweeping
746
+ /// wallet
747
+ /// - The optional output must be the second input in the vector
748
+ /// - The optional input is required if the sweeping wallet has a
749
+ /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,
750
+ /// that input must point the the sweeping wallet main UTXO.
751
+ function processMovedFundsSweepTxInputs(
752
+ BridgeState.Storage storage self,
753
+ bytes memory sweepTxInputVector,
754
+ BitcoinTx.UTXO memory mainUtxo,
755
+ bytes20 walletPubKeyHash
756
+ ) internal returns (uint256 inputsTotalValue) {
757
+ // To determine the total number of Bitcoin transaction inputs,
758
+ // we need to parse the compactSize uint (VarInt) the input vector is
759
+ // prepended by. That compactSize uint encodes the number of vector
760
+ // elements using the format presented in:
761
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
762
+ // We don't need asserting the compactSize uint is parseable since it
763
+ // was already checked during `validateVin` validation performed as
764
+ // part of the `BitcoinTx.validateProof` call.
765
+ // See `BitcoinTx.inputVector` docs for more details.
766
+ (
767
+ uint256 inputsCompactSizeUintLength,
768
+ uint256 inputsCount
769
+ ) = sweepTxInputVector.parseVarInt();
770
+
771
+ // To determine the first input starting index, we must jump over
772
+ // the compactSize uint which prepends the input vector. One byte
773
+ // must be added because `BtcUtils.parseVarInt` does not include
774
+ // compactSize uint tag in the returned length.
775
+ //
776
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
777
+ // returns `0`, so we jump over one byte of compactSize uint.
778
+ //
779
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
780
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
781
+ // tag byte included) so we need to jump over 1+2 bytes of
782
+ // compactSize uint.
783
+ //
784
+ // Please refer `BTCUtils` library and compactSize uint
785
+ // docs in `BitcoinTx` library for more details.
786
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
787
+
788
+ // We always expect the first input to be the swept UTXO. Additionally,
789
+ // if the sweeping wallet has a main UTXO, that main UTXO should be
790
+ // pointed by the second input.
791
+ require(
792
+ inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),
793
+ "Moved funds sweep transaction must have a proper inputs count"
794
+ );
795
+
796
+ // Parse the first input and extract its outpoint tx hash and index.
797
+ (
798
+ bytes32 firstInputOutpointTxHash,
799
+ uint32 firstInputOutpointIndex,
800
+ uint256 firstInputLength
801
+ ) = parseMovedFundsSweepTxInputAt(
802
+ sweepTxInputVector,
803
+ inputStartingIndex
804
+ );
805
+
806
+ // Build the request key and fetch the corresponding moved funds sweep
807
+ // request from contract storage.
808
+ MovedFundsSweepRequest storage sweepRequest = self
809
+ .movedFundsSweepRequests[
810
+ uint256(
811
+ keccak256(
812
+ abi.encodePacked(
813
+ firstInputOutpointTxHash,
814
+ firstInputOutpointIndex
815
+ )
816
+ )
817
+ )
818
+ ];
819
+
820
+ // The sweep request must exist, must be not processed yet, and must
821
+ // belong to the sweeping wallet.
822
+ require(sweepRequest.createdAt != 0, "Sweep request does not exist");
823
+ require(sweepRequest.sweptAt == 0, "Sweep request already processed");
824
+ // We must check if the wallet extracted from the moved funds sweep
825
+ // transaction output is truly the owner of the sweep request connected
826
+ // with the swept UTXO. This is needed to prevent a case when a wallet
827
+ // handles its own sweep request but locks the funds on another
828
+ // wallet public key hash.
829
+ require(
830
+ sweepRequest.walletPubKeyHash == walletPubKeyHash,
831
+ "Sweep request belongs to another wallet"
832
+ );
833
+ // If the validation passed, the sweep request must be marked as
834
+ // processed and its value should be counted into the total inputs
835
+ // value sum.
836
+ /* solhint-disable-next-line not-rely-on-time */
837
+ sweepRequest.sweptAt = uint32(block.timestamp);
838
+ inputsTotalValue += sweepRequest.value;
839
+
840
+ // TODO: Decrease the sweep request count for the sweeping wallet.
841
+ // That will be handled in the PR that will block moving
842
+ // funds commitments for wallets with pending sweep requests.
843
+
844
+ // If the main UTXO for the sweeping wallet exists, it must be processed.
845
+ if (mainUtxo.txHash != bytes32(0)) {
846
+ // The second input is supposed to point to that sweeping wallet
847
+ // main UTXO. We need to parse that input.
848
+ (
849
+ bytes32 secondInputOutpointTxHash,
850
+ uint32 secondInputOutpointIndex,
851
+
852
+ ) = parseMovedFundsSweepTxInputAt(
853
+ sweepTxInputVector,
854
+ inputStartingIndex + firstInputLength
855
+ );
856
+ // Make sure the second input refers to the sweeping wallet main UTXO.
857
+ require(
858
+ mainUtxo.txHash == secondInputOutpointTxHash &&
859
+ mainUtxo.txOutputIndex == secondInputOutpointIndex,
860
+ "Second input must point to the wallet's main UTXO"
861
+ );
862
+
863
+ // If the validation passed, count the main UTXO value into the
864
+ // total inputs value sum.
865
+ inputsTotalValue += mainUtxo.txOutputValue;
866
+
867
+ // Main UTXO used as an input, mark it as spent. This is needed
868
+ // to defend against fraud challenges referring to this main UTXO.
869
+ self.spentMainUTXOs[
870
+ uint256(
871
+ keccak256(
872
+ abi.encodePacked(
873
+ secondInputOutpointTxHash,
874
+ secondInputOutpointIndex
875
+ )
876
+ )
877
+ )
878
+ ] = true;
879
+ }
880
+
881
+ return inputsTotalValue;
882
+ }
883
+
884
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
885
+ /// @param inputVector Bitcoin transaction input vector
886
+ /// @param inputStartingIndex Index the given input starts at
887
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
888
+ /// pointed in the given input's outpoint.
889
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
890
+ /// which is pointed in the given input's outpoint.
891
+ /// @return inputLength Byte length of the given input.
892
+ /// @dev This function assumes vector's structure is valid so it must be
893
+ /// validated using e.g. `BTCUtils.validateVin` function before it
894
+ /// is passed here.
895
+ function parseMovedFundsSweepTxInputAt(
896
+ bytes memory inputVector,
897
+ uint256 inputStartingIndex
898
+ )
899
+ internal
900
+ pure
901
+ returns (
902
+ bytes32 outpointTxHash,
903
+ uint32 outpointIndex,
904
+ uint256 inputLength
905
+ )
906
+ {
907
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
908
+
909
+ outpointIndex = BTCUtils.reverseUint32(
910
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
911
+ );
912
+
913
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
914
+
915
+ return (outpointTxHash, outpointIndex, inputLength);
916
+ }
524
917
  }
@@ -19,7 +19,10 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
19
19
  deployments.getNetworkName() === "hardhat" ? 1 : 6
20
20
 
21
21
  const Deposit = await deploy("Deposit", { from: deployer, log: true })
22
- const Sweep = await deploy("Sweep", { from: deployer, log: true })
22
+ const DepositSweep = await deploy("DepositSweep", {
23
+ from: deployer,
24
+ log: true,
25
+ })
23
26
  const Redemption = await deploy("Redemption", { from: deployer, log: true })
24
27
  const Wallets = await deploy("Wallets", { from: deployer, log: true })
25
28
  const Fraud = await deploy("Fraud", { from: deployer, log: true })
@@ -41,7 +44,7 @@ const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
41
44
  ],
42
45
  libraries: {
43
46
  Deposit: Deposit.address,
44
- Sweep: Sweep.address,
47
+ DepositSweep: DepositSweep.address,
45
48
  Redemption: Redemption.address,
46
49
  Wallets: Wallets.address,
47
50
  Fraud: Fraud.address,