@keep-network/tbtc-v2 0.1.1-dev.7 → 0.1.1-dev.72

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