@keep-network/tbtc-v2 0.1.1-dev.34 → 0.1.1-dev.37

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 (36) hide show
  1. package/artifacts/TBTC.json +3 -3
  2. package/artifacts/TBTCToken.json +3 -3
  3. package/artifacts/VendingMachine.json +10 -10
  4. package/artifacts/solcInputs/{a67a2c11233ce411fb55a9f369ced323.json → e22260bedca047fea8676977de0ef137.json} +15 -6
  5. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  6. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  7. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  8. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  9. package/build/contracts/bridge/Bridge.sol/Bridge.json +196 -204
  10. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  11. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +2 -2
  12. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  13. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  14. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  15. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +1 -1
  16. package/build/contracts/bridge/Frauds.sol/Frauds.json +2 -2
  17. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  18. package/build/contracts/bridge/{Bridge.sol → IRelay.sol}/IRelay.json +1 -1
  19. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  20. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  21. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  22. package/build/contracts/bridge/Redeem.sol/Redeem.json +126 -0
  23. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
  24. package/build/contracts/bridge/Sweep.sol/Sweep.json +48 -0
  25. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  26. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  27. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  28. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  29. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  30. package/contracts/bridge/Bridge.sol +165 -1130
  31. package/contracts/bridge/BridgeState.sol +110 -0
  32. package/contracts/bridge/IRelay.sol +28 -0
  33. package/contracts/bridge/Redeem.sol +849 -0
  34. package/contracts/bridge/Sweep.sol +510 -0
  35. package/package.json +1 -1
  36. package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +0 -4
@@ -19,26 +19,20 @@ 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
+
22
23
  import {IWalletOwner as EcdsaWalletOwner} from "@keep-network/ecdsa/contracts/api/IWalletOwner.sol";
23
24
 
24
- import "../bank/Bank.sol";
25
+ import "./IRelay.sol";
25
26
  import "./BridgeState.sol";
27
+ import "./Deposit.sol";
28
+ import "./Sweep.sol";
29
+ import "./Redeem.sol";
26
30
  import "./BitcoinTx.sol";
27
31
  import "./EcdsaLib.sol";
28
32
  import "./Wallets.sol";
29
33
  import "./Frauds.sol";
30
34
 
31
- /// @title Interface for the Bitcoin relay
32
- /// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay
33
- /// provides the difficulty of the previous and current epoch. One
34
- /// difficulty epoch spans 2016 blocks.
35
- interface IRelay {
36
- /// @notice Returns the difficulty of the current epoch.
37
- function getCurrentEpochDifficulty() external view returns (uint256);
38
-
39
- /// @notice Returns the difficulty of the previous epoch.
40
- function getPrevEpochDifficulty() external view returns (uint256);
41
- }
35
+ import "../bank/Bank.sol";
42
36
 
43
37
  /// @title Bitcoin Bridge
44
38
  /// @notice Bridge manages BTC deposit and redemption flow and is increasing and
