@keep-network/tbtc-v2 0.1.1-dev.10 → 0.1.1-dev.102

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