@keep-network/tbtc-v2 0.1.1-dev.6 → 0.1.1-dev.60

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 (95) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/Bank.json +752 -0
  3. package/artifacts/Bridge.json +3962 -0
  4. package/artifacts/Deposit.json +117 -0
  5. package/artifacts/DepositSweep.json +76 -0
  6. package/artifacts/EcdsaDkgValidator.json +532 -0
  7. package/artifacts/EcdsaInactivity.json +156 -0
  8. package/artifacts/Fraud.json +154 -0
  9. package/artifacts/KeepRegistry.json +99 -0
  10. package/artifacts/KeepStake.json +286 -0
  11. package/artifacts/KeepToken.json +711 -0
  12. package/artifacts/KeepTokenStaking.json +483 -0
  13. package/artifacts/MovingFunds.json +227 -0
  14. package/artifacts/NuCypherStakingEscrow.json +256 -0
  15. package/artifacts/NuCypherToken.json +711 -0
  16. package/artifacts/RandomBeaconStub.json +141 -0
  17. package/artifacts/Redemption.json +162 -0
  18. package/artifacts/ReimbursementPool.json +509 -0
  19. package/artifacts/Relay.json +123 -0
  20. package/artifacts/SortitionPool.json +944 -0
  21. package/artifacts/T.json +1148 -0
  22. package/artifacts/TBTC.json +27 -26
  23. package/artifacts/TBTCToken.json +27 -26
  24. package/artifacts/TokenStaking.json +2288 -0
  25. package/artifacts/TokenholderGovernor.json +1795 -0
  26. package/artifacts/TokenholderTimelock.json +1058 -0
  27. package/artifacts/VendingMachine.json +30 -29
  28. package/artifacts/VendingMachineKeep.json +400 -0
  29. package/artifacts/VendingMachineNuCypher.json +400 -0
  30. package/artifacts/WalletRegistry.json +2709 -0
  31. package/artifacts/WalletRegistryGovernance.json +2364 -0
  32. package/artifacts/Wallets.json +186 -0
  33. package/artifacts/solcInputs/59994c0eff9c9c3b454733a65b82146c.json +218 -0
  34. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  35. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  36. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  37. package/build/contracts/bank/Bank.sol/Bank.json +20 -2
  38. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  39. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  40. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  41. package/build/contracts/bridge/Bridge.sol/Bridge.json +2470 -132
  42. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  43. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +220 -0
  44. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  45. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  46. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +4 -0
  47. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +30 -0
  48. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  49. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  50. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  51. package/build/contracts/bridge/Fraud.sol/Fraud.json +86 -0
  52. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  53. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  54. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  55. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +125 -0
  56. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +4 -0
  57. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +10 -0
  58. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +4 -0
  59. package/build/contracts/bridge/Redemption.sol/Redemption.json +92 -0
  60. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  61. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  62. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  63. package/build/contracts/bridge/Wallets.sol/Wallets.json +112 -0
  64. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  65. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  66. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  67. package/build/contracts/vault/IVault.sol/IVault.json +19 -1
  68. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  69. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +36 -18
  70. package/contracts/GovernanceUtils.sol +1 -1
  71. package/contracts/bank/Bank.sol +34 -18
  72. package/contracts/bridge/BitcoinTx.sol +303 -0
  73. package/contracts/bridge/Bridge.sol +1527 -247
  74. package/contracts/bridge/BridgeState.sol +698 -0
  75. package/contracts/bridge/Deposit.sol +266 -0
  76. package/contracts/bridge/DepositSweep.sol +514 -0
  77. package/contracts/bridge/EcdsaLib.sol +45 -0
  78. package/contracts/bridge/Fraud.sol +508 -0
  79. package/contracts/bridge/IRelay.sol +28 -0
  80. package/contracts/bridge/MovingFunds.sol +1034 -0
  81. package/contracts/bridge/Redemption.sol +868 -0
  82. package/contracts/bridge/VendingMachine.sol +1 -1
  83. package/contracts/bridge/Wallets.sol +550 -0
  84. package/contracts/token/TBTC.sol +1 -1
  85. package/contracts/vault/IVault.sol +32 -10
  86. package/contracts/vault/TBTCVault.sol +20 -2
  87. package/deploy/00_resolve_relay.ts +28 -0
  88. package/deploy/04_deploy_bank.ts +27 -0
  89. package/deploy/05_deploy_bridge.ts +67 -0
  90. package/deploy/06_bank_update_bridge.ts +19 -0
  91. package/deploy/07_transfer_ownership.ts +15 -0
  92. package/deploy/08_transfer_governance.ts +20 -0
  93. package/export.json +15711 -475
  94. package/package.json +27 -24
  95. package/artifacts/solcInputs/c4fd2c31cc58f5fe0cc586dd84a84b60.json +0 -125
