@keep-network/tbtc-v2 0.1.1-dev.5 → 0.1.1-dev.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/Bank.json +752 -0
  3. package/artifacts/Bridge.json +3271 -0
  4. package/artifacts/Deposit.json +117 -0
  5. package/artifacts/EcdsaDkgValidator.json +532 -0
  6. package/artifacts/EcdsaInactivity.json +156 -0
  7. package/artifacts/Fraud.json +153 -0
  8. package/artifacts/KeepRegistry.json +99 -0
  9. package/artifacts/KeepStake.json +286 -0
  10. package/artifacts/KeepToken.json +711 -0
  11. package/artifacts/KeepTokenStaking.json +483 -0
  12. package/artifacts/MovingFunds.json +160 -0
  13. package/artifacts/NuCypherStakingEscrow.json +256 -0
  14. package/artifacts/NuCypherToken.json +711 -0
  15. package/artifacts/RandomBeaconStub.json +141 -0
  16. package/artifacts/Redemption.json +161 -0
  17. package/artifacts/ReimbursementPool.json +509 -0
  18. package/artifacts/Relay.json +123 -0
  19. package/artifacts/SortitionPool.json +944 -0
  20. package/artifacts/Sweep.json +76 -0
  21. package/artifacts/T.json +1148 -0
  22. package/artifacts/TBTC.json +27 -26
  23. package/artifacts/TBTCToken.json +27 -26
  24. package/artifacts/TokenStaking.json +2288 -0
  25. package/artifacts/TokenholderGovernor.json +1795 -0
  26. package/artifacts/TokenholderTimelock.json +1058 -0
  27. package/artifacts/VendingMachine.json +30 -29
  28. package/artifacts/VendingMachineKeep.json +400 -0
  29. package/artifacts/VendingMachineNuCypher.json +400 -0
  30. package/artifacts/WalletRegistry.json +2709 -0
  31. package/artifacts/WalletRegistryGovernance.json +2364 -0
  32. package/artifacts/Wallets.json +186 -0
  33. package/artifacts/solcInputs/b0c3ed0992bd570aaaee717425c37538.json +218 -0
  34. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  35. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  36. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  37. package/build/contracts/bank/Bank.sol/Bank.json +20 -2
  38. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  39. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  40. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  41. package/build/contracts/bridge/Bridge.sol/Bridge.json +2093 -77
  42. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  43. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +166 -0
  44. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  45. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  46. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  47. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  48. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  49. package/build/contracts/bridge/Fraud.sol/Fraud.json +86 -0
  50. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  51. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  52. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  53. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +81 -0
  54. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +4 -0
  55. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +10 -0
  56. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +4 -0
  57. package/build/contracts/bridge/Redemption.sol/Redemption.json +92 -0
  58. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
  59. package/build/contracts/bridge/Sweep.sol/Sweep.json +30 -0
  60. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  61. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  62. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  63. package/build/contracts/bridge/Wallets.sol/Wallets.json +112 -0
  64. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  65. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  66. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  67. package/build/contracts/vault/IVault.sol/IVault.json +19 -1
  68. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  69. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +36 -18
  70. package/contracts/GovernanceUtils.sol +1 -1
  71. package/contracts/bank/Bank.sol +34 -18
  72. package/contracts/bridge/BitcoinTx.sol +234 -0
  73. package/contracts/bridge/Bridge.sol +1274 -126
  74. package/contracts/bridge/BridgeState.sol +538 -0
  75. package/contracts/bridge/Deposit.sol +266 -0
  76. package/contracts/bridge/EcdsaLib.sol +45 -0
  77. package/contracts/bridge/Fraud.sol +488 -0
  78. package/contracts/bridge/IRelay.sol +28 -0
  79. package/contracts/bridge/MovingFunds.sol +511 -0
  80. package/contracts/bridge/Redemption.sol +846 -0
  81. package/contracts/bridge/Sweep.sol +514 -0
  82. package/contracts/bridge/VendingMachine.sol +1 -1
  83. package/contracts/bridge/Wallets.sol +551 -0
  84. package/contracts/token/TBTC.sol +1 -1
  85. package/contracts/vault/IVault.sol +32 -10
  86. package/contracts/vault/TBTCVault.sol +20 -2
  87. package/deploy/00_resolve_relay.ts +28 -0
  88. package/deploy/04_deploy_bank.ts +27 -0
  89. package/deploy/05_deploy_bridge.ts +64 -0
  90. package/deploy/06_bank_update_bridge.ts +19 -0
  91. package/deploy/07_transfer_ownership.ts +15 -0
  92. package/deploy/08_transfer_governance.ts +20 -0
  93. package/export.json +15173 -472
  94. package/package.json +27 -23
  95. package/artifacts/solcInputs/d71966212a658480bad5748ad85b1396.json +0 -116