@@ -60,13 +54,15 @@ interface IRelay {
60
54
  /// balances in the Bank.
61
55
  /// @dev Bridge is an upgradeable component of the Bank.
62
56
  ///
63
- /// TODO: All wallets-related operations that are currently done directly
64
- /// by the Bridge can be probably delegated to the Wallets library.
65
- /// Examples of such operations are main UTXO or pending redemptions
66
- /// value updates.
57
+ // TODO: All wallets-related operations that are currently done directly
58
+ // by the Bridge can be probably delegated to the Wallets library.
59
+ // Examples of such operations are main UTXO or pending redemptions
60
+ // value updates.
67
61
  contract Bridge is Ownable, EcdsaWalletOwner {
68
62
  using BridgeState for BridgeState.Storage;
69
63
  using Deposit for BridgeState.Storage;
64
+ using Sweep for BridgeState.Storage;
65
+ using Redeem for BridgeState.Storage;
70
66
  using Frauds for Frauds.Data;
71
67
  using Wallets for Wallets.Data;
72
68
 
@@ -74,126 +70,8 @@ contract Bridge is Ownable, EcdsaWalletOwner {
74
70
  using BTCUtils for uint256;
75
71
  using BytesLib for bytes;
76
72
 
77
- /// @notice Represents an outcome of the sweep Bitcoin transaction
78
- /// inputs processing.
79
- struct SweepTxInputsInfo {
80
- // Sum of all inputs values i.e. all deposits and main UTXO value,
81
- // if present.
82
- uint256 inputsTotalValue;
83
- // Addresses of depositors who performed processed deposits. Ordered in
84
- // the same order as deposits inputs in the input vector. Size of this
85
- // array is either equal to the number of inputs (main UTXO doesn't
86
- // exist) or less by one (main UTXO exists and is pointed by one of
87
- // the inputs).
88
- address[] depositors;
89
- // Amounts of deposits corresponding to processed deposits. Ordered in
90
- // the same order as deposits inputs in the input vector. Size of this
91
- // array is either equal to the number of inputs (main UTXO doesn't
92
- // exist) or less by one (main UTXO exists and is pointed by one of
93
- // the inputs).
94
- uint256[] depositedAmounts;
95
- // Values of the treasury fee corresponding to processed deposits.
96
- // Ordered in the same order as deposits inputs in the input vector.
97
- // Size of this array is either equal to the number of inputs (main
98
- // UTXO doesn't exist) or less by one (main UTXO exists and is pointed
99
- // by one of the inputs).
100
- uint256[] treasuryFees;
101
- }
102
-
103
- /// @notice Represents a redemption request.
104
- struct RedemptionRequest {
105
- // ETH address of the redeemer who created the request.
106
- address redeemer;
107
- // Requested TBTC amount in satoshi.
108
- uint64 requestedAmount;
109
- // Treasury TBTC fee in satoshi at the moment of request creation.
110
- uint64 treasuryFee;
111
- // Transaction maximum BTC fee in satoshi at the moment of request
112
- // creation.
113
- uint64 txMaxFee;
114
- // UNIX timestamp the request was created at.
115
- uint32 requestedAt;
116
- }
117
-
118
- /// @notice Represents an outcome of the redemption Bitcoin transaction
119
- /// outputs processing.
120
- struct RedemptionTxOutputsInfo {
121
- // Total TBTC value in satoshi that should be burned by the Bridge.
122
- // It includes the total amount of all BTC redeemed in the transaction
123
- // and the fee paid to BTC miners for the redemption transaction.
124
- uint64 totalBurnableValue;
125
- // Total TBTC value in satoshi that should be transferred to
126
- // the treasury. It is a sum of all treasury fees paid by all
127
- // redeemers included in the redemption transaction.
128
- uint64 totalTreasuryFee;
129
- // Index of the change output. The change output becomes
130
- // the new main wallet's UTXO.
131
- uint32 changeIndex;
132
- // Value in satoshi of the change output.
133
- uint64 changeValue;
134
- }
135
-
136
- /// @notice The number of confirmations on the Bitcoin chain required to
137
- /// successfully evaluate an SPV proof.
138
- uint256 public txProofDifficultyFactor;
139
-
140
- /// TODO: Revisit whether it should be governable or not.
141
- /// @notice Address of the Bank this Bridge belongs to.
142
- Bank public bank;
143
-
144
- /// TODO: Make it governable.
145
- /// @notice Handle to the Bitcoin relay.
146
- IRelay public relay;
147
-
148
- /// TODO: Revisit whether it should be governable or not.
149
- /// @notice Address where the redemptions treasury fees will be sent to.
150
- /// Treasury takes part in the operators rewarding process.
151
- address public treasury;
152
-
153
73
  BridgeState.Storage internal self;
154
74
 
155
- /// TODO: Make it governable.
156
- /// @notice Maximum amount of BTC transaction fee that can be incurred by
157
- /// each swept deposit being part of the given sweep
158
- /// transaction. If the maximum BTC transaction fee is exceeded,
159
- /// such transaction is considered a fraud.
160
- /// @dev This is a per-deposit input max fee for the sweep transaction.
161
- uint64 public depositTxMaxFee;
162
-
163
- /// TODO: Make it governable.
164
- /// @notice The minimal amount that can be requested for redemption.
165
- /// Value of this parameter must take into account the value of
166
- /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
167
- /// parameters in order to make requests that can incur the
168
- /// treasury and transaction fee and still satisfy the redeemer.
169
- uint64 public redemptionDustThreshold;
170
-
171
- /// TODO: Make it governable.
172
- /// @notice Divisor used to compute the treasury fee taken from each
173
- /// redemption request and transferred to the treasury upon
174
- /// successful request finalization. That fee is computed as follows:
175
- /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
176
- /// For example, if the treasury fee needs to be 2% of each
177
- /// redemption request, the `redemptionTreasuryFeeDivisor` should
178
- /// be set to `50` because `1/50 = 0.02 = 2%`.
179
- uint64 public redemptionTreasuryFeeDivisor;
180
-
181
- /// TODO: Make it governable.
182
- /// @notice Maximum amount of BTC transaction fee that can be incurred by
183
- /// each redemption request being part of the given redemption
184
- /// transaction. If the maximum BTC transaction fee is exceeded, such
185
- /// transaction is considered a fraud.
186
- /// @dev This is a per-redemption output max fee for the redemption transaction.
187
- uint64 public redemptionTxMaxFee;
188
-
189
- /// TODO: Make it governable.
190
- /// @notice Time after which the redemption request can be reported as
191
- /// timed out. It is counted from the moment when the redemption
192
- /// request was created via `requestRedemption` call. Reported
193
- /// timed out requests are cancelled and locked TBTC is returned
194
- /// to the redeemer in full amount.
195
- uint256 public redemptionTimeout;
196
-
197
75
  /// TODO: Make it governable.
198
76
  /// @notice Maximum amount of the total BTC transaction fee that is
199
77
  /// acceptable in a single moving funds transaction.
@@ -203,45 +81,6 @@ contract Bridge is Ownable, EcdsaWalletOwner {
203
81
  /// for the entire transaction.
204
82
  uint64 public movingFundsTxMaxTotalFee;
205
83
 
206
- /// @notice Collection of main UTXOs that are honestly spent indexed by
207
- /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash
208
- /// is bytes32 (ordered as in Bitcoin internally) and
209
- /// fundingOutputIndex an uint32. A main UTXO is considered honestly
210
- /// spent if it was used as an input of a transaction that have been
211
- /// proven in the Bridge.
212
- mapping(uint256 => bool) public spentMainUTXOs;
213
-
214
- /// @notice Collection of all pending redemption requests indexed by
215
- /// redemption key built as
216
- /// keccak256(walletPubKeyHash | redeemerOutputScript). The
217
- /// walletPubKeyHash is the 20-byte wallet's public key hash
218
- /// (computed using Bitcoin HASH160 over the compressed ECDSA
219
- /// public key) and redeemerOutputScript is a Bitcoin script
220
- /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
221
- /// redeemed BTC as requested by the redeemer. Requests are added
222
- /// to this mapping by the `requestRedemption` method (duplicates
223
- /// not allowed) and are removed by one of the following methods:
224
- /// - `submitRedemptionProof` in case the request was handled
225
- /// successfully
226
- /// - `notifyRedemptionTimeout` in case the request was reported
227
- /// to be timed out
228
- mapping(uint256 => RedemptionRequest) public pendingRedemptions;
229
-
230
- /// @notice Collection of all timed out redemptions requests indexed by
231
- /// redemption key built as
232
- /// keccak256(walletPubKeyHash | redeemerOutputScript). The
233
- /// walletPubKeyHash is the 20-byte wallet's public key hash
234
- /// (computed using Bitcoin HASH160 over the compressed ECDSA
235
- /// public key) and redeemerOutputScript is the Bitcoin script
236
- /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
237
- /// out request. Timed out requests are stored in this mapping to
238
- /// avoid slashing the wallets multiple times for the same timeout.
239
- /// Only one method can add to this mapping:
240
- /// - `notifyRedemptionTimeout` which puts the redemption key
241
- /// to this mapping basing on a timed out request stored
242
- /// previously in `pendingRedemptions` mapping.
243
- mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
244
-
245
84
  /// @notice Contains parameters related to frauds and the collection of all
246
85
  /// submitted fraud challenges.
247
86
  Frauds.Data internal frauds;
@@ -357,24 +196,24 @@ contract Bridge is Ownable, EcdsaWalletOwner {
357
196
  uint256 _txProofDifficultyFactor
358
197
  ) {
359
198
  require(_bank != address(0), "Bank address cannot be zero");
360
- bank = Bank(_bank);
199
+ self.bank = Bank(_bank);
361
200
 
362
201
  require(_relay != address(0), "Relay address cannot be zero");
363
- relay = IRelay(_relay);
202
+ self.relay = IRelay(_relay);
364
203
 
365
204
  require(_treasury != address(0), "Treasury address cannot be zero");
366
- treasury = _treasury;
205
+ self.treasury = _treasury;
367
206
 
368
- txProofDifficultyFactor = _txProofDifficultyFactor;
207
+ self.txProofDifficultyFactor = _txProofDifficultyFactor;
369
208
 
370
209
  // TODO: Revisit initial values.
371
210
  self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
372
- depositTxMaxFee = 10000; // 10000 satoshi
211
+ self.depositTxMaxFee = 10000; // 10000 satoshi
373
212
  self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
374
- redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
375
- redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
376
- redemptionTxMaxFee = 10000; // 10000 satoshi
377
- redemptionTimeout = 172800; // 48 hours
213
+ self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
214
+ self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
215
+ self.redemptionTxMaxFee = 10000; // 10000 satoshi
216
+ self.redemptionTimeout = 172800; // 48 hours
378
217
  movingFundsTxMaxTotalFee = 10000; // 10000 satoshi
379
218
 
380
219
  // TODO: Revisit initial values.
@@ -549,22 +388,6 @@ contract Bridge is Ownable, EcdsaWalletOwner {
549
388
  return wallets.activeWalletPubKeyHash;
550
389
  }
551
390
 
552
- /// @notice Determines the current Bitcoin SPV proof difficulty context.
553
- /// @return proofDifficulty Bitcoin proof difficulty context.
554
- function proofDifficultyContext()
555
- internal
556
- view
557
- returns (BitcoinTx.ProofDifficulty memory proofDifficulty)
558
- {
559
- proofDifficulty.currentEpochDifficulty = relay
560
- .getCurrentEpochDifficulty();
561
- proofDifficulty.previousEpochDifficulty = relay
562
- .getPrevEpochDifficulty();
563
- proofDifficulty.difficultyFactor = txProofDifficultyFactor;
564
-
565
- return proofDifficulty;
566
- }
567
-
568
391
  /// @notice Used by the depositor to reveal information about their P2(W)SH
569
392
  /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain
570
393
  /// wallet listens for revealed deposit events and may decide to
@@ -647,410 +470,7 @@ contract Bridge is Ownable, EcdsaWalletOwner {
647
470
  BitcoinTx.Proof calldata sweepProof,
648
471
  BitcoinTx.UTXO calldata mainUtxo
649
472
  ) external {
650
- // TODO: Fail early if the function call gets frontrunned. See discussion:
651
- // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
652
-
653
- // The actual transaction proof is performed here. After that point, we
654
- // can assume the transaction happened on Bitcoin chain and has
655
- // a sufficient number of confirmations as determined by
656
- // `txProofDifficultyFactor` constant.
657
- bytes32 sweepTxHash = BitcoinTx.validateProof(
658
- sweepTx,
659
- sweepProof,
660
- proofDifficultyContext()
661
- );
662
-
663
- // Process sweep transaction output and extract its target wallet
664
- // public key hash and value.
665
- (
666
- bytes20 walletPubKeyHash,
667
- uint64 sweepTxOutputValue
668
- ) = processSweepTxOutput(sweepTx.outputVector);
669
-
670
- (
671
- Wallets.Wallet storage wallet,
672
- BitcoinTx.UTXO memory resolvedMainUtxo
673
- ) = resolveSweepingWallet(walletPubKeyHash, mainUtxo);
674
-
675
- // Process sweep transaction inputs and extract all information needed
676
- // to perform deposit bookkeeping.
677
- SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(
678
- sweepTx.inputVector,
679
- resolvedMainUtxo
680
- );
681
-
682
- // Helper variable that will hold the sum of treasury fees paid by
683
- // all deposits.
684
- uint256 totalTreasuryFee = 0;
685
-
686
- // Determine the transaction fee that should be incurred by each deposit
687
- // and the indivisible remainder that should be additionally incurred
688
- // by the last deposit.
689
- (
690
- uint256 depositTxFee,
691
- uint256 depositTxFeeRemainder
692
- ) = sweepTxFeeDistribution(
693
- inputsInfo.inputsTotalValue,
694
- sweepTxOutputValue,
695
- inputsInfo.depositedAmounts.length
696
- );
697
-
698
- // Make sure the highest value of the deposit transaction fee does not
699
- // exceed the maximum value limited by the governable parameter.
700
- require(
701
- depositTxFee + depositTxFeeRemainder <= depositTxMaxFee,
702
- "Transaction fee is too high"
703
- );
704
-
705
- // Reduce each deposit amount by treasury fee and transaction fee.
706
- for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {
707
- // The last deposit should incur the deposit transaction fee
708
- // remainder.
709
- uint256 depositTxFeeIncurred = i ==
710
- inputsInfo.depositedAmounts.length - 1
711
- ? depositTxFee + depositTxFeeRemainder
712
- : depositTxFee;
713
-
714
- // There is no need to check whether
715
- // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`
716
- // since the `depositDustThreshold` should force that condition
717
- // to be always true.
718
- inputsInfo.depositedAmounts[i] =
719
- inputsInfo.depositedAmounts[i] -
720
- inputsInfo.treasuryFees[i] -
721
- depositTxFeeIncurred;
722
- totalTreasuryFee += inputsInfo.treasuryFees[i];
723
- }
724
-
725
- // Record this sweep data and assign them to the wallet public key hash
726
- // as new main UTXO. Transaction output index is always 0 as sweep
727
- // transaction always contains only one output.
728
- wallet.mainUtxoHash = keccak256(
729
- abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
730
- );
731
-
732
- emit DepositsSwept(walletPubKeyHash, sweepTxHash);
733
-
734
- // Update depositors balances in the Bank.
735
- bank.increaseBalances(
736
- inputsInfo.depositors,
737
- inputsInfo.depositedAmounts
738
- );
739
- // Pass the treasury fee to the treasury address.
740
- bank.increaseBalance(treasury, totalTreasuryFee);
741
-
742
- // TODO: Handle deposits having `vault` set.
743
- }
744
-
745
- /// @notice Resolves sweeping wallet based on the provided wallet public key
746
- /// hash. Validates the wallet state and current main UTXO, as
747
- /// currently known on the Ethereum chain.
748
- /// @param walletPubKeyHash public key hash of the wallet proving the sweep
749
- /// Bitcoin transaction.
750
- /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
751
- /// the Ethereum chain. If no main UTXO exists for the given wallet,
752
- /// this parameter is ignored
753
- /// @dev Requirements:
754
- /// - Sweeping wallet must be either in Live or MovingFunds state.
755
- /// - If the main UTXO of the sweeping wallet exists in the storage,
756
- /// the passed `mainUTXO` parameter must be equal to the stored one.
757
- function resolveSweepingWallet(
758
- bytes20 walletPubKeyHash,
759
- BitcoinTx.UTXO calldata mainUtxo
760
- )
761
- internal
762
- returns (
763
- Wallets.Wallet storage wallet,
764
- BitcoinTx.UTXO memory resolvedMainUtxo
765
- )
766
- {
767
- wallet = wallets.registeredWallets[walletPubKeyHash];
768
-
769
- Wallets.WalletState walletState = wallet.state;
770
- require(
771
- walletState == Wallets.WalletState.Live ||
772
- walletState == Wallets.WalletState.MovingFunds,
773
- "Wallet must be in Live or MovingFunds state"
774
- );
775
-
776
- // Check if the main UTXO for given wallet exists. If so, validate
777
- // passed main UTXO data against the stored hash and use them for
778
- // further processing. If no main UTXO exists, use empty data.
779
- resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);
780
- bytes32 mainUtxoHash = wallet.mainUtxoHash;
781
- if (mainUtxoHash != bytes32(0)) {
782
- require(
783
- keccak256(
784
- abi.encodePacked(
785
- mainUtxo.txHash,
786
- mainUtxo.txOutputIndex,
787
- mainUtxo.txOutputValue
788
- )
789
- ) == mainUtxoHash,
790
- "Invalid main UTXO data"
791
- );
792
- resolvedMainUtxo = mainUtxo;
793
- }
794
- }
795
-
796
- /// @notice Processes the Bitcoin sweep transaction output vector by
797
- /// extracting the single output and using it to gain additional
798
- /// information required for further processing (e.g. value and
799
- /// wallet public key hash).
800
- /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.
801
- /// This function assumes vector's structure is valid so it must be
802
- /// validated using e.g. `BTCUtils.validateVout` function before
803
- /// it is passed here
804
- /// @return walletPubKeyHash 20-byte wallet public key hash.
805
- /// @return value 8-byte sweep transaction output value.
806
- function processSweepTxOutput(bytes memory sweepTxOutputVector)
807
- internal
808
- pure
809
- returns (bytes20 walletPubKeyHash, uint64 value)
810
- {
811
- // To determine the total number of sweep transaction outputs, we need to
812
- // parse the compactSize uint (VarInt) the output vector is prepended by.
813
- // That compactSize uint encodes the number of vector elements using the
814
- // format presented in:
815
- // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
816
- // We don't need asserting the compactSize uint is parseable since it
817
- // was already checked during `validateVout` validation.
818
- // See `BitcoinTx.outputVector` docs for more details.
819
- (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
820
- require(
821
- outputsCount == 1,
822
- "Sweep transaction must have a single output"
823
- );
824
-
825
- bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
826
- value = output.extractValue();
827
- bytes memory walletPubKeyHashBytes = output.extractHash();
828
- // The sweep transaction output should always be P2PKH or P2WPKH.
829
- // In both cases, the wallet public key hash should be 20 bytes length.
830
- require(
831
- walletPubKeyHashBytes.length == 20,
832
- "Wallet public key hash should have 20 bytes"
833
- );
834
- /* solhint-disable-next-line no-inline-assembly */
835
- assembly {
836
- walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))
837
- }
838
-
839
- return (walletPubKeyHash, value);
840
- }
841
-
842
- /// @notice Processes the Bitcoin sweep transaction input vector. It
843
- /// extracts each input and tries to obtain associated deposit or
844
- /// main UTXO data, depending on the input type. Reverts
845
- /// if one of the inputs cannot be recognized as a pointer to a
846
- /// revealed deposit or expected main UTXO.
847
- /// This function also marks each processed deposit as swept.
848
- /// @param sweepTxInputVector Bitcoin sweep transaction input vector.
849
- /// This function assumes vector's structure is valid so it must be
850
- /// validated using e.g. `BTCUtils.validateVin` function before
851
- /// it is passed here
852
- /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO
853
- /// exists for the given the wallet, this parameter's fields should
854
- /// be zeroed to bypass the main UTXO validation
855
- /// @return info Outcomes of the processing.
856
- function processSweepTxInputs(
857
- bytes memory sweepTxInputVector,
858
- BitcoinTx.UTXO memory mainUtxo
859
- ) internal returns (SweepTxInputsInfo memory info) {
860
- // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO
861
- // for the given wallet doesn't exist and it is not expected to be
862
- // included in the sweep transaction input vector.
863
- bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);
864
- bool mainUtxoFound = false;
865
-
866
- // Determining the total number of sweep transaction inputs in the same
867
- // way as for number of outputs. See `BitcoinTx.inputVector` docs for
868
- // more details.
869
- (
870
- uint256 inputsCompactSizeUintLength,
871
- uint256 inputsCount
872
- ) = sweepTxInputVector.parseVarInt();
873
-
874
- // To determine the first input starting index, we must jump over
875
- // the compactSize uint which prepends the input vector. One byte
876
- // must be added because `BtcUtils.parseVarInt` does not include
877
- // compactSize uint tag in the returned length.
878
- //
879
- // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
880
- // returns `0`, so we jump over one byte of compactSize uint.
881
- //
882
- // For >= 253 && <= 0xffff there is `0xfd` tag,
883
- // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
884
- // tag byte included) so we need to jump over 1+2 bytes of
885
- // compactSize uint.
886
- //
887
- // Please refer `BTCUtils` library and compactSize uint
888
- // docs in `BitcoinTx` library for more details.
889
- uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
890
-
891
- // Determine the swept deposits count. If main UTXO is NOT expected,
892
- // all inputs should be deposits. If main UTXO is expected, one input
893
- // should point to that main UTXO.
894
- info.depositors = new address[](
895
- !mainUtxoExpected ? inputsCount : inputsCount - 1
896
- );
897
- info.depositedAmounts = new uint256[](info.depositors.length);
898
- info.treasuryFees = new uint256[](info.depositors.length);
899
-
900
- // Initialize helper variables.
901
- uint256 processedDepositsCount = 0;
902
-
903
- // Inputs processing loop.
904
- for (uint256 i = 0; i < inputsCount; i++) {
905
- (
906
- bytes32 outpointTxHash,
907
- uint32 outpointIndex,
908
- uint256 inputLength
909
- ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
910
-
911
- Deposit.Request storage deposit = self.deposits[
912
- uint256(
913
- keccak256(abi.encodePacked(outpointTxHash, outpointIndex))
914
- )
915
- ];
916
-
917
- if (deposit.revealedAt != 0) {
918
- // If we entered here, that means the input was identified as
919
- // a revealed deposit.
920
- require(deposit.sweptAt == 0, "Deposit already swept");
921
-
922
- if (processedDepositsCount == info.depositors.length) {
923
- // If this condition is true, that means a deposit input
924
- // took place of an expected main UTXO input.
925
- // In other words, there is no expected main UTXO
926
- // input and all inputs come from valid, revealed deposits.
927
- revert(
928
- "Expected main UTXO not present in sweep transaction inputs"
929
- );
930
- }
931
-
932
- /* solhint-disable-next-line not-rely-on-time */
933
- deposit.sweptAt = uint32(block.timestamp);
934
-
935
- info.depositors[processedDepositsCount] = deposit.depositor;
936
- info.depositedAmounts[processedDepositsCount] = deposit.amount;
937
- info.inputsTotalValue += info.depositedAmounts[
938
- processedDepositsCount
939
- ];
940
- info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;
941
-
942
- processedDepositsCount++;
943
- } else if (
944
- mainUtxoExpected != mainUtxoFound &&
945
- mainUtxo.txHash == outpointTxHash
946
- ) {
947
- // If we entered here, that means the input was identified as
948
- // the expected main UTXO.
949
- info.inputsTotalValue += mainUtxo.txOutputValue;
950
- mainUtxoFound = true;
951
-
952
- // Main UTXO used as an input, mark it as spent.
953
- spentMainUTXOs[
954
- uint256(
955
- keccak256(
956
- abi.encodePacked(outpointTxHash, outpointIndex)
957
- )
958
- )
959
- ] = true;
960
- } else {
961
- revert("Unknown input type");
962
- }
963
-
964
- // Make the `inputStartingIndex` pointing to the next input by
965
- // increasing it by current input's length.
966
- inputStartingIndex += inputLength;
967
- }
968
-
969
- // Construction of the input processing loop guarantees that:
970
- // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`
971
- // is always true at this point. We just use the first variable
972
- // to assert the total count of swept deposit is bigger than zero.
973
- require(
974
- processedDepositsCount > 0,
975
- "Sweep transaction must process at least one deposit"
976
- );
977
-
978
- // Assert the main UTXO was used as one of current sweep's inputs if
979
- // it was actually expected.
980
- require(
981
- mainUtxoExpected == mainUtxoFound,
982
- "Expected main UTXO not present in sweep transaction inputs"
983
- );
984
-
985
- return info;
986
- }
987
-
988
- /// @notice Parses a Bitcoin transaction input starting at the given index.
989
- /// @param inputVector Bitcoin transaction input vector
990
- /// @param inputStartingIndex Index the given input starts at
991
- /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
992
- /// pointed in the given input's outpoint.
993
- /// @return outpointIndex 4-byte index of the Bitcoin transaction output
994
- /// which is pointed in the given input's outpoint.
995
- /// @return inputLength Byte length of the given input.
996
- /// @dev This function assumes vector's structure is valid so it must be
997
- /// validated using e.g. `BTCUtils.validateVin` function before it
998
- /// is passed here.
999
- function parseTxInputAt(
1000
- bytes memory inputVector,
1001
- uint256 inputStartingIndex
1002
- )
1003
- internal
1004
- pure
1005
- returns (
1006
- bytes32 outpointTxHash,
1007
- uint32 outpointIndex,
1008
- uint256 inputLength
1009
- )
1010
- {
1011
- outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
1012
-
1013
- outpointIndex = BTCUtils.reverseUint32(
1014
- uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
1015
- );
1016
-
1017
- inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
1018
-
1019
- return (outpointTxHash, outpointIndex, inputLength);
1020
- }
1021
-
1022
- /// @notice Determines the distribution of the sweep transaction fee
1023
- /// over swept deposits.
1024
- /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.
1025
- /// @param sweepTxOutputValue Value of the sweep transaction output.
1026
- /// @param depositsCount Count of the deposits swept by the sweep transaction.
1027
- /// @return depositTxFee Transaction fee per deposit determined by evenly
1028
- /// spreading the divisible part of the sweep transaction fee
1029
- /// over all deposits.
1030
- /// @return depositTxFeeRemainder The indivisible part of the sweep
1031
- /// transaction fee than cannot be distributed over all deposits.
1032
- /// @dev It is up to the caller to decide how the remainder should be
1033
- /// counted in. This function only computes its value.
1034
- function sweepTxFeeDistribution(
1035
- uint256 sweepTxInputsTotalValue,
1036
- uint256 sweepTxOutputValue,
1037
- uint256 depositsCount
1038
- )
1039
- internal
1040
- pure
1041
- returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)
1042
- {
1043
- // The sweep transaction fee is just the difference between inputs
1044
- // amounts sum and the output amount.
1045
- uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;
1046
- // Compute the indivisible remainder that remains after dividing the
1047
- // sweep transaction fee over all deposits evenly.
1048
- depositTxFeeRemainder = sweepTxFee % depositsCount;
1049
- // Compute the transaction fee per deposit by dividing the sweep
1050
- // transaction fee (reduced by the remainder) by the number of deposits.
1051
- depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;
1052
-
1053
- return (depositTxFee, depositTxFeeRemainder);
473
+ self.submitSweepProof(wallets, sweepTx, sweepProof, mainUtxo);
1054
474
  }
1055
475
 
1056
476
  /// @notice Submits a fraud challenge indicating that a UTXO being under
@@ -1155,11 +575,11 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1155
575
 
1156
576
  // Check that the UTXO key identifies a correctly spent UTXO.
1157
577
  require(
1158
- self.deposits[utxoKey].sweptAt > 0 || spentMainUTXOs[utxoKey],
578
+ self.deposits[utxoKey].sweptAt > 0 || self.spentMainUTXOs[utxoKey],
1159
579
  "Spent UTXO not found among correctly spent UTXOs"
1160
580
  );
1161
581
 
1162
- frauds.defeatChallenge(walletPublicKey, preimage, treasury);
582
+ frauds.defeatChallenge(walletPublicKey, preimage, self.treasury);
1163
583
  }
1164
584
 
1165
585
  /// @notice Notifies about defeat timeout for the given fraud challenge.
@@ -1265,123 +685,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1265
685
  bytes calldata redeemerOutputScript,
1266
686
  uint64 amount
1267
687
  ) external {
1268
- Wallets.Wallet storage wallet = wallets.registeredWallets[
1269
- walletPubKeyHash
1270
- ];
1271
-
1272
- require(
1273
- wallet.state == Wallets.WalletState.Live,
1274
- "Wallet must be in Live state"
1275
- );
1276
-
1277
- bytes32 mainUtxoHash = wallet.mainUtxoHash;
1278
- require(
1279
- mainUtxoHash != bytes32(0),
1280
- "No main UTXO for the given wallet"
1281
- );
1282
- require(
1283
- keccak256(
1284
- abi.encodePacked(
1285
- mainUtxo.txHash,
1286
- mainUtxo.txOutputIndex,
1287
- mainUtxo.txOutputValue
1288
- )
1289
- ) == mainUtxoHash,
1290
- "Invalid main UTXO data"
1291
- );
1292
-
1293
- // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1294
- // if it is the oldest one who can handle the request. This will
1295
- // be suggested by the dApp but may not be respected by users who
1296
- // interact directly with the contract. Do we need to enforce it
1297
- // here? One option is not to enforce it, to save on gas, but if
1298
- // we see this rule is not respected, upgrade Bridge contract to
1299
- // require it.
1300
-
1301
- // Validate if redeemer output script is a correct standard type
1302
- // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1303
- // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1304
- // a function extracts the payload properly only from standard outputs
1305
- // so if it succeeds, we have a guarantee the redeemer output script
1306
- // is proper. Worth to note `extractHash` ignores the value at all
1307
- // so this is why we can use 0 safely. This way of validation is the
1308
- // same as in tBTC v1.
1309
- bytes memory redeemerOutputScriptPayload = abi
1310
- .encodePacked(bytes8(0), redeemerOutputScript)
1311
- .extractHash();
1312
- require(
1313
- redeemerOutputScriptPayload.length > 0,
1314
- "Redeemer output script must be a standard type"
1315
- );
1316
- // Check if the redeemer output script payload does not point to the
1317
- // wallet public key hash.
1318
- require(
1319
- keccak256(abi.encodePacked(walletPubKeyHash)) !=
1320
- keccak256(redeemerOutputScriptPayload),
1321
- "Redeemer output script must not point to the wallet PKH"
1322
- );
1323
-
1324
- require(
1325
- amount >= redemptionDustThreshold,
1326
- "Redemption amount too small"
1327
- );
1328
-
1329
- // The redemption key is built on top of the wallet public key hash
1330
- // and redeemer output script pair. That means there can be only one
1331
- // request asking for redemption from the given wallet to the given
1332
- // BTC script at the same time.
1333
- uint256 redemptionKey = uint256(
1334
- keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1335
- );
1336
-
1337
- // Check if given redemption key is not used by a pending redemption.
1338
- // There is no need to check for existence in `timedOutRedemptions`
1339
- // since the wallet's state is changed to other than Live after
1340
- // first time out is reported so making new requests is not possible.
1341
- // slither-disable-next-line incorrect-equality
1342
- require(
1343
- pendingRedemptions[redemptionKey].requestedAt == 0,
1344
- "There is a pending redemption request from this wallet to the same address"
1345
- );
1346
-
1347
- // No need to check whether `amount - treasuryFee - txMaxFee > 0`
1348
- // since the `redemptionDustThreshold` should force that condition
1349
- // to be always true.
1350
- uint64 treasuryFee = redemptionTreasuryFeeDivisor > 0
1351
- ? amount / redemptionTreasuryFeeDivisor
1352
- : 0;
1353
- uint64 txMaxFee = redemptionTxMaxFee;
1354
-
1355
- // The main wallet UTXO's value doesn't include all pending redemptions.
1356
- // To determine if the requested redemption can be performed by the
1357
- // wallet we need to subtract the total value of all pending redemptions
1358
- // from that wallet's main UTXO value. Given that the treasury fee is
1359
- // not redeemed from the wallet, we are subtracting it.
1360
- wallet.pendingRedemptionsValue += amount - treasuryFee;
1361
- require(
1362
- mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
1363
- "Insufficient wallet funds"
1364
- );
1365
-
1366
- pendingRedemptions[redemptionKey] = RedemptionRequest(
1367
- msg.sender,
1368
- amount,
1369
- treasuryFee,
1370
- txMaxFee,
1371
- /* solhint-disable-next-line not-rely-on-time */
1372
- uint32(block.timestamp)
1373
- );
1374
-
1375
- emit RedemptionRequested(
688
+ self.requestRedemption(
689
+ wallets,
1376
690
  walletPubKeyHash,
691
+ mainUtxo,
1377
692
  redeemerOutputScript,
1378
- msg.sender,
1379
- amount,
1380
- treasuryFee,
1381
- txMaxFee
693
+ amount
1382
694
  );
1383
-
1384
- bank.transferBalanceFrom(msg.sender, address(this), amount);
1385
695
  }
1386
696
 
1387
697
  /// @notice Used by the wallet to prove the BTC redemption transaction
@@ -1434,370 +744,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1434
744
  BitcoinTx.UTXO calldata mainUtxo,
1435
745
  bytes20 walletPubKeyHash
1436
746
  ) external {
1437
- // TODO: Just as for `submitSweepProof`, fail early if the function
1438
- // call gets frontrunned. See discussion:
1439
- // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1440
-
1441
- // The actual transaction proof is performed here. After that point, we
1442
- // can assume the transaction happened on Bitcoin chain and has
1443
- // a sufficient number of confirmations as determined by
1444
- // `txProofDifficultyFactor` constant.
1445
- bytes32 redemptionTxHash = BitcoinTx.validateProof(
747
+ self.submitRedemptionProof(
748
+ wallets,
1446
749
  redemptionTx,
1447
750
  redemptionProof,
1448
- proofDifficultyContext()
1449
- );
1450
-
1451
- // Process the redemption transaction input. Specifically, check if it
1452
- // refers to the expected wallet's main UTXO.
1453
- processWalletOutboundTxInput(
1454
- redemptionTx.inputVector,
1455
751
  mainUtxo,
1456
752
  walletPubKeyHash
1457
753
  );
1458
-
1459
- Wallets.Wallet storage wallet = wallets.registeredWallets[
1460
- walletPubKeyHash
1461
- ];
1462
-
1463
- Wallets.WalletState walletState = wallet.state;
1464
- require(
1465
- walletState == Wallets.WalletState.Live ||
1466
- walletState == Wallets.WalletState.MovingFunds,
1467
- "Wallet must be in Live or MovingFuds state"
1468
- );
1469
-
1470
- // Process redemption transaction outputs to extract some info required
1471
- // for further processing.
1472
- RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
1473
- redemptionTx.outputVector,
1474
- walletPubKeyHash
1475
- );
1476
-
1477
- if (outputsInfo.changeValue > 0) {
1478
- // If the change value is grater than zero, it means the change
1479
- // output exists and can be used as new wallet's main UTXO.
1480
- wallet.mainUtxoHash = keccak256(
1481
- abi.encodePacked(
1482
- redemptionTxHash,
1483
- outputsInfo.changeIndex,
1484
- outputsInfo.changeValue
1485
- )
1486
- );
1487
- } else {
1488
- // If the change value is zero, it means the change output doesn't
1489
- // exists and no funds left on the wallet. Delete the main UTXO
1490
- // for that wallet to represent that state in a proper way.
1491
- delete wallet.mainUtxoHash;
1492
- }
1493
-
1494
- wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
1495
-
1496
- emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1497
-
1498
- bank.decreaseBalance(outputsInfo.totalBurnableValue);
1499
- bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1500
- }
1501
-
1502
- /// @notice Checks whether an outbound Bitcoin transaction performed from
1503
- /// the given wallet has an input vector that contains a single
1504
- /// input referring to the wallet's main UTXO. Marks that main UTXO
1505
- /// as correctly spent if the validation succeeds. Reverts otherwise.
1506
- /// There are two outbound transactions from a wallet possible: a
1507
- /// redemption transaction or a moving funds to another wallet
1508
- /// transaction.
1509
- /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input
1510
- /// vector. This function assumes vector's structure is valid so it
1511
- /// must be validated using e.g. `BTCUtils.validateVin` function
1512
- /// before it is passed here
1513
- /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1514
- /// the Ethereum chain.
1515
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1516
- // HASH160 over the compressed ECDSA public key) of the wallet which
1517
- /// performed the outbound transaction.
1518
- function processWalletOutboundTxInput(
1519
- bytes memory walletOutboundTxInputVector,
1520
- BitcoinTx.UTXO calldata mainUtxo,
1521
- bytes20 walletPubKeyHash
1522
- ) internal {
1523
- // Assert that main UTXO for passed wallet exists in storage.
1524
- bytes32 mainUtxoHash = wallets
1525
- .registeredWallets[walletPubKeyHash]
1526
- .mainUtxoHash;
1527
- require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1528
-
1529
- // Assert that passed main UTXO parameter is the same as in storage and
1530
- // can be used for further processing.
1531
- require(
1532
- keccak256(
1533
- abi.encodePacked(
1534
- mainUtxo.txHash,
1535
- mainUtxo.txOutputIndex,
1536
- mainUtxo.txOutputValue
1537
- )
1538
- ) == mainUtxoHash,
1539
- "Invalid main UTXO data"
1540
- );
1541
-
1542
- // Assert that the single outbound transaction input actually
1543
- // refers to the wallet's main UTXO.
1544
- (
1545
- bytes32 outpointTxHash,
1546
- uint32 outpointIndex
1547
- ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);
1548
- require(
1549
- mainUtxo.txHash == outpointTxHash &&
1550
- mainUtxo.txOutputIndex == outpointIndex,
1551
- "Outbound transaction input must point to the wallet's main UTXO"
1552
- );
1553
-
1554
- // Main UTXO used as an input, mark it as spent.
1555
- spentMainUTXOs[
1556
- uint256(
1557
- keccak256(
1558
- abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
1559
- )
1560
- )
1561
- ] = true;
1562
- }
1563
-
1564
- /// @notice Parses the input vector of an outbound Bitcoin transaction
1565
- /// performed from the given wallet. It extracts the single input
1566
- /// then the transaction hash and output index from its outpoint.
1567
- /// There are two outbound transactions from a wallet possible: a
1568
- /// redemption transaction or a moving funds to another wallet
1569
- /// transaction.
1570
- /// @param walletOutboundTxInputVector Bitcoin outbound transaction input
1571
- /// vector. This function assumes vector's structure is valid so it
1572
- /// must be validated using e.g. `BTCUtils.validateVin` function
1573
- /// before it is passed here
1574
- /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1575
- /// pointed in the input's outpoint.
1576
- /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1577
- /// which is pointed in the input's outpoint.
1578
- function parseWalletOutboundTxInput(
1579
- bytes memory walletOutboundTxInputVector
1580
- ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {
1581
- // To determine the total number of Bitcoin transaction inputs,
1582
- // we need to parse the compactSize uint (VarInt) the input vector is
1583
- // prepended by. That compactSize uint encodes the number of vector
1584
- // elements using the format presented in:
1585
- // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1586
- // We don't need asserting the compactSize uint is parseable since it
1587
- // was already checked during `validateVin` validation.
1588
- // See `BitcoinTx.inputVector` docs for more details.
1589
- (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();
1590
- require(
1591
- inputsCount == 1,
1592
- "Outbound transaction must have a single input"
1593
- );
1594
-
1595
- bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);
1596
-
1597
- outpointTxHash = input.extractInputTxIdLE();
1598
-
1599
- outpointIndex = BTCUtils.reverseUint32(
1600
- uint32(input.extractTxIndexLE())
1601
- );
1602
-
1603
- // There is only one input in the transaction. Input has an outpoint
1604
- // field that is a reference to the transaction being spent (see
1605
- // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1606
- // to spend (`outpointTxHash`) and the index of the specific output
1607
- // from that transaction (`outpointIndex`).
1608
- return (outpointTxHash, outpointIndex);
1609
- }
1610
-
1611
- /// @notice Processes the Bitcoin redemption transaction output vector.
1612
- /// It extracts each output and tries to identify it as a pending
1613
- /// redemption request, reported timed out request, or change.
1614
- /// Reverts if one of the outputs cannot be recognized properly.
1615
- /// This function also marks each request as processed by removing
1616
- /// them from `pendingRedemptions` mapping.
1617
- /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1618
- /// vector. This function assumes vector's structure is valid so it
1619
- /// must be validated using e.g. `BTCUtils.validateVout` function
1620
- /// before it is passed here
1621
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1622
- // HASH160 over the compressed ECDSA public key) of the wallet which
1623
- /// performed the redemption transaction.
1624
- /// @return info Outcomes of the processing.
1625
- function processRedemptionTxOutputs(
1626
- bytes memory redemptionTxOutputVector,
1627
- bytes20 walletPubKeyHash
1628
- ) internal returns (RedemptionTxOutputsInfo memory info) {
1629
- // Determining the total number of redemption transaction outputs in
1630
- // the same way as for number of inputs. See `BitcoinTx.outputVector`
1631
- // docs for more details.
1632
- (
1633
- uint256 outputsCompactSizeUintLength,
1634
- uint256 outputsCount
1635
- ) = redemptionTxOutputVector.parseVarInt();
1636
-
1637
- // To determine the first output starting index, we must jump over
1638
- // the compactSize uint which prepends the output vector. One byte
1639
- // must be added because `BtcUtils.parseVarInt` does not include
1640
- // compactSize uint tag in the returned length.
1641
- //
1642
- // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1643
- // returns `0`, so we jump over one byte of compactSize uint.
1644
- //
1645
- // For >= 253 && <= 0xffff there is `0xfd` tag,
1646
- // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1647
- // tag byte included) so we need to jump over 1+2 bytes of
1648
- // compactSize uint.
1649
- //
1650
- // Please refer `BTCUtils` library and compactSize uint
1651
- // docs in `BitcoinTx` library for more details.
1652
- uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1653
-
1654
- // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1655
- // scripts that can be used to lock the change. This is done upfront to
1656
- // save on gas. Both scripts have a strict format defined by Bitcoin.
1657
- //
1658
- // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
1659
- // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1660
- // - 0x19: Byte length of the entire script
1661
- // - 0x76: OP_DUP
1662
- // - 0xa9: OP_HASH160
1663
- // - 0x14: Byte length of the public key hash
1664
- // - 0x88: OP_EQUALVERIFY
1665
- // - 0xac: OP_CHECKSIG
1666
- // which matches the P2PKH structure as per:
1667
- // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
1668
- bytes32 walletP2PKHScriptKeccak = keccak256(
1669
- abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1670
- );
1671
- // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
1672
- // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1673
- // - 0x16: Byte length of the entire script
1674
- // - 0x00: OP_0
1675
- // - 0x14: Byte length of the public key hash
1676
- // which matches the P2WPKH structure as per:
1677
- // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
1678
- bytes32 walletP2WPKHScriptKeccak = keccak256(
1679
- abi.encodePacked(hex"160014", walletPubKeyHash)
1680
- );
1681
-
1682
- // Helper variable that counts the number of processed redemption
1683
- // outputs. Redemptions can be either pending or reported as timed out.
1684
- // TODO: Revisit the approach with redemptions count according to
1685
- // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1686
- uint256 processedRedemptionsCount = 0;
1687
-
1688
- // Outputs processing loop.
1689
- for (uint256 i = 0; i < outputsCount; i++) {
1690
- // TODO: Check if we can optimize gas costs by adding
1691
- // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1692
- // in order to avoid allocating bytes in memory.
1693
- uint256 outputLength = redemptionTxOutputVector
1694
- .determineOutputLengthAt(outputStartingIndex);
1695
- bytes memory output = redemptionTxOutputVector.slice(
1696
- outputStartingIndex,
1697
- outputLength
1698
- );
1699
-
1700
- // Extract the value from given output.
1701
- uint64 outputValue = output.extractValue();
1702
- // The output consists of an 8-byte value and a variable length
1703
- // script. To extract that script we slice the output starting from
1704
- // 9th byte until the end.
1705
- bytes memory outputScript = output.slice(8, output.length - 8);
1706
-
1707
- if (
1708
- info.changeValue == 0 &&
1709
- (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1710
- keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1711
- outputValue > 0
1712
- ) {
1713
- // If we entered here, that means the change output with a
1714
- // proper non-zero value was found.
1715
- info.changeIndex = uint32(i);
1716
- info.changeValue = outputValue;
1717
- } else {
1718
- // If we entered here, that the means the given output is
1719
- // supposed to represent a redemption. Build the redemption key
1720
- // to perform that check.
1721
- uint256 redemptionKey = uint256(
1722
- keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
1723
- );
1724
-
1725
- if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1726
- // If we entered here, that means the output was identified
1727
- // as a pending redemption request.
1728
- RedemptionRequest storage request = pendingRedemptions[
1729
- redemptionKey
1730
- ];
1731
- // Compute the request's redeemable amount as the requested
1732
- // amount reduced by the treasury fee. The request's
1733
- // minimal amount is then the redeemable amount reduced by
1734
- // the maximum transaction fee.
1735
- uint64 redeemableAmount = request.requestedAmount -
1736
- request.treasuryFee;
1737
- // Output value must fit between the request's redeemable
1738
- // and minimal amounts to be deemed valid.
1739
- require(
1740
- redeemableAmount - request.txMaxFee <= outputValue &&
1741
- outputValue <= redeemableAmount,
1742
- "Output value is not within the acceptable range of the pending request"
1743
- );
1744
- // Add the redeemable amount to the total burnable value
1745
- // the Bridge will use to decrease its balance in the Bank.
1746
- info.totalBurnableValue += redeemableAmount;
1747
- // Add the request's treasury fee to the total treasury fee
1748
- // value the Bridge will transfer to the treasury.
1749
- info.totalTreasuryFee += request.treasuryFee;
1750
- // Request was properly handled so remove its redemption
1751
- // key from the mapping to make it reusable for further
1752
- // requests.
1753
- delete pendingRedemptions[redemptionKey];
1754
-
1755
- processedRedemptionsCount++;
1756
- } else {
1757
- // If we entered here, the output is not a redemption
1758
- // request but there is still a chance the given output is
1759
- // related to a reported timed out redemption request.
1760
- // If so, check if the output value matches the request
1761
- // amount to confirm this is an overdue request fulfillment
1762
- // then bypass this output and process the subsequent
1763
- // ones. That also means the wallet was already punished
1764
- // for the inactivity. Otherwise, just revert.
1765
- RedemptionRequest storage request = timedOutRedemptions[
1766
- redemptionKey
1767
- ];
1768
-
1769
- require(
1770
- request.requestedAt != 0,
1771
- "Output is a non-requested redemption"
1772
- );
1773
-
1774
- uint64 redeemableAmount = request.requestedAmount -
1775
- request.treasuryFee;
1776
-
1777
- require(
1778
- redeemableAmount - request.txMaxFee <= outputValue &&
1779
- outputValue <= redeemableAmount,
1780
- "Output value is not within the acceptable range of the timed out request"
1781
- );
1782
-
1783
- processedRedemptionsCount++;
1784
- }
1785
- }
1786
-
1787
- // Make the `outputStartingIndex` pointing to the next output by
1788
- // increasing it by current output's length.
1789
- outputStartingIndex += outputLength;
1790
- }
1791
-
1792
- // Protect against the cases when there is only a single change output
1793
- // referring back to the wallet PKH and just burning main UTXO value
1794
- // for transaction fees.
1795
- require(
1796
- processedRedemptionsCount > 0,
1797
- "Redemption transaction must process at least one redemption"
1798
- );
1799
-
1800
- return info;
1801
754
  }
1802
755
 
1803
756
  /// @notice Notifies that there is a pending redemption request associated
@@ -1828,56 +781,11 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1828
781
  bytes20 walletPubKeyHash,
1829
782
  bytes calldata redeemerOutputScript
1830
783
  ) external {
1831
- uint256 redemptionKey = uint256(
1832
- keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1833
- );
1834
- RedemptionRequest memory request = pendingRedemptions[redemptionKey];
1835
-
1836
- require(request.requestedAt > 0, "Redemption request does not exist");
1837
- require(
1838
- /* solhint-disable-next-line not-rely-on-time */
1839
- request.requestedAt + redemptionTimeout < block.timestamp,
1840
- "Redemption request has not timed out"
1841
- );
1842
-
1843
- // Update the wallet's pending redemptions value
1844
- Wallets.Wallet storage wallet = wallets.registeredWallets[
1845
- walletPubKeyHash
1846
- ];
1847
- wallet.pendingRedemptionsValue -=
1848
- request.requestedAmount -
1849
- request.treasuryFee;
1850
-
1851
- require(
1852
- // TODO: Allow the wallets in `Closing` state when the state is added
1853
- wallet.state == Wallets.WalletState.Live ||
1854
- wallet.state == Wallets.WalletState.MovingFunds ||
1855
- wallet.state == Wallets.WalletState.Terminated,
1856
- "The wallet must be in Live, MovingFunds or Terminated state"
784
+ self.notifyRedemptionTimeout(
785
+ wallets,
786
+ walletPubKeyHash,
787
+ redeemerOutputScript
1857
788
  );
1858
-
1859
- // It is worth noting that there is no need to check if
1860
- // `timedOutRedemption` mapping already contains the given redemption
1861
- // key. There is no possibility to re-use a key of a reported timed-out
1862
- // redemption because the wallet responsible for causing the timeout is
1863
- // moved to a state that prevents it to receive new redemption requests.
1864
-
1865
- // Move the redemption from pending redemptions to timed-out redemptions
1866
- timedOutRedemptions[redemptionKey] = request;
1867
- delete pendingRedemptions[redemptionKey];
1868
-
1869
- if (
1870
- wallet.state == Wallets.WalletState.Live ||
1871
- wallet.state == Wallets.WalletState.MovingFunds
1872
- ) {
1873
- // Propagate timeout consequences to the wallet
1874
- wallets.notifyRedemptionTimedOut(walletPubKeyHash);
1875
- }
1876
-
1877
- emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
1878
-
1879
- // Return the requested amount of tokens to the redeemer
1880
- bank.transferBalance(request.redeemer, request.requestedAmount);
1881
789
  }
1882
790
 
1883
791
  /// @notice Used by the wallet to prove the BTC moving funds transaction
@@ -1938,12 +846,14 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1938
846
  bytes32 movingFundsTxHash = BitcoinTx.validateProof(
1939
847
  movingFundsTx,
1940
848
  movingFundsProof,
1941
- proofDifficultyContext()
849
+ self.proofDifficultyContext()
1942
850
  );
1943
851
 
1944
852
  // Process the moving funds transaction input. Specifically, check if
1945
853
  // it refers to the expected wallet's main UTXO.
1946
- processWalletOutboundTxInput(
854
+ OutboundTx.processWalletOutboundTxInput(
855
+ self,
856
+ wallets,
1947
857
  movingFundsTx.inputVector,
1948
858
  mainUtxo,
1949
859
  walletPubKeyHash
@@ -2120,6 +1030,15 @@ contract Bridge is Ownable, EcdsaWalletOwner {
2120
1030
  return (targetWalletsHash, outputsTotalValue);
2121
1031
  }
2122
1032
 
1033
+ /// @notice Returns the addresses of contracts Bridge is interacting with.
1034
+ /// @return bank Address of the Bank the Bridge belongs to.
1035
+ /// @return relay Address of the Bitcoin relay providing the current Bitcoin
1036
+ /// network difficulty.
1037
+ function getContracts() external view returns (Bank bank, IRelay relay) {
1038
+ bank = self.bank;
1039
+ relay = self.relay;
1040
+ }
1041
+
2123
1042
  /// @notice Returns the current values of Bridge deposit parameters.
2124
1043
  /// @return depositDustThreshold The minimal amount that can be requested
2125
1044
  /// to deposit. Value of this parameter must take into account the
@@ -2133,13 +1052,77 @@ contract Bridge is Ownable, EcdsaWalletOwner {
2133
1052
  /// For example, if the treasury fee needs to be 2% of each deposit,
2134
1053
  /// the `depositTreasuryFeeDivisor` should be set to `50`
2135
1054
  /// because `1/50 = 0.02 = 2%`.
1055
+ /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can
1056
+ /// be incurred by each swept deposit being part of the given sweep
1057
+ /// transaction. If the maximum BTC transaction fee is exceeded,
1058
+ /// such transaction is considered a fraud.
1059
+ /// @return treasury Address where the deposit treasury fees will be
1060
+ /// sent to. Treasury takes part in the operators rewarding process.
1061
+ /// @return txProofDifficultyFactor The number of confirmations on the
1062
+ /// Bitcoin chain required to successfully evaluate an SPV proof.
2136
1063
  function depositParameters()
2137
1064
  external
2138
1065
  view
2139
- returns (uint64 depositDustThreshold, uint64 depositTreasuryFeeDivisor)
1066
+ returns (
1067
+ uint64 depositDustThreshold,
1068
+ uint64 depositTreasuryFeeDivisor,
1069
+ uint64 depositTxMaxFee,
1070
+ address treasury,
1071
+ uint256 txProofDifficultyFactor
1072
+ )
2140
1073
  {
2141
1074
  depositDustThreshold = self.depositDustThreshold;
2142
1075
  depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;
1076
+ depositTxMaxFee = self.depositTxMaxFee;
1077
+ treasury = self.treasury;
1078
+ txProofDifficultyFactor = self.txProofDifficultyFactor;
1079
+ }
1080
+
1081
+ /// @notice Returns the current values of Bridge redemption parameters.
1082
+ /// @return redemptionDustThreshold The minimal amount that can be requested
1083
+ /// for redemption. Value of this parameter must take into account
1084
+ /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
1085
+ /// parameters in order to make requests that can incur the
1086
+ /// treasury and transaction fee and still satisfy the redeemer.
1087
+ /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury
1088
+ /// fee taken from each redemption request and transferred to the
1089
+ /// treasury upon successful request finalization. That fee is
1090
+ /// computed as follows:
1091
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
1092
+ /// For example, if the treasury fee needs to be 2% of each
1093
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
1094
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
1095
+ /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that
1096
+ /// can be incurred by each redemption request being part of the
1097
+ /// given redemption transaction. If the maximum BTC transaction
1098
+ /// fee is exceeded, such transaction is considered a fraud.
1099
+ /// @return redemptionTimeout Time after which the redemption request can be
1100
+ /// reported as timed out. It is counted from the moment when the
1101
+ /// redemption request was created via `requestRedemption` call.
1102
+ /// Reported timed out requests are cancelled and locked TBTC is
1103
+ /// returned to the redeemer in full amount.
1104
+ /// @return treasury Address where the redemption treasury fees will be
1105
+ /// sent to. Treasury takes part in the operators rewarding process.
1106
+ /// @return txProofDifficultyFactor The number of confirmations on the
1107
+ /// Bitcoin chain required to successfully evaluate an SPV proof.
1108
+ function redemptionParameters()
1109
+ external
1110
+ view
1111
+ returns (
1112
+ uint64 redemptionDustThreshold,
1113
+ uint64 redemptionTreasuryFeeDivisor,
1114
+ uint64 redemptionTxMaxFee,
1115
+ uint256 redemptionTimeout,
1116
+ address treasury,
1117
+ uint256 txProofDifficultyFactor
1118
+ )
1119
+ {
1120
+ redemptionDustThreshold = self.redemptionDustThreshold;
1121
+ redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;
1122
+ redemptionTxMaxFee = self.redemptionTxMaxFee;
1123
+ redemptionTimeout = self.redemptionTimeout;
1124
+ treasury = self.treasury;
1125
+ txProofDifficultyFactor = self.txProofDifficultyFactor;
2143
1126
  }
2144
1127
 
2145
1128
  /// @notice Indicates if the vault with the given address is trusted or not.
@@ -2164,7 +1147,59 @@ contract Bridge is Ownable, EcdsaWalletOwner {
2164
1147
  view
2165
1148
  returns (Deposit.Request memory)
2166
1149
  {
2167
- // TODO: rename to getDeposit?
2168
1150
  return self.deposits[depositKey];
2169
1151
  }
1152
+
1153
+ /// @notice Collection of main UTXOs that are honestly spent indexed by
1154
+ /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash
1155
+ /// is bytes32 (ordered as in Bitcoin internally) and
1156
+ /// fundingOutputIndex an uint32. A main UTXO is considered honestly
1157
+ /// spent if it was used as an input of a transaction that have been
1158
+ /// proven in the Bridge.
1159
+ function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {
1160
+ return self.spentMainUTXOs[utxoKey];
1161
+ }
1162
+
1163
+ /// @notice Collection of all pending redemption requests indexed by
1164
+ /// redemption key built as
1165
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1166
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1167
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1168
+ /// public key) and redeemerOutputScript is a Bitcoin script
1169
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
1170
+ /// redeemed BTC as requested by the redeemer. Requests are added
1171
+ /// to this mapping by the `requestRedemption` method (duplicates
1172
+ /// not allowed) and are removed by one of the following methods:
1173
+ /// - `submitRedemptionProof` in case the request was handled
1174
+ /// successfully
1175
+ /// - `notifyRedemptionTimeout` in case the request was reported
1176
+ /// to be timed out
1177
+ function pendingRedemptions(uint256 redemptionKey)
1178
+ external
1179
+ view
1180
+ returns (Redeem.RedemptionRequest memory)
1181
+ {
1182
+ return self.pendingRedemptions[redemptionKey];
1183
+ }
1184
+
1185
+ /// @notice Collection of all timed out redemptions requests indexed by
1186
+ /// redemption key built as
1187
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1188
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1189
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1190
+ /// public key) and redeemerOutputScript is the Bitcoin script
1191
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
1192
+ /// out request. Timed out requests are stored in this mapping to
1193
+ /// avoid slashing the wallets multiple times for the same timeout.
1194
+ /// Only one method can add to this mapping:
1195
+ /// - `notifyRedemptionTimeout` which puts the redemption key
1196
+ /// to this mapping basing on a timed out request stored
1197
+ /// previously in `pendingRedemptions` mapping.
1198
+ function timedOutRedemptions(uint256 redemptionKey)
1199
+ external
1200
+ view
1201
+ returns (Redeem.RedemptionRequest memory)
1202
+ {
1203
+ return self.timedOutRedemptions[redemptionKey];
1204
+ }
2170
1205
  }