@@ -0,0 +1,1034 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity ^0.8.9;
17
+
18
+ import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
19
+ import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
20
+
21
+ import "./BitcoinTx.sol";
22
+ import "./BridgeState.sol";
23
+ import "./Redemption.sol";
24
+ import "./Wallets.sol";
25
+
26
+ /// @title Moving Bridge wallet funds
27
+ /// @notice The library handles the logic for moving Bitcoin between Bridge
28
+ /// wallets.
29
+ /// @dev A wallet that failed a heartbeat, did not process requested redemption
30
+ /// on time, or qualifies to be closed, begins the procedure of moving
31
+ /// funds to other wallets in the Bridge. The wallet needs to commit to
32
+ /// which other Live wallets it is moving the funds to and then, provide an
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.
37
+ library MovingFunds {
38
+ using BridgeState for BridgeState.Storage;
39
+ using Wallets for BridgeState.Storage;
40
+ using BitcoinTx for BridgeState.Storage;
41
+
42
+ using BTCUtils for bytes;
43
+ using BytesLib for bytes;
44
+
45
+ /// @notice Represents temporary information needed during the processing
46
+ /// of the moving funds Bitcoin transaction outputs. This structure
47
+ /// is an internal one and should not be exported outside of the
48
+ /// moving funds transaction processing code.
49
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
50
+ struct MovingFundsTxOutputsProcessingInfo {
51
+ // 32-byte hash of the moving funds Bitcoin transaction.
52
+ bytes32 movingFundsTxHash;
53
+ // Output vector of the moving funds Bitcoin transaction. It is
54
+ // assumed the vector's structure is valid so it must be validated
55
+ // using e.g. `BTCUtils.validateVout` function before being used
56
+ // during the processing. The validation is usually done as part
57
+ // of the `BitcoinTx.validateProof` call that checks the SPV proof.
58
+ bytes movingFundsTxOutputVector;
59
+ }
60
+
61
+ /// @notice Represents moved funds sweep request state.
62
+ enum MovedFundsSweepRequestState {
63
+ /// @dev The request is unknown to the Bridge.
64
+ Unknown,
65
+ /// @dev Request is pending and can become either processed or timed out.
66
+ Pending,
67
+ /// @dev Request was processed by the target wallet.
68
+ Processed,
69
+ /// @dev Request was not processed in the given time window and
70
+ /// the timeout was reported.
71
+ TimedOut
72
+ }
73
+
74
+ /// @notice Represents a moved funds sweep request. The request is
75
+ /// registered in `submitMovingFundsProof` where we know funds
76
+ /// have been moved to the target wallet and the only step left is
77
+ /// to have the target wallet sweep them.
78
+ struct MovedFundsSweepRequest {
79
+ // 20-byte public key hash of the wallet supposed to sweep the UTXO
80
+ // representing the received funds with their own main UTXO
81
+ bytes20 walletPubKeyHash;
82
+ // Value of the received funds.
83
+ uint64 value;
84
+ // UNIX timestamp the request was created at.
85
+ uint32 createdAt;
86
+ // The current state of the request.
87
+ MovedFundsSweepRequestState state;
88
+ }
89
+
90
+ event MovingFundsCommitmentSubmitted(
91
+ bytes20 walletPubKeyHash,
92
+ bytes20[] targetWallets,
93
+ address submitter
94
+ );
95
+
96
+ event MovingFundsCompleted(
97
+ bytes20 walletPubKeyHash,
98
+ bytes32 movingFundsTxHash
99
+ );
100
+
101
+ event MovingFundsTimedOut(bytes20 walletPubKeyHash);
102
+
103
+ event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);
104
+
105
+ event MovedFundsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
106
+
107
+ event MovedFundsSweepTimedOut(
108
+ bytes20 walletPubKeyHash,
109
+ bytes32 movingFundsTxHash,
110
+ uint32 movingFundsTxOutputIndex
111
+ );
112
+
113
+ /// @notice Submits the moving funds target wallets commitment.
114
+ /// Once all requirements are met, that function registers the
115
+ /// target wallets commitment and opens the way for moving funds
116
+ /// proof submission.
117
+ /// @param walletPubKeyHash 20-byte public key hash of the source wallet
118
+ /// @param walletMainUtxo Data of the source wallet's main UTXO, as
119
+ /// currently known on the Ethereum chain
120
+ /// @param walletMembersIDs Identifiers of the source wallet signing group
121
+ /// members
122
+ /// @param walletMemberIndex Position of the caller in the source wallet
123
+ /// signing group members list
124
+ /// @param targetWallets List of 20-byte public key hashes of the target
125
+ /// wallets that the source wallet commits to move the funds to
126
+ /// @dev Requirements:
127
+ /// - The source wallet must be in the MovingFunds state
128
+ /// - The source wallet must not have pending redemption requests
129
+ /// - The source wallet must not have pending moved funds sweep requests
130
+ /// - The source wallet must not have submitted its commitment already
131
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
132
+ /// be exactly the same as the hash stored under `membersIdsHash`
133
+ /// for the given source wallet in the ECDSA registry. Those IDs are
134
+ /// not directly stored in the contract for gas efficiency purposes
135
+ /// but they can be read from appropriate `DkgResultSubmitted`
136
+ /// and `DkgResultApproved` events.
137
+ /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]
138
+ /// - The caller must be the member of the source wallet signing group
139
+ /// at the position indicated by `walletMemberIndex` parameter
140
+ /// - The `walletMainUtxo` components must point to the recent main
141
+ /// UTXO of the source wallet, as currently known on the Ethereum
142
+ /// chain.
143
+ /// - Source wallet BTC balance must be greater than zero
144
+ /// - At least one Live wallet must exist in the system
145
+ /// - Submitted target wallets count must match the expected count
146
+ /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`
147
+ /// where `N > 0`
148
+ /// - Each target wallet must be not equal to the source wallet
149
+ /// - Each target wallet must follow the expected order i.e. all
150
+ /// target wallets 20-byte public key hashes represented as numbers
151
+ /// must form a strictly increasing sequence without duplicates.
152
+ /// - Each target wallet must be in Live state
153
+ function submitMovingFundsCommitment(
154
+ BridgeState.Storage storage self,
155
+ bytes20 walletPubKeyHash,
156
+ BitcoinTx.UTXO calldata walletMainUtxo,
157
+ uint32[] calldata walletMembersIDs,
158
+ uint256 walletMemberIndex,
159
+ bytes20[] calldata targetWallets
160
+ ) external {
161
+ Wallets.Wallet storage wallet = self.registeredWallets[
162
+ walletPubKeyHash
163
+ ];
164
+
165
+ require(
166
+ wallet.state == Wallets.WalletState.MovingFunds,
167
+ "Source wallet must be in MovingFunds state"
168
+ );
169
+
170
+ require(
171
+ wallet.pendingRedemptionsValue == 0,
172
+ "Source wallet must handle all pending redemptions first"
173
+ );
174
+
175
+ require(
176
+ wallet.pendingMovedFundsSweepRequestsCount == 0,
177
+ "Source wallet must handle all pending moved funds sweep requests first"
178
+ );
179
+
180
+ require(
181
+ wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),
182
+ "Target wallets commitment already submitted"
183
+ );
184
+
185
+ require(
186
+ self.ecdsaWalletRegistry.isWalletMember(
187
+ wallet.ecdsaWalletID,
188
+ walletMembersIDs,
189
+ msg.sender,
190
+ walletMemberIndex
191
+ ),
192
+ "Caller is not a member of the source wallet"
193
+ );
194
+
195
+ uint64 walletBtcBalance = self.getWalletBtcBalance(
196
+ walletPubKeyHash,
197
+ walletMainUtxo
198
+ );
199
+
200
+ require(walletBtcBalance > 0, "Wallet BTC balance is zero");
201
+
202
+ uint256 expectedTargetWalletsCount = Math.min(
203
+ self.liveWalletsCount,
204
+ Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)
205
+ );
206
+
207
+ // This requirement fails only when `liveWalletsCount` is zero. In
208
+ // that case, the system cannot accept the commitment and must provide
209
+ // new wallets first.
210
+ //
211
+ // TODO: Expose separate function to reset the moving funds timeout
212
+ // if no Live wallets exist in the system.
213
+ require(expectedTargetWalletsCount > 0, "No target wallets available");
214
+
215
+ require(
216
+ targetWallets.length == expectedTargetWalletsCount,
217
+ "Submitted target wallets count is other than expected"
218
+ );
219
+
220
+ uint160 lastProcessedTargetWallet = 0;
221
+
222
+ for (uint256 i = 0; i < targetWallets.length; i++) {
223
+ bytes20 targetWallet = targetWallets[i];
224
+
225
+ require(
226
+ targetWallet != walletPubKeyHash,
227
+ "Submitted target wallet cannot be equal to the source wallet"
228
+ );
229
+
230
+ require(
231
+ uint160(targetWallet) > lastProcessedTargetWallet,
232
+ "Submitted target wallet breaks the expected order"
233
+ );
234
+
235
+ require(
236
+ self.registeredWallets[targetWallet].state ==
237
+ Wallets.WalletState.Live,
238
+ "Submitted target wallet must be in Live state"
239
+ );
240
+
241
+ lastProcessedTargetWallet = uint160(targetWallet);
242
+ }
243
+
244
+ wallet.movingFundsTargetWalletsCommitmentHash = keccak256(
245
+ abi.encodePacked(targetWallets)
246
+ );
247
+
248
+ emit MovingFundsCommitmentSubmitted(
249
+ walletPubKeyHash,
250
+ targetWallets,
251
+ msg.sender
252
+ );
253
+ }
254
+
255
+ /// @notice Used by the wallet to prove the BTC moving funds transaction
256
+ /// and to make the necessary state changes. Moving funds is only
257
+ /// accepted if it satisfies SPV proof.
258
+ ///
259
+ /// The function validates the moving funds transaction structure
260
+ /// by checking if it actually spends the main UTXO of the declared
261
+ /// wallet and locks the value on the pre-committed target wallets
262
+ /// using a reasonable transaction fee. If all preconditions are
263
+ /// met, this functions closes the source wallet.
264
+ ///
265
+ /// It is possible to prove the given moving funds transaction only
266
+ /// one time.
267
+ /// @param movingFundsTx Bitcoin moving funds transaction data
268
+ /// @param movingFundsProof Bitcoin moving funds proof data
269
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
270
+ /// the Ethereum chain
271
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
272
+ /// HASH160 over the compressed ECDSA public key) of the wallet
273
+ /// which performed the moving funds transaction
274
+ /// @dev Requirements:
275
+ /// - `movingFundsTx` components must match the expected structure. See
276
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
277
+ /// correspond to appropriate Bitcoin transaction fields to produce
278
+ /// a provable transaction hash.
279
+ /// - The `movingFundsTx` should represent a Bitcoin transaction with
280
+ /// exactly 1 input that refers to the wallet's main UTXO. That
281
+ /// transaction should have 1..n outputs corresponding to the
282
+ /// pre-committed target wallets. Outputs must be ordered in the
283
+ /// same way as their corresponding target wallets are ordered
284
+ /// within the target wallets commitment.
285
+ /// - `movingFundsProof` components must match the expected structure.
286
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
287
+ /// field must contain a valid number of block headers, not less
288
+ /// than the `txProofDifficultyFactor` contract constant.
289
+ /// - `mainUtxo` components must point to the recent main UTXO
290
+ /// of the given wallet, as currently known on the Ethereum chain.
291
+ /// Additionally, the recent main UTXO on Ethereum must be set.
292
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
293
+ /// as transaction single input.
294
+ /// - The wallet that `walletPubKeyHash` points to must be in the
295
+ /// MovingFunds state.
296
+ /// - The target wallets commitment must be submitted by the wallet
297
+ /// that `walletPubKeyHash` points to.
298
+ /// - The total Bitcoin transaction fee must be lesser or equal
299
+ /// to `movingFundsTxMaxTotalFee` governable parameter.
300
+ function submitMovingFundsProof(
301
+ BridgeState.Storage storage self,
302
+ BitcoinTx.Info calldata movingFundsTx,
303
+ BitcoinTx.Proof calldata movingFundsProof,
304
+ BitcoinTx.UTXO calldata mainUtxo,
305
+ bytes20 walletPubKeyHash
306
+ ) external {
307
+ // The actual transaction proof is performed here. After that point, we
308
+ // can assume the transaction happened on Bitcoin chain and has
309
+ // a sufficient number of confirmations as determined by
310
+ // `txProofDifficultyFactor` constant.
311
+ bytes32 movingFundsTxHash = self.validateProof(
312
+ movingFundsTx,
313
+ movingFundsProof
314
+ );
315
+
316
+ // Process the moving funds transaction input. Specifically, check if
317
+ // it refers to the expected wallet's main UTXO.
318
+ OutboundTx.processWalletOutboundTxInput(
319
+ self,
320
+ movingFundsTx.inputVector,
321
+ mainUtxo,
322
+ walletPubKeyHash
323
+ );
324
+
325
+ (
326
+ bytes32 targetWalletsHash,
327
+ uint256 outputsTotalValue
328
+ ) = processMovingFundsTxOutputs(
329
+ self,
330
+ MovingFundsTxOutputsProcessingInfo(
331
+ movingFundsTxHash,
332
+ movingFundsTx.outputVector
333
+ )
334
+ );
335
+
336
+ require(
337
+ mainUtxo.txOutputValue - outputsTotalValue <=
338
+ self.movingFundsTxMaxTotalFee,
339
+ "Transaction fee is too high"
340
+ );
341
+
342
+ self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);
343
+ // slither-disable-next-line reentrancy-events
344
+ emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);
345
+ }
346
+
347
+ /// @notice Processes the moving funds Bitcoin transaction output vector
348
+ /// and extracts information required for further processing.
349
+ /// @param processInfo Processing info containing the moving funds tx
350
+ /// hash and output vector.
351
+ /// @return targetWalletsHash keccak256 hash over the list of actual
352
+ /// target wallets used in the transaction.
353
+ /// @return outputsTotalValue Sum of all outputs values.
354
+ /// @dev Requirements:
355
+ /// - The `movingFundsTxOutputVector` must be parseable, i.e. must
356
+ /// be validated by the caller as stated in their parameter doc.
357
+ /// - Each output must refer to a 20-byte public key hash.
358
+ /// - The total outputs value must be evenly divided over all outputs.
359
+ function processMovingFundsTxOutputs(
360
+ BridgeState.Storage storage self,
361
+ MovingFundsTxOutputsProcessingInfo memory processInfo
362
+ ) internal returns (bytes32 targetWalletsHash, uint256 outputsTotalValue) {
363
+ // Determining the total number of Bitcoin transaction outputs in
364
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
365
+ // docs for more details.
366
+ (
367
+ uint256 outputsCompactSizeUintLength,
368
+ uint256 outputsCount
369
+ ) = processInfo.movingFundsTxOutputVector.parseVarInt();
370
+
371
+ // To determine the first output starting index, we must jump over
372
+ // the compactSize uint which prepends the output vector. One byte
373
+ // must be added because `BtcUtils.parseVarInt` does not include
374
+ // compactSize uint tag in the returned length.
375
+ //
376
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
377
+ // returns `0`, so we jump over one byte of compactSize uint.
378
+ //
379
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
380
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
381
+ // tag byte included) so we need to jump over 1+2 bytes of
382
+ // compactSize uint.
383
+ //
384
+ // Please refer `BTCUtils` library and compactSize uint
385
+ // docs in `BitcoinTx` library for more details.
386
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
387
+
388
+ bytes20[] memory targetWallets = new bytes20[](outputsCount);
389
+ uint64[] memory outputsValues = new uint64[](outputsCount);
390
+
391
+ // Outputs processing loop. Note that the `outputIndex` must be
392
+ // `uint32` to build proper `movedFundsSweepRequests` keys.
393
+ for (
394
+ uint32 outputIndex = 0;
395
+ outputIndex < outputsCount;
396
+ outputIndex++
397
+ ) {
398
+ uint256 outputLength = processInfo
399
+ .movingFundsTxOutputVector
400
+ .determineOutputLengthAt(outputStartingIndex);
401
+
402
+ bytes memory output = processInfo.movingFundsTxOutputVector.slice(
403
+ outputStartingIndex,
404
+ outputLength
405
+ );
406
+
407
+ bytes20 targetWalletPubKeyHash = self.extractPubKeyHash(output);
408
+
409
+ // Add the wallet public key hash to the list that will be used
410
+ // to build the result list hash. There is no need to check if
411
+ // given output is a change here because the actual target wallet
412
+ // list must be exactly the same as the pre-committed target wallet
413
+ // list which is guaranteed to be valid.
414
+ targetWallets[outputIndex] = targetWalletPubKeyHash;
415
+
416
+ // Extract the value from given output.
417
+ outputsValues[outputIndex] = output.extractValue();
418
+ outputsTotalValue += outputsValues[outputIndex];
419
+
420
+ // Register a moved funds sweep request that must be handled
421
+ // by the target wallet. The target wallet must sweep the
422
+ // received funds with their own main UTXO in order to update
423
+ // their BTC balance. Worth noting there is no need to check
424
+ // if the sweep request already exists in the system because
425
+ // the moving funds wallet is moved to the Closing state after
426
+ // submitting the moving funds proof so there is no possibility
427
+ // to submit the proof again and register the sweep request twice.
428
+ self.movedFundsSweepRequests[
429
+ uint256(
430
+ keccak256(
431
+ abi.encodePacked(
432
+ processInfo.movingFundsTxHash,
433
+ outputIndex
434
+ )
435
+ )
436
+ )
437
+ ] = MovedFundsSweepRequest(
438
+ targetWalletPubKeyHash,
439
+ outputsValues[outputIndex],
440
+ /* solhint-disable-next-line not-rely-on-time */
441
+ uint32(block.timestamp),
442
+ MovedFundsSweepRequestState.Pending
443
+ );
444
+ // We added a new moved funds sweep request for the target wallet
445
+ // so we must increment their request counter.
446
+ self
447
+ .registeredWallets[targetWalletPubKeyHash]
448
+ .pendingMovedFundsSweepRequestsCount++;
449
+
450
+ // Make the `outputStartingIndex` pointing to the next output by
451
+ // increasing it by current output's length.
452
+ outputStartingIndex += outputLength;
453
+ }
454
+
455
+ // Compute the indivisible remainder that remains after dividing the
456
+ // outputs total value over all outputs evenly.
457
+ uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;
458
+ // Compute the minimum allowed output value by dividing the outputs
459
+ // total value (reduced by the remainder) by the number of outputs.
460
+ uint256 minOutputValue = (outputsTotalValue -
461
+ outputsTotalValueRemainder) / outputsCount;
462
+ // Maximum possible value is the minimum value with the remainder included.
463
+ uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;
464
+
465
+ for (uint256 i = 0; i < outputsCount; i++) {
466
+ require(
467
+ minOutputValue <= outputsValues[i] &&
468
+ outputsValues[i] <= maxOutputValue,
469
+ "Transaction amount is not distributed evenly"
470
+ );
471
+ }
472
+
473
+ targetWalletsHash = keccak256(abi.encodePacked(targetWallets));
474
+
475
+ return (targetWalletsHash, outputsTotalValue);
476
+ }
477
+
478
+ /// @notice Notifies about a timed out moving funds process. Terminates
479
+ /// the wallet and slashes signing group members as a result.
480
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
481
+ /// @param walletMembersIDs Identifiers of the wallet signing group members
482
+ /// @dev Requirements:
483
+ /// - The wallet must be in the MovingFunds state
484
+ /// - The moving funds timeout must be actually exceeded
485
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
486
+ /// be exactly the same as the hash stored under `membersIdsHash`
487
+ /// for the given `walletID`. Those IDs are not directly stored
488
+ /// in the contract for gas efficiency purposes but they can be
489
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
490
+ /// events of the `WalletRegistry` contract
491
+ function notifyMovingFundsTimeout(
492
+ BridgeState.Storage storage self,
493
+ bytes20 walletPubKeyHash,
494
+ uint32[] calldata walletMembersIDs
495
+ ) external {
496
+ Wallets.Wallet storage wallet = self.registeredWallets[
497
+ walletPubKeyHash
498
+ ];
499
+
500
+ require(
501
+ wallet.state == Wallets.WalletState.MovingFunds,
502
+ "ECDSA wallet must be in MovingFunds state"
503
+ );
504
+
505
+ require(
506
+ /* solhint-disable-next-line not-rely-on-time */
507
+ block.timestamp >
508
+ wallet.movingFundsRequestedAt + self.movingFundsTimeout,
509
+ "Moving funds has not timed out yet"
510
+ );
511
+
512
+ self.terminateWallet(walletPubKeyHash);
513
+
514
+ self.ecdsaWalletRegistry.seize(
515
+ self.movingFundsTimeoutSlashingAmount,
516
+ self.movingFundsTimeoutNotifierRewardMultiplier,
517
+ msg.sender,
518
+ wallet.ecdsaWalletID,
519
+ walletMembersIDs
520
+ );
521
+
522
+ // slither-disable-next-line reentrancy-events
523
+ emit MovingFundsTimedOut(walletPubKeyHash);
524
+ }
525
+
526
+ /// @notice Notifies about a moving funds wallet whose BTC balance is
527
+ /// below the moving funds dust threshold. Ends the moving funds
528
+ /// process and begins wallet closing immediately.
529
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
530
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known
531
+ /// on the Ethereum chain.
532
+ /// @dev Requirements:
533
+ /// - The wallet must be in the MovingFunds state
534
+ /// - The `mainUtxo` components must point to the recent main UTXO
535
+ /// of the given wallet, as currently known on the Ethereum chain.
536
+ /// If the wallet has no main UTXO, this parameter can be empty as it
537
+ /// is ignored.
538
+ /// - The wallet BTC balance must be below the moving funds threshold
539
+ function notifyMovingFundsBelowDust(
540
+ BridgeState.Storage storage self,
541
+ bytes20 walletPubKeyHash,
542
+ BitcoinTx.UTXO calldata mainUtxo
543
+ ) external {
544
+ Wallets.Wallet storage wallet = self.registeredWallets[
545
+ walletPubKeyHash
546
+ ];
547
+
548
+ require(
549
+ wallet.state == Wallets.WalletState.MovingFunds,
550
+ "ECDSA wallet must be in MovingFunds state"
551
+ );
552
+
553
+ uint64 walletBtcBalance = self.getWalletBtcBalance(
554
+ walletPubKeyHash,
555
+ mainUtxo
556
+ );
557
+
558
+ require(
559
+ walletBtcBalance < self.movingFundsDustThreshold,
560
+ "Wallet BTC balance must be below the moving funds dust threshold"
561
+ );
562
+
563
+ self.beginWalletClosing(walletPubKeyHash);
564
+
565
+ // slither-disable-next-line reentrancy-events
566
+ emit MovingFundsBelowDustReported(walletPubKeyHash);
567
+ }
568
+
569
+ /// @notice Used by the wallet to prove the BTC moved funds sweep
570
+ /// transaction and to make the necessary state changes. Moved
571
+ /// funds sweep is only accepted if it satisfies SPV proof.
572
+ ///
573
+ /// The function validates the sweep transaction structure by
574
+ /// checking if it actually spends the moved funds UTXO and the
575
+ /// sweeping wallet's main UTXO (optionally), and if it locks the
576
+ /// value on the sweeping wallet's 20-byte public key hash using a
577
+ /// reasonable transaction fee. If all preconditions are
578
+ /// met, this function updates the sweeping wallet main UTXO, thus
579
+ /// their BTC balance.
580
+ ///
581
+ /// It is possible to prove the given sweep transaction only
582
+ /// one time.
583
+ /// @param sweepTx Bitcoin sweep funds transaction data
584
+ /// @param sweepProof Bitcoin sweep funds proof data
585
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently
586
+ /// known on the Ethereum chain
587
+ /// @dev Requirements:
588
+ /// - `sweepTx` components must match the expected structure. See
589
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
590
+ /// correspond to appropriate Bitcoin transaction fields to produce
591
+ /// a provable transaction hash.
592
+ /// - The `sweepTx` should represent a Bitcoin transaction with
593
+ /// the first input pointing to a wallet's sweep Pending request and,
594
+ /// optionally, the second input pointing to the wallet's main UTXO,
595
+ /// if the sweeping wallet has a main UTXO set. There should be only
596
+ /// one output locking funds on the sweeping wallet 20-byte public
597
+ /// key hash.
598
+ /// - `sweepProof` components must match the expected structure.
599
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
600
+ /// field must contain a valid number of block headers, not less
601
+ /// than the `txProofDifficultyFactor` contract constant.
602
+ /// - `mainUtxo` components must point to the recent main UTXO
603
+ /// of the sweeping wallet, as currently known on the Ethereum chain.
604
+ /// If there is no main UTXO, this parameter is ignored.
605
+ /// - The sweeping wallet must be in the Live or MovingFunds state.
606
+ /// - The total Bitcoin transaction fee must be lesser or equal
607
+ /// to `movedFundsSweepTxMaxTotalFee` governable parameter.
608
+ function submitMovedFundsSweepProof(
609
+ BridgeState.Storage storage self,
610
+ BitcoinTx.Info calldata sweepTx,
611
+ BitcoinTx.Proof calldata sweepProof,
612
+ BitcoinTx.UTXO calldata mainUtxo
613
+ ) external {
614
+ // The actual transaction proof is performed here. After that point, we
615
+ // can assume the transaction happened on Bitcoin chain and has
616
+ // a sufficient number of confirmations as determined by
617
+ // `txProofDifficultyFactor` constant.
618
+ bytes32 sweepTxHash = self.validateProof(sweepTx, sweepProof);
619
+
620
+ (
621
+ bytes20 walletPubKeyHash,
622
+ uint64 sweepTxOutputValue
623
+ ) = processMovedFundsSweepTxOutput(self, sweepTx.outputVector);
624
+
625
+ (
626
+ Wallets.Wallet storage wallet,
627
+ BitcoinTx.UTXO memory resolvedMainUtxo
628
+ ) = resolveMovedFundsSweepingWallet(self, walletPubKeyHash, mainUtxo);
629
+
630
+ uint256 sweepTxInputsTotalValue = processMovedFundsSweepTxInputs(
631
+ self,
632
+ sweepTx.inputVector,
633
+ resolvedMainUtxo,
634
+ walletPubKeyHash
635
+ );
636
+
637
+ require(
638
+ sweepTxInputsTotalValue - sweepTxOutputValue <=
639
+ self.movedFundsSweepTxMaxTotalFee,
640
+ "Transaction fee is too high"
641
+ );
642
+
643
+ // Use the sweep transaction output as the new sweeping wallet's main UTXO.
644
+ // Transaction output index is always 0 as sweep transaction always
645
+ // contains only one output.
646
+ wallet.mainUtxoHash = keccak256(
647
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
648
+ );
649
+
650
+ // slither-disable-next-line reentrancy-events
651
+ emit MovedFundsSwept(walletPubKeyHash, sweepTxHash);
652
+ }
653
+
654
+ /// @notice Processes the Bitcoin moved funds sweep transaction output vector
655
+ /// by extracting the single output and using it to gain additional
656
+ /// information required for further processing (e.g. value and
657
+ /// wallet public key hash).
658
+ /// @param sweepTxOutputVector Bitcoin moved funds sweep transaction output
659
+ /// vector.
660
+ /// This function assumes vector's structure is valid so it must be
661
+ /// validated using e.g. `BTCUtils.validateVout` function before
662
+ /// it is passed here
663
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
664
+ /// @return value 8-byte moved funds sweep transaction output value.
665
+ /// @dev Requirements:
666
+ /// - Output vector must contain only one output
667
+ /// - The single output must be of P2PKH or P2WPKH type and lock the
668
+ /// funds on a 20-byte public key hash
669
+ function processMovedFundsSweepTxOutput(
670
+ BridgeState.Storage storage self,
671
+ bytes memory sweepTxOutputVector
672
+ ) internal view returns (bytes20 walletPubKeyHash, uint64 value) {
673
+ // To determine the total number of sweep transaction outputs, we need to
674
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
675
+ // That compactSize uint encodes the number of vector elements using the
676
+ // format presented in:
677
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
678
+ // We don't need asserting the compactSize uint is parseable since it
679
+ // was already checked during `validateVout` validation performed as
680
+ // part of the `BitcoinTx.validateProof` call.
681
+ // See `BitcoinTx.outputVector` docs for more details.
682
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
683
+ require(
684
+ outputsCount == 1,
685
+ "Moved funds sweep transaction must have a single output"
686
+ );
687
+
688
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
689
+ walletPubKeyHash = self.extractPubKeyHash(output);
690
+ value = output.extractValue();
691
+
692
+ return (walletPubKeyHash, value);
693
+ }
694
+
695
+ /// @notice Resolves sweeping wallet based on the provided wallet public key
696
+ /// hash. Validates the wallet state and current main UTXO, as
697
+ /// currently known on the Ethereum chain.
698
+ /// @param walletPubKeyHash public key hash of the wallet proving the sweep
699
+ /// Bitcoin transaction.
700
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
701
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
702
+ /// this parameter is ignored
703
+ /// @return wallet Data of the sweeping wallet.
704
+ /// @return resolvedMainUtxo The actual main UTXO of the sweeping wallet
705
+ /// resolved by cross-checking the `mainUtxo` parameter with
706
+ /// the chain state. If the validation went well, this is the
707
+ /// plain-text main UTXO corresponding to the `wallet.mainUtxoHash`.
708
+ /// @dev Requirements:
709
+ /// - Sweeping wallet must be either in Live or MovingFunds state.
710
+ /// - If the main UTXO of the sweeping wallet exists in the storage,
711
+ /// the passed `mainUTXO` parameter must be equal to the stored one.
712
+ function resolveMovedFundsSweepingWallet(
713
+ BridgeState.Storage storage self,
714
+ bytes20 walletPubKeyHash,
715
+ BitcoinTx.UTXO calldata mainUtxo
716
+ )
717
+ internal
718
+ view
719
+ returns (
720
+ Wallets.Wallet storage wallet,
721
+ BitcoinTx.UTXO memory resolvedMainUtxo
722
+ )
723
+ {
724
+ wallet = self.registeredWallets[walletPubKeyHash];
725
+
726
+ Wallets.WalletState walletState = wallet.state;
727
+ require(
728
+ walletState == Wallets.WalletState.Live ||
729
+ walletState == Wallets.WalletState.MovingFunds,
730
+ "Wallet must be in Live or MovingFunds state"
731
+ );
732
+
733
+ // Check if the main UTXO for given wallet exists. If so, validate
734
+ // passed main UTXO data against the stored hash and use them for
735
+ // further processing. If no main UTXO exists, use empty data.
736
+ resolvedMainUtxo = BitcoinTx.UTXO(bytes32(0), 0, 0);
737
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
738
+ if (mainUtxoHash != bytes32(0)) {
739
+ require(
740
+ keccak256(
741
+ abi.encodePacked(
742
+ mainUtxo.txHash,
743
+ mainUtxo.txOutputIndex,
744
+ mainUtxo.txOutputValue
745
+ )
746
+ ) == mainUtxoHash,
747
+ "Invalid main UTXO data"
748
+ );
749
+ resolvedMainUtxo = mainUtxo;
750
+ }
751
+ }
752
+
753
+ /// @notice Processes the Bitcoin moved funds sweep transaction input vector.
754
+ /// It extracts the first input and tries to match it with one of
755
+ /// the moved funds sweep requests targeting the sweeping wallet.
756
+ /// If the sweep request is an existing Pending request, this
757
+ /// function marks it as Processed. If the sweeping wallet has a
758
+ /// main UTXO, this function extracts the second input, makes sure
759
+ /// it refers to the wallet main UTXO, and marks that main UTXO as
760
+ /// correctly spent.
761
+ /// @param sweepTxInputVector Bitcoin moved funds sweep transaction input vector.
762
+ /// This function assumes vector's structure is valid so it must be
763
+ /// validated using e.g. `BTCUtils.validateVin` function before
764
+ /// it is passed here
765
+ /// @param mainUtxo Data of the sweeping wallet's main UTXO. If no main UTXO
766
+ /// exists for the given the wallet, this parameter's fields should
767
+ /// be zeroed to bypass the main UTXO validation
768
+ /// @param walletPubKeyHash 20-byte public key hash of the sweeping wallet
769
+ /// @return inputsTotalValue Total inputs value sum.
770
+ /// @dev Requirements:
771
+ /// - The input vector must consist of one mandatory and one optional
772
+ /// input.
773
+ /// - The mandatory input must be the first input in the vector
774
+ /// - The mandatory input must point to a Pending moved funds sweep
775
+ /// request that is targeted to the sweeping wallet
776
+ /// - The optional output must be the second input in the vector
777
+ /// - The optional input is required if the sweeping wallet has a
778
+ /// main UTXO (i.e. the `mainUtxo` is not zeroed). In that case,
779
+ /// that input must point the the sweeping wallet main UTXO.
780
+ function processMovedFundsSweepTxInputs(
781
+ BridgeState.Storage storage self,
782
+ bytes memory sweepTxInputVector,
783
+ BitcoinTx.UTXO memory mainUtxo,
784
+ bytes20 walletPubKeyHash
785
+ ) internal returns (uint256 inputsTotalValue) {
786
+ // To determine the total number of Bitcoin transaction inputs,
787
+ // we need to parse the compactSize uint (VarInt) the input vector is
788
+ // prepended by. That compactSize uint encodes the number of vector
789
+ // elements using the format presented in:
790
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
791
+ // We don't need asserting the compactSize uint is parseable since it
792
+ // was already checked during `validateVin` validation performed as
793
+ // part of the `BitcoinTx.validateProof` call.
794
+ // See `BitcoinTx.inputVector` docs for more details.
795
+ (
796
+ uint256 inputsCompactSizeUintLength,
797
+ uint256 inputsCount
798
+ ) = sweepTxInputVector.parseVarInt();
799
+
800
+ // To determine the first input starting index, we must jump over
801
+ // the compactSize uint which prepends the input vector. One byte
802
+ // must be added because `BtcUtils.parseVarInt` does not include
803
+ // compactSize uint tag in the returned length.
804
+ //
805
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
806
+ // returns `0`, so we jump over one byte of compactSize uint.
807
+ //
808
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
809
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
810
+ // tag byte included) so we need to jump over 1+2 bytes of
811
+ // compactSize uint.
812
+ //
813
+ // Please refer `BTCUtils` library and compactSize uint
814
+ // docs in `BitcoinTx` library for more details.
815
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
816
+
817
+ // We always expect the first input to be the swept UTXO. Additionally,
818
+ // if the sweeping wallet has a main UTXO, that main UTXO should be
819
+ // pointed by the second input.
820
+ require(
821
+ inputsCount == (mainUtxo.txHash != bytes32(0) ? 2 : 1),
822
+ "Moved funds sweep transaction must have a proper inputs count"
823
+ );
824
+
825
+ // Parse the first input and extract its outpoint tx hash and index.
826
+ (
827
+ bytes32 firstInputOutpointTxHash,
828
+ uint32 firstInputOutpointIndex,
829
+ uint256 firstInputLength
830
+ ) = parseMovedFundsSweepTxInputAt(
831
+ sweepTxInputVector,
832
+ inputStartingIndex
833
+ );
834
+
835
+ // Build the request key and fetch the corresponding moved funds sweep
836
+ // request from contract storage.
837
+ MovedFundsSweepRequest storage sweepRequest = self
838
+ .movedFundsSweepRequests[
839
+ uint256(
840
+ keccak256(
841
+ abi.encodePacked(
842
+ firstInputOutpointTxHash,
843
+ firstInputOutpointIndex
844
+ )
845
+ )
846
+ )
847
+ ];
848
+
849
+ require(
850
+ sweepRequest.state == MovedFundsSweepRequestState.Pending,
851
+ "Sweep request must be in Pending state"
852
+ );
853
+ // We must check if the wallet extracted from the moved funds sweep
854
+ // transaction output is truly the owner of the sweep request connected
855
+ // with the swept UTXO. This is needed to prevent a case when a wallet
856
+ // handles its own sweep request but locks the funds on another
857
+ // wallet public key hash.
858
+ require(
859
+ sweepRequest.walletPubKeyHash == walletPubKeyHash,
860
+ "Sweep request belongs to another wallet"
861
+ );
862
+ // If the validation passed, the sweep request must be marked as
863
+ // processed and its value should be counted into the total inputs
864
+ // value sum.
865
+ sweepRequest.state = MovedFundsSweepRequestState.Processed;
866
+ inputsTotalValue += sweepRequest.value;
867
+
868
+ self
869
+ .registeredWallets[walletPubKeyHash]
870
+ .pendingMovedFundsSweepRequestsCount--;
871
+
872
+ // If the main UTXO for the sweeping wallet exists, it must be processed.
873
+ if (mainUtxo.txHash != bytes32(0)) {
874
+ // The second input is supposed to point to that sweeping wallet
875
+ // main UTXO. We need to parse that input.
876
+ (
877
+ bytes32 secondInputOutpointTxHash,
878
+ uint32 secondInputOutpointIndex,
879
+
880
+ ) = parseMovedFundsSweepTxInputAt(
881
+ sweepTxInputVector,
882
+ inputStartingIndex + firstInputLength
883
+ );
884
+ // Make sure the second input refers to the sweeping wallet main UTXO.
885
+ require(
886
+ mainUtxo.txHash == secondInputOutpointTxHash &&
887
+ mainUtxo.txOutputIndex == secondInputOutpointIndex,
888
+ "Second input must point to the wallet's main UTXO"
889
+ );
890
+
891
+ // If the validation passed, count the main UTXO value into the
892
+ // total inputs value sum.
893
+ inputsTotalValue += mainUtxo.txOutputValue;
894
+
895
+ // Main UTXO used as an input, mark it as spent. This is needed
896
+ // to defend against fraud challenges referring to this main UTXO.
897
+ self.spentMainUTXOs[
898
+ uint256(
899
+ keccak256(
900
+ abi.encodePacked(
901
+ secondInputOutpointTxHash,
902
+ secondInputOutpointIndex
903
+ )
904
+ )
905
+ )
906
+ ] = true;
907
+ }
908
+
909
+ return inputsTotalValue;
910
+ }
911
+
912
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
913
+ /// @param inputVector Bitcoin transaction input vector
914
+ /// @param inputStartingIndex Index the given input starts at
915
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
916
+ /// pointed in the given input's outpoint.
917
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
918
+ /// which is pointed in the given input's outpoint.
919
+ /// @return inputLength Byte length of the given input.
920
+ /// @dev This function assumes vector's structure is valid so it must be
921
+ /// validated using e.g. `BTCUtils.validateVin` function before it
922
+ /// is passed here.
923
+ function parseMovedFundsSweepTxInputAt(
924
+ bytes memory inputVector,
925
+ uint256 inputStartingIndex
926
+ )
927
+ internal
928
+ pure
929
+ returns (
930
+ bytes32 outpointTxHash,
931
+ uint32 outpointIndex,
932
+ uint256 inputLength
933
+ )
934
+ {
935
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
936
+
937
+ outpointIndex = BTCUtils.reverseUint32(
938
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
939
+ );
940
+
941
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
942
+
943
+ return (outpointTxHash, outpointIndex, inputLength);
944
+ }
945
+
946
+ /// @notice Notifies about a timed out moved funds sweep process. If the
947
+ /// wallet is not terminated yet, that function terminates
948
+ /// the wallet and slashes signing group members as a result.
949
+ /// Marks the given sweep request as TimedOut.
950
+ /// @param movingFundsTxHash 32-byte hash of the moving funds transaction
951
+ /// that caused the sweep request to be created
952
+ /// @param movingFundsTxOutputIndex Index of the moving funds transaction
953
+ /// output that is subject of the sweep request.
954
+ /// @param walletMembersIDs Identifiers of the wallet signing group members
955
+ /// @dev Requirements:
956
+ /// - The moved funds sweep request must be in the Pending state
957
+ /// - The moved funds sweep timeout must be actually exceeded
958
+ /// - The wallet must be either in the Live or MovingFunds or
959
+ /// Terminated state
960
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
961
+ /// be exactly the same as the hash stored under `membersIdsHash`
962
+ /// for the given `walletID`. Those IDs are not directly stored
963
+ /// in the contract for gas efficiency purposes but they can be
964
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
965
+ /// events of the `WalletRegistry` contract
966
+ function notifyMovedFundsSweepTimeout(
967
+ BridgeState.Storage storage self,
968
+ bytes32 movingFundsTxHash,
969
+ uint32 movingFundsTxOutputIndex,
970
+ uint32[] calldata walletMembersIDs
971
+ ) external {
972
+ MovedFundsSweepRequest storage sweepRequest = self
973
+ .movedFundsSweepRequests[
974
+ uint256(
975
+ keccak256(
976
+ abi.encodePacked(
977
+ movingFundsTxHash,
978
+ movingFundsTxOutputIndex
979
+ )
980
+ )
981
+ )
982
+ ];
983
+
984
+ require(
985
+ sweepRequest.state == MovedFundsSweepRequestState.Pending,
986
+ "Sweep request must be in Pending state"
987
+ );
988
+
989
+ require(
990
+ /* solhint-disable-next-line not-rely-on-time */
991
+ block.timestamp >
992
+ sweepRequest.createdAt + self.movedFundsSweepTimeout,
993
+ "Sweep request has not timed out yet"
994
+ );
995
+
996
+ bytes20 walletPubKeyHash = sweepRequest.walletPubKeyHash;
997
+ Wallets.Wallet storage wallet = self.registeredWallets[
998
+ walletPubKeyHash
999
+ ];
1000
+ Wallets.WalletState walletState = wallet.state;
1001
+
1002
+ require(
1003
+ walletState == Wallets.WalletState.Live ||
1004
+ walletState == Wallets.WalletState.MovingFunds ||
1005
+ walletState == Wallets.WalletState.Terminated,
1006
+ "ECDSA wallet must be in Live or MovingFunds or Terminated state"
1007
+ );
1008
+
1009
+ sweepRequest.state = MovedFundsSweepRequestState.TimedOut;
1010
+ wallet.pendingMovedFundsSweepRequestsCount--;
1011
+
1012
+ if (
1013
+ walletState == Wallets.WalletState.Live ||
1014
+ walletState == Wallets.WalletState.MovingFunds
1015
+ ) {
1016
+ self.terminateWallet(walletPubKeyHash);
1017
+
1018
+ self.ecdsaWalletRegistry.seize(
1019
+ self.movedFundsSweepTimeoutSlashingAmount,
1020
+ self.movedFundsSweepTimeoutNotifierRewardMultiplier,
1021
+ msg.sender,
1022
+ wallet.ecdsaWalletID,
1023
+ walletMembersIDs
1024
+ );
1025
+ }
1026
+
1027
+ // slither-disable-next-line reentrancy-events
1028
+ emit MovedFundsSweepTimedOut(
1029
+ walletPubKeyHash,
1030
+ movingFundsTxHash,
1031
+ movingFundsTxOutputIndex
1032
+ );
1033
+ }
1034
+ }