@@ -0,0 +1,511 @@
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
+ library MovingFunds {
35
+ using BridgeState for BridgeState.Storage;
36
+ using Wallets for BridgeState.Storage;
37
+ using BitcoinTx for BridgeState.Storage;
38
+
39
+ using BTCUtils for bytes;
40
+ using BytesLib for bytes;
41
+
42
+ event MovingFundsCommitmentSubmitted(
43
+ bytes20 walletPubKeyHash,
44
+ bytes20[] targetWallets,
45
+ address submitter
46
+ );
47
+
48
+ event MovingFundsCompleted(
49
+ bytes20 walletPubKeyHash,
50
+ bytes32 movingFundsTxHash
51
+ );
52
+
53
+ event MovingFundsTimedOut(bytes20 walletPubKeyHash);
54
+
55
+ event MovingFundsBelowDustReported(bytes20 walletPubKeyHash);
56
+
57
+ /// @notice Submits the moving funds target wallets commitment.
58
+ /// Once all requirements are met, that function registers the
59
+ /// target wallets commitment and opens the way for moving funds
60
+ /// proof submission.
61
+ /// @param walletPubKeyHash 20-byte public key hash of the source wallet
62
+ /// @param walletMainUtxo Data of the source wallet's main UTXO, as
63
+ /// currently known on the Ethereum chain
64
+ /// @param walletMembersIDs Identifiers of the source wallet signing group
65
+ /// members
66
+ /// @param walletMemberIndex Position of the caller in the source wallet
67
+ /// signing group members list
68
+ /// @param targetWallets List of 20-byte public key hashes of the target
69
+ /// wallets that the source wallet commits to move the funds to
70
+ /// @dev Requirements:
71
+ /// - The source wallet must be in the MovingFunds state
72
+ /// - The source wallet must not have pending redemption requests
73
+ /// - The source wallet must not have submitted its commitment already
74
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
75
+ /// be exactly the same as the hash stored under `membersIdsHash`
76
+ /// for the given source wallet in the ECDSA registry. Those IDs are
77
+ /// not directly stored in the contract for gas efficiency purposes
78
+ /// but they can be read from appropriate `DkgResultSubmitted`
79
+ /// and `DkgResultApproved` events.
80
+ /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length]
81
+ /// - The caller must be the member of the source wallet signing group
82
+ /// at the position indicated by `walletMemberIndex` parameter
83
+ /// - The `walletMainUtxo` components must point to the recent main
84
+ /// UTXO of the source wallet, as currently known on the Ethereum
85
+ /// chain.
86
+ /// - Source wallet BTC balance must be greater than zero
87
+ /// - At least one Live wallet must exist in the system
88
+ /// - Submitted target wallets count must match the expected count
89
+ /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`
90
+ /// where `N > 0`
91
+ /// - Each target wallet must be not equal to the source wallet
92
+ /// - Each target wallet must follow the expected order i.e. all
93
+ /// target wallets 20-byte public key hashes represented as numbers
94
+ /// must form a strictly increasing sequence without duplicates.
95
+ /// - Each target wallet must be in Live state
96
+ function submitMovingFundsCommitment(
97
+ BridgeState.Storage storage self,
98
+ bytes20 walletPubKeyHash,
99
+ BitcoinTx.UTXO calldata walletMainUtxo,
100
+ uint32[] calldata walletMembersIDs,
101
+ uint256 walletMemberIndex,
102
+ bytes20[] calldata targetWallets
103
+ ) external {
104
+ Wallets.Wallet storage wallet = self.registeredWallets[
105
+ walletPubKeyHash
106
+ ];
107
+
108
+ require(
109
+ wallet.state == Wallets.WalletState.MovingFunds,
110
+ "Source wallet must be in MovingFunds state"
111
+ );
112
+
113
+ require(
114
+ wallet.pendingRedemptionsValue == 0,
115
+ "Source wallet must handle all pending redemptions first"
116
+ );
117
+
118
+ require(
119
+ wallet.movingFundsTargetWalletsCommitmentHash == bytes32(0),
120
+ "Target wallets commitment already submitted"
121
+ );
122
+
123
+ require(
124
+ self.ecdsaWalletRegistry.isWalletMember(
125
+ wallet.ecdsaWalletID,
126
+ walletMembersIDs,
127
+ msg.sender,
128
+ walletMemberIndex
129
+ ),
130
+ "Caller is not a member of the source wallet"
131
+ );
132
+
133
+ uint64 walletBtcBalance = self.getWalletBtcBalance(
134
+ walletPubKeyHash,
135
+ walletMainUtxo
136
+ );
137
+
138
+ require(walletBtcBalance > 0, "Wallet BTC balance is zero");
139
+
140
+ uint256 expectedTargetWalletsCount = Math.min(
141
+ self.liveWalletsCount,
142
+ Math.ceilDiv(walletBtcBalance, self.walletMaxBtcTransfer)
143
+ );
144
+
145
+ // This requirement fails only when `liveWalletsCount` is zero. In
146
+ // that case, the system cannot accept the commitment and must provide
147
+ // new wallets first.
148
+ //
149
+ // TODO: Expose separate function to reset the moving funds timeout
150
+ // if no Live wallets exist in the system.
151
+ require(expectedTargetWalletsCount > 0, "No target wallets available");
152
+
153
+ require(
154
+ targetWallets.length == expectedTargetWalletsCount,
155
+ "Submitted target wallets count is other than expected"
156
+ );
157
+
158
+ uint160 lastProcessedTargetWallet = 0;
159
+
160
+ for (uint256 i = 0; i < targetWallets.length; i++) {
161
+ bytes20 targetWallet = targetWallets[i];
162
+
163
+ require(
164
+ targetWallet != walletPubKeyHash,
165
+ "Submitted target wallet cannot be equal to the source wallet"
166
+ );
167
+
168
+ require(
169
+ uint160(targetWallet) > lastProcessedTargetWallet,
170
+ "Submitted target wallet breaks the expected order"
171
+ );
172
+
173
+ require(
174
+ self.registeredWallets[targetWallet].state ==
175
+ Wallets.WalletState.Live,
176
+ "Submitted target wallet must be in Live state"
177
+ );
178
+
179
+ lastProcessedTargetWallet = uint160(targetWallet);
180
+ }
181
+
182
+ wallet.movingFundsTargetWalletsCommitmentHash = keccak256(
183
+ abi.encodePacked(targetWallets)
184
+ );
185
+
186
+ emit MovingFundsCommitmentSubmitted(
187
+ walletPubKeyHash,
188
+ targetWallets,
189
+ msg.sender
190
+ );
191
+ }
192
+
193
+ /// @notice Used by the wallet to prove the BTC moving funds transaction
194
+ /// and to make the necessary state changes. Moving funds is only
195
+ /// accepted if it satisfies SPV proof.
196
+ ///
197
+ /// The function validates the moving funds transaction structure
198
+ /// by checking if it actually spends the main UTXO of the declared
199
+ /// wallet and locks the value on the pre-committed target wallets
200
+ /// using a reasonable transaction fee. If all preconditions are
201
+ /// met, this functions closes the source wallet.
202
+ ///
203
+ /// It is possible to prove the given moving funds transaction only
204
+ /// one time.
205
+ /// @param movingFundsTx Bitcoin moving funds transaction data
206
+ /// @param movingFundsProof Bitcoin moving funds proof data
207
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
208
+ /// the Ethereum chain
209
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
210
+ /// HASH160 over the compressed ECDSA public key) of the wallet
211
+ /// which performed the moving funds transaction
212
+ /// @dev Requirements:
213
+ /// - `movingFundsTx` components must match the expected structure. See
214
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
215
+ /// correspond to appropriate Bitcoin transaction fields to produce
216
+ /// a provable transaction hash.
217
+ /// - The `movingFundsTx` should represent a Bitcoin transaction with
218
+ /// exactly 1 input that refers to the wallet's main UTXO. That
219
+ /// transaction should have 1..n outputs corresponding to the
220
+ /// pre-committed target wallets. Outputs must be ordered in the
221
+ /// same way as their corresponding target wallets are ordered
222
+ /// within the target wallets commitment.
223
+ /// - `movingFundsProof` components must match the expected structure.
224
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
225
+ /// field must contain a valid number of block headers, not less
226
+ /// than the `txProofDifficultyFactor` contract constant.
227
+ /// - `mainUtxo` components must point to the recent main UTXO
228
+ /// of the given wallet, as currently known on the Ethereum chain.
229
+ /// Additionally, the recent main UTXO on Ethereum must be set.
230
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
231
+ /// as transaction single input.
232
+ /// - The wallet that `walletPubKeyHash` points to must be in the
233
+ /// MovingFunds state.
234
+ /// - The target wallets commitment must be submitted by the wallet
235
+ /// that `walletPubKeyHash` points to.
236
+ /// - The total Bitcoin transaction fee must be lesser or equal
237
+ /// to `movingFundsTxMaxTotalFee` governable parameter.
238
+ function submitMovingFundsProof(
239
+ BridgeState.Storage storage self,
240
+ BitcoinTx.Info calldata movingFundsTx,
241
+ BitcoinTx.Proof calldata movingFundsProof,
242
+ BitcoinTx.UTXO calldata mainUtxo,
243
+ bytes20 walletPubKeyHash
244
+ ) external {
245
+ // The actual transaction proof is performed here. After that point, we
246
+ // can assume the transaction happened on Bitcoin chain and has
247
+ // a sufficient number of confirmations as determined by
248
+ // `txProofDifficultyFactor` constant.
249
+ bytes32 movingFundsTxHash = self.validateProof(
250
+ movingFundsTx,
251
+ movingFundsProof
252
+ );
253
+
254
+ // Process the moving funds transaction input. Specifically, check if
255
+ // it refers to the expected wallet's main UTXO.
256
+ OutboundTx.processWalletOutboundTxInput(
257
+ self,
258
+ movingFundsTx.inputVector,
259
+ mainUtxo,
260
+ walletPubKeyHash
261
+ );
262
+
263
+ (
264
+ bytes32 targetWalletsHash,
265
+ uint256 outputsTotalValue
266
+ ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);
267
+
268
+ require(
269
+ mainUtxo.txOutputValue - outputsTotalValue <=
270
+ self.movingFundsTxMaxTotalFee,
271
+ "Transaction fee is too high"
272
+ );
273
+
274
+ self.notifyWalletFundsMoved(walletPubKeyHash, targetWalletsHash);
275
+ // slither-disable-next-line reentrancy-events
276
+ emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);
277
+ }
278
+
279
+ /// @notice Processes the moving funds Bitcoin transaction output vector
280
+ /// and extracts information required for further processing.
281
+ /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output
282
+ /// vector. This function assumes vector's structure is valid so it
283
+ /// must be validated using e.g. `BTCUtils.validateVout` function
284
+ /// before it is passed here
285
+ /// @return targetWalletsHash keccak256 hash over the list of actual
286
+ /// target wallets used in the transaction.
287
+ /// @return outputsTotalValue Sum of all outputs values.
288
+ /// @dev Requirements:
289
+ /// - The `movingFundsTxOutputVector` must be parseable, i.e. must
290
+ /// be validated by the caller as stated in their parameter doc.
291
+ /// - Each output must refer to a 20-byte public key hash.
292
+ /// - The total outputs value must be evenly divided over all outputs.
293
+ function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)
294
+ internal
295
+ pure
296
+ returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)
297
+ {
298
+ // Determining the total number of Bitcoin transaction outputs in
299
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
300
+ // docs for more details.
301
+ (
302
+ uint256 outputsCompactSizeUintLength,
303
+ uint256 outputsCount
304
+ ) = movingFundsTxOutputVector.parseVarInt();
305
+
306
+ // To determine the first output starting index, we must jump over
307
+ // the compactSize uint which prepends the output vector. One byte
308
+ // must be added because `BtcUtils.parseVarInt` does not include
309
+ // compactSize uint tag in the returned length.
310
+ //
311
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
312
+ // returns `0`, so we jump over one byte of compactSize uint.
313
+ //
314
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
315
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
316
+ // tag byte included) so we need to jump over 1+2 bytes of
317
+ // compactSize uint.
318
+ //
319
+ // Please refer `BTCUtils` library and compactSize uint
320
+ // docs in `BitcoinTx` library for more details.
321
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
322
+
323
+ bytes20[] memory targetWallets = new bytes20[](outputsCount);
324
+ uint64[] memory outputsValues = new uint64[](outputsCount);
325
+
326
+ // Outputs processing loop.
327
+ for (uint256 i = 0; i < outputsCount; i++) {
328
+ uint256 outputLength = movingFundsTxOutputVector
329
+ .determineOutputLengthAt(outputStartingIndex);
330
+
331
+ bytes memory output = movingFundsTxOutputVector.slice(
332
+ outputStartingIndex,
333
+ outputLength
334
+ );
335
+
336
+ // Extract the output script payload.
337
+ bytes memory targetWalletPubKeyHashBytes = output.extractHash();
338
+ // Output script payload must refer to a known wallet public key
339
+ // hash which is always 20-byte.
340
+ require(
341
+ targetWalletPubKeyHashBytes.length == 20,
342
+ "Target wallet public key hash must have 20 bytes"
343
+ );
344
+
345
+ bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes
346
+ .slice20(0);
347
+
348
+ // The next step is making sure that the 20-byte public key hash
349
+ // is actually used in the right context of a P2PKH or P2WPKH
350
+ // output. To do so, we must extract the full script from the output
351
+ // and compare with the expected P2PKH and P2WPKH scripts
352
+ // referring to that 20-byte public key hash. The output consists
353
+ // of an 8-byte value and a variable length script. To extract the
354
+ // script we slice the output starting from 9th byte until the end.
355
+ bytes32 outputScriptKeccak = keccak256(
356
+ output.slice(8, output.length - 8)
357
+ );
358
+ // Build the expected P2PKH script which has the following byte
359
+ // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to
360
+ // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
361
+ // - 0x19: Byte length of the entire script
362
+ // - 0x76: OP_DUP
363
+ // - 0xa9: OP_HASH160
364
+ // - 0x14: Byte length of the public key hash
365
+ // - 0x88: OP_EQUALVERIFY
366
+ // - 0xac: OP_CHECKSIG
367
+ // which matches the P2PKH structure as per:
368
+ // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
369
+ bytes32 targetWalletP2PKHScriptKeccak = keccak256(
370
+ abi.encodePacked(
371
+ hex"1976a914",
372
+ targetWalletPubKeyHash,
373
+ hex"88ac"
374
+ )
375
+ );
376
+ // Build the expected P2WPKH script which has the following format:
377
+ // <0x160014> <20-byte PKH>. According to
378
+ // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
379
+ // - 0x16: Byte length of the entire script
380
+ // - 0x00: OP_0
381
+ // - 0x14: Byte length of the public key hash
382
+ // which matches the P2WPKH structure as per:
383
+ // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
384
+ bytes32 targetWalletP2WPKHScriptKeccak = keccak256(
385
+ abi.encodePacked(hex"160014", targetWalletPubKeyHash)
386
+ );
387
+ // Make sure the actual output script matches either the P2PKH
388
+ // or P2WPKH format.
389
+ require(
390
+ outputScriptKeccak == targetWalletP2PKHScriptKeccak ||
391
+ outputScriptKeccak == targetWalletP2WPKHScriptKeccak,
392
+ "Output must be P2PKH or P2WPKH"
393
+ );
394
+
395
+ // Add the wallet public key hash to the list that will be used
396
+ // to build the result list hash. There is no need to check if
397
+ // given output is a change here because the actual target wallet
398
+ // list must be exactly the same as the pre-committed target wallet
399
+ // list which is guaranteed to be valid.
400
+ targetWallets[i] = targetWalletPubKeyHash;
401
+
402
+ // Extract the value from given output.
403
+ outputsValues[i] = output.extractValue();
404
+ outputsTotalValue += outputsValues[i];
405
+
406
+ // Make the `outputStartingIndex` pointing to the next output by
407
+ // increasing it by current output's length.
408
+ outputStartingIndex += outputLength;
409
+ }
410
+
411
+ // Compute the indivisible remainder that remains after dividing the
412
+ // outputs total value over all outputs evenly.
413
+ uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;
414
+ // Compute the minimum allowed output value by dividing the outputs
415
+ // total value (reduced by the remainder) by the number of outputs.
416
+ uint256 minOutputValue = (outputsTotalValue -
417
+ outputsTotalValueRemainder) / outputsCount;
418
+ // Maximum possible value is the minimum value with the remainder included.
419
+ uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;
420
+
421
+ for (uint256 i = 0; i < outputsCount; i++) {
422
+ require(
423
+ minOutputValue <= outputsValues[i] &&
424
+ outputsValues[i] <= maxOutputValue,
425
+ "Transaction amount is not distributed evenly"
426
+ );
427
+ }
428
+
429
+ targetWalletsHash = keccak256(abi.encodePacked(targetWallets));
430
+
431
+ return (targetWalletsHash, outputsTotalValue);
432
+ }
433
+
434
+ /// @notice Notifies about a timed out moving funds process. Terminates
435
+ /// the wallet and slashes signing group members as a result.
436
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
437
+ /// @dev Requirements:
438
+ /// - The wallet must be in the MovingFunds state
439
+ /// - The moving funds timeout must be actually exceeded
440
+ function notifyMovingFundsTimeout(
441
+ BridgeState.Storage storage self,
442
+ bytes20 walletPubKeyHash
443
+ ) external {
444
+ Wallets.Wallet storage wallet = self.registeredWallets[
445
+ walletPubKeyHash
446
+ ];
447
+
448
+ require(
449
+ wallet.state == Wallets.WalletState.MovingFunds,
450
+ "ECDSA wallet must be in MovingFunds state"
451
+ );
452
+
453
+ require(
454
+ /* solhint-disable-next-line not-rely-on-time */
455
+ block.timestamp >
456
+ wallet.movingFundsRequestedAt + self.movingFundsTimeout,
457
+ "Moving funds has not timed out yet"
458
+ );
459
+
460
+ self.terminateWallet(walletPubKeyHash);
461
+
462
+ // TODO: Perform slashing of wallet operators, reward the notifier
463
+ // using seized amount, and add unit tests for that.
464
+
465
+ // slither-disable-next-line reentrancy-events
466
+ emit MovingFundsTimedOut(walletPubKeyHash);
467
+ }
468
+
469
+ /// @notice Notifies about a moving funds wallet whose BTC balance is
470
+ /// below the moving funds dust threshold. Ends the moving funds
471
+ /// process and begins wallet closing immediately.
472
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
473
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known
474
+ /// on the Ethereum chain.
475
+ /// @dev Requirements:
476
+ /// - The wallet must be in the MovingFunds state
477
+ /// - The `mainUtxo` components must point to the recent main UTXO
478
+ /// of the given wallet, as currently known on the Ethereum chain.
479
+ /// If the wallet has no main UTXO, this parameter can be empty as it
480
+ /// is ignored.
481
+ /// - The wallet BTC balance must be below the moving funds threshold
482
+ function notifyMovingFundsBelowDust(
483
+ BridgeState.Storage storage self,
484
+ bytes20 walletPubKeyHash,
485
+ BitcoinTx.UTXO calldata mainUtxo
486
+ ) external {
487
+ Wallets.Wallet storage wallet = self.registeredWallets[
488
+ walletPubKeyHash
489
+ ];
490
+
491
+ require(
492
+ wallet.state == Wallets.WalletState.MovingFunds,
493
+ "ECDSA wallet must be in MovingFunds state"
494
+ );
495
+
496
+ uint64 walletBtcBalance = self.getWalletBtcBalance(
497
+ walletPubKeyHash,
498
+ mainUtxo
499
+ );
500
+
501
+ require(
502
+ walletBtcBalance < self.movingFundsDustThreshold,
503
+ "Wallet BTC balance must be below the moving funds dust threshold"
504
+ );
505
+
506
+ self.beginWalletClosing(walletPubKeyHash);
507
+
508
+ // slither-disable-next-line reentrancy-events
509
+ emit MovingFundsBelowDustReported(walletPubKeyHash);
510
+ }
511
+ }