@keep-network/tbtc-v2 0.1.1-dev.4 → 0.1.1-dev.40

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 (60) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/TBTC.json +19 -18
  3. package/artifacts/TBTCToken.json +19 -18
  4. package/artifacts/VendingMachine.json +20 -19
  5. package/artifacts/solcInputs/f1a50b67569d88ee54efa3e22c6b484e.json +215 -0
  6. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  7. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  8. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  9. package/build/contracts/bank/Bank.sol/Bank.json +20 -2
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  11. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  12. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  13. package/build/contracts/bridge/Bridge.sol/Bridge.json +1743 -64
  14. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  15. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +10 -0
  16. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  17. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  18. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  19. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  20. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +4 -0
  21. package/build/contracts/bridge/Frauds.sol/Frauds.json +138 -0
  22. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  23. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  24. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  25. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +48 -0
  26. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  27. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  28. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  29. package/build/contracts/bridge/Redeem.sol/Redeem.json +110 -0
  30. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
  31. package/build/contracts/bridge/Sweep.sol/Sweep.json +30 -0
  32. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  33. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  34. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  35. package/build/contracts/bridge/Wallets.sol/Wallets.json +138 -0
  36. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  37. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  38. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  39. package/build/contracts/vault/IVault.sol/IVault.json +19 -1
  40. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  41. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +36 -18
  42. package/contracts/GovernanceUtils.sol +1 -1
  43. package/contracts/bank/Bank.sol +34 -18
  44. package/contracts/bridge/BitcoinTx.sol +241 -0
  45. package/contracts/bridge/Bridge.sol +980 -123
  46. package/contracts/bridge/BridgeState.sol +172 -0
  47. package/contracts/bridge/Deposit.sol +247 -0
  48. package/contracts/bridge/EcdsaLib.sol +30 -0
  49. package/contracts/bridge/Frauds.sol +529 -0
  50. package/contracts/bridge/IRelay.sol +28 -0
  51. package/contracts/bridge/MovingFunds.sol +280 -0
  52. package/contracts/bridge/Redeem.sol +849 -0
  53. package/contracts/bridge/Sweep.sol +510 -0
  54. package/contracts/bridge/VendingMachine.sol +1 -1
  55. package/contracts/bridge/Wallets.sol +591 -0
  56. package/contracts/token/TBTC.sol +1 -1
  57. package/contracts/vault/IVault.sol +32 -10
  58. package/contracts/vault/TBTCVault.sol +20 -2
  59. package/package.json +28 -24
  60. package/artifacts/solcInputs/d71966212a658480bad5748ad85b1396.json +0 -116
@@ -0,0 +1,591 @@
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 {IWalletRegistry as EcdsaWalletRegistry} from "@keep-network/ecdsa/contracts/api/IWalletRegistry.sol";
20
+ import {EcdsaDkg} from "@keep-network/ecdsa/contracts/libraries/EcdsaDkg.sol";
21
+
22
+ import "./BitcoinTx.sol";
23
+ import "./EcdsaLib.sol";
24
+
25
+ /// @title Wallet library
26
+ /// @notice Library responsible for handling integration between Bridge
27
+ /// contract and ECDSA wallets.
28
+ library Wallets {
29
+ using BTCUtils for bytes;
30
+
31
+ /// @notice Struct that groups the state managed by the library.
32
+ struct Data {
33
+ // ECDSA Wallet Registry contract handle.
34
+ EcdsaWalletRegistry registry;
35
+ // Determines how frequently a new wallet creation can be requested.
36
+ // Value in seconds.
37
+ uint32 creationPeriod;
38
+ // The minimum BTC threshold in satoshi that is used to decide about
39
+ // wallet creation or closing.
40
+ uint64 minBtcBalance;
41
+ // The maximum BTC threshold in satoshi that is used to decide about
42
+ // wallet creation.
43
+ uint64 maxBtcBalance;
44
+ // The maximum age of a wallet in seconds, after which the wallet
45
+ // moving funds process can be requested.
46
+ uint32 maxAge;
47
+ // 20-byte wallet public key hash being reference to the currently
48
+ // active wallet. Can be unset to the zero value under certain
49
+ // circumstances.
50
+ bytes20 activeWalletPubKeyHash;
51
+ // Maps the 20-byte wallet public key hash (computed using Bitcoin
52
+ // HASH160 over the compressed ECDSA public key) to the basic wallet
53
+ // information like state and pending redemptions value.
54
+ mapping(bytes20 => Wallet) registeredWallets;
55
+ }
56
+
57
+ /// @notice Represents wallet state:
58
+ enum WalletState {
59
+ /// @dev The wallet is unknown to the Bridge.
60
+ Unknown,
61
+ /// @dev The wallet can sweep deposits and accept redemption requests.
62
+ Live,
63
+ /// @dev The wallet was deemed unhealthy and is expected to move their
64
+ /// outstanding funds to another wallet. The wallet can still
65
+ /// fulfill their pending redemption requests although new
66
+ /// redemption requests and new deposit reveals are not accepted.
67
+ MovingFunds,
68
+ /// @dev The wallet moved or redeemed all their funds and cannot
69
+ /// perform any action.
70
+ Closed,
71
+ /// @dev The wallet committed a fraud that was reported. The wallet is
72
+ /// blocked and can not perform any actions in the Bridge.
73
+ /// Off-chain coordination with the wallet operators is needed to
74
+ /// recover funds.
75
+ Terminated
76
+ }
77
+
78
+ /// @notice Holds information about a wallet.
79
+ struct Wallet {
80
+ // Identifier of a ECDSA Wallet registered in the ECDSA Wallet Registry.
81
+ bytes32 ecdsaWalletID;
82
+ // Latest wallet's main UTXO hash computed as
83
+ // keccak256(txHash | txOutputIndex | txOutputValue). The `tx` prefix
84
+ // refers to the transaction which created that main UTXO. The `txHash`
85
+ // is `bytes32` (ordered as in Bitcoin internally), `txOutputIndex`
86
+ // an `uint32`, and `txOutputValue` an `uint64` value.
87
+ bytes32 mainUtxoHash;
88
+ // The total redeemable value of pending redemption requests targeting
89
+ // that wallet.
90
+ uint64 pendingRedemptionsValue;
91
+ // UNIX timestamp the wallet was created at.
92
+ uint32 createdAt;
93
+ // UNIX timestamp indicating the moment the wallet was requested to
94
+ // move their funds.
95
+ uint32 movingFundsRequestedAt;
96
+ // Current state of the wallet.
97
+ WalletState state;
98
+ // Moving funds target wallet commitment submitted by the wallet. It
99
+ // is built by applying the keccak256 hash over the list of 20-byte
100
+ // public key hashes of the target wallets.
101
+ bytes32 movingFundsTargetWalletsCommitmentHash;
102
+ }
103
+
104
+ event WalletCreationPeriodUpdated(uint32 newCreationPeriod);
105
+
106
+ event WalletBtcBalanceRangeUpdated(
107
+ uint64 newMinBtcBalance,
108
+ uint64 newMaxBtcBalance
109
+ );
110
+
111
+ event WalletMaxAgeUpdated(uint32 newMaxAge);
112
+
113
+ event NewWalletRequested();
114
+
115
+ event NewWalletRegistered(
116
+ bytes32 indexed ecdsaWalletID,
117
+ bytes20 indexed walletPubKeyHash
118
+ );
119
+
120
+ event WalletMovingFunds(
121
+ bytes32 indexed ecdsaWalletID,
122
+ bytes20 indexed walletPubKeyHash
123
+ );
124
+
125
+ event WalletClosed(
126
+ bytes32 indexed ecdsaWalletID,
127
+ bytes20 indexed walletPubKeyHash
128
+ );
129
+
130
+ event WalletTerminated(
131
+ bytes32 indexed ecdsaWalletID,
132
+ bytes20 indexed walletPubKeyHash
133
+ );
134
+
135
+ /// @notice Initializes state invariants.
136
+ /// @param registry ECDSA Wallet Registry reference
137
+ /// @dev Requirements:
138
+ /// - ECDSA Wallet Registry address must not be initialized
139
+ function init(Data storage self, address registry) external {
140
+ require(
141
+ registry != address(0),
142
+ "ECDSA Wallet Registry address cannot be zero"
143
+ );
144
+ require(
145
+ address(self.registry) == address(0),
146
+ "ECDSA Wallet Registry address already set"
147
+ );
148
+
149
+ self.registry = EcdsaWalletRegistry(registry);
150
+ }
151
+
152
+ /// @notice Sets the wallet creation period.
153
+ /// @param creationPeriod New value of the wallet creation period
154
+ function setCreationPeriod(Data storage self, uint32 creationPeriod)
155
+ external
156
+ {
157
+ self.creationPeriod = creationPeriod;
158
+
159
+ emit WalletCreationPeriodUpdated(creationPeriod);
160
+ }
161
+
162
+ /// @notice Sets the minimum and maximum BTC balance parameters.
163
+ /// @param minBtcBalance New value of the minimum BTC balance
164
+ /// @param maxBtcBalance New value of the maximum BTC balance
165
+ /// @dev Requirements:
166
+ /// - Minimum BTC balance must be greater than zero
167
+ /// - Maximum BTC balance must be greater than minimum BTC balance
168
+ function setBtcBalanceRange(
169
+ Data storage self,
170
+ uint64 minBtcBalance,
171
+ uint64 maxBtcBalance
172
+ ) external {
173
+ require(minBtcBalance > 0, "Minimum must be greater than zero");
174
+ require(
175
+ maxBtcBalance > minBtcBalance,
176
+ "Maximum must be greater than the minimum"
177
+ );
178
+
179
+ self.minBtcBalance = minBtcBalance;
180
+ self.maxBtcBalance = maxBtcBalance;
181
+
182
+ emit WalletBtcBalanceRangeUpdated(minBtcBalance, maxBtcBalance);
183
+ }
184
+
185
+ /// @notice Sets the wallet maximum age.
186
+ /// @param maxAge New value of the wallet maximum age
187
+ function setMaxAge(Data storage self, uint32 maxAge) external {
188
+ self.maxAge = maxAge;
189
+
190
+ emit WalletMaxAgeUpdated(maxAge);
191
+ }
192
+
193
+ /// @notice Requests creation of a new wallet. This function just
194
+ /// forms a request and the creation process is performed
195
+ /// asynchronously. Outcome of that process should be delivered
196
+ /// using `registerNewWallet` function.
197
+ /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as
198
+ /// currently known on the Ethereum chain.
199
+ /// @dev Requirements:
200
+ /// - `activeWalletMainUtxo` components must point to the recent main
201
+ /// UTXO of the given active wallet, as currently known on the
202
+ /// Ethereum chain. If there is no active wallet at the moment, or
203
+ /// the active wallet has no main UTXO, this parameter can be
204
+ /// empty as it is ignored.
205
+ /// - Wallet creation must not be in progress
206
+ /// - If the active wallet is set, one of the following
207
+ /// conditions must be true:
208
+ /// - The active wallet BTC balance is above the minimum threshold
209
+ /// and the active wallet is old enough, i.e. the creation period
210
+ /// was elapsed since its creation time
211
+ /// - The active wallet BTC balance is above the maximum threshold
212
+ function requestNewWallet(
213
+ Data storage self,
214
+ BitcoinTx.UTXO calldata activeWalletMainUtxo
215
+ ) external {
216
+ require(
217
+ self.registry.getWalletCreationState() == EcdsaDkg.State.IDLE,
218
+ "Wallet creation already in progress"
219
+ );
220
+
221
+ bytes20 activeWalletPubKeyHash = self.activeWalletPubKeyHash;
222
+
223
+ // If the active wallet is set, fetch this wallet's details from
224
+ // storage to perform conditions check. The `registerNewWallet`
225
+ // function guarantees an active wallet is always one of the
226
+ // registered ones.
227
+ if (activeWalletPubKeyHash != bytes20(0)) {
228
+ uint64 activeWalletBtcBalance = getWalletBtcBalance(
229
+ self,
230
+ activeWalletPubKeyHash,
231
+ activeWalletMainUtxo
232
+ );
233
+ uint32 activeWalletCreatedAt = self
234
+ .registeredWallets[activeWalletPubKeyHash]
235
+ .createdAt;
236
+ /* solhint-disable-next-line not-rely-on-time */
237
+ bool activeWalletOldEnough = block.timestamp >=
238
+ activeWalletCreatedAt + self.creationPeriod;
239
+
240
+ require(
241
+ (activeWalletOldEnough &&
242
+ activeWalletBtcBalance >= self.minBtcBalance) ||
243
+ activeWalletBtcBalance >= self.maxBtcBalance,
244
+ "Wallet creation conditions are not met"
245
+ );
246
+ }
247
+
248
+ emit NewWalletRequested();
249
+
250
+ self.registry.requestNewWallet();
251
+ }
252
+
253
+ /// @notice Gets BTC balance for given the wallet.
254
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
255
+ /// @param walletMainUtxo Data of the wallet's main UTXO, as currently
256
+ /// known on the Ethereum chain.
257
+ /// @return walletBtcBalance Current BTC balance for the given wallet.
258
+ /// @dev Requirements:
259
+ /// - `walletMainUtxo` components must point to the recent main UTXO
260
+ /// of the given wallet, as currently known on the Ethereum chain.
261
+ /// If the wallet has no main UTXO, this parameter can be empty as it
262
+ /// is ignored.
263
+ function getWalletBtcBalance(
264
+ Data storage self,
265
+ bytes20 walletPubKeyHash,
266
+ BitcoinTx.UTXO calldata walletMainUtxo
267
+ ) internal view returns (uint64 walletBtcBalance) {
268
+ bytes32 walletMainUtxoHash = self
269
+ .registeredWallets[walletPubKeyHash]
270
+ .mainUtxoHash;
271
+
272
+ // If the wallet has a main UTXO hash set, cross-check it with the
273
+ // provided plain-text parameter and get the transaction output value
274
+ // as BTC balance. Otherwise, the BTC balance is just zero.
275
+ if (walletMainUtxoHash != bytes32(0)) {
276
+ require(
277
+ keccak256(
278
+ abi.encodePacked(
279
+ walletMainUtxo.txHash,
280
+ walletMainUtxo.txOutputIndex,
281
+ walletMainUtxo.txOutputValue
282
+ )
283
+ ) == walletMainUtxoHash,
284
+ "Invalid wallet main UTXO data"
285
+ );
286
+
287
+ walletBtcBalance = walletMainUtxo.txOutputValue;
288
+ }
289
+
290
+ return walletBtcBalance;
291
+ }
292
+
293
+ /// @notice Registers a new wallet. This function should be called
294
+ /// after the wallet creation process initiated using
295
+ /// `requestNewWallet` completes and brings the outcomes.
296
+ /// @param ecdsaWalletID Wallet's unique identifier.
297
+ /// @param publicKeyX Wallet's public key's X coordinate.
298
+ /// @param publicKeyY Wallet's public key's Y coordinate.
299
+ /// @dev Requirements:
300
+ /// - The only caller authorized to call this function is `registry`
301
+ /// - Given wallet data must not belong to an already registered wallet
302
+ function registerNewWallet(
303
+ Data storage self,
304
+ bytes32 ecdsaWalletID,
305
+ bytes32 publicKeyX,
306
+ bytes32 publicKeyY
307
+ ) external {
308
+ require(
309
+ msg.sender == address(self.registry),
310
+ "Caller is not the ECDSA Wallet Registry"
311
+ );
312
+
313
+ // Compress wallet's public key and calculate Bitcoin's hash160 of it.
314
+ bytes20 walletPubKeyHash = bytes20(
315
+ EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()
316
+ );
317
+
318
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
319
+ require(
320
+ wallet.state == WalletState.Unknown,
321
+ "ECDSA wallet has been already registered"
322
+ );
323
+ wallet.ecdsaWalletID = ecdsaWalletID;
324
+ wallet.state = WalletState.Live;
325
+ /* solhint-disable-next-line not-rely-on-time */
326
+ wallet.createdAt = uint32(block.timestamp);
327
+
328
+ // Set the freshly created wallet as the new active wallet.
329
+ self.activeWalletPubKeyHash = walletPubKeyHash;
330
+
331
+ emit NewWalletRegistered(ecdsaWalletID, walletPubKeyHash);
332
+ }
333
+
334
+ /// @notice Handles a notification about a wallet heartbeat failure and
335
+ /// triggers the wallet moving funds process.
336
+ /// @param publicKeyX Wallet's public key's X coordinate.
337
+ /// @param publicKeyY Wallet's public key's Y coordinate.
338
+ /// @dev Requirements:
339
+ /// - The only caller authorized to call this function is `registry`
340
+ /// - Wallet must be in Live state
341
+ function notifyWalletHeartbeatFailed(
342
+ Data storage self,
343
+ bytes32 publicKeyX,
344
+ bytes32 publicKeyY
345
+ ) external {
346
+ require(
347
+ msg.sender == address(self.registry),
348
+ "Caller is not the ECDSA Wallet Registry"
349
+ );
350
+
351
+ // Compress wallet's public key and calculate Bitcoin's hash160 of it.
352
+ bytes20 walletPubKeyHash = bytes20(
353
+ EcdsaLib.compressPublicKey(publicKeyX, publicKeyY).hash160View()
354
+ );
355
+
356
+ require(
357
+ self.registeredWallets[walletPubKeyHash].state == WalletState.Live,
358
+ "ECDSA wallet must be in Live state"
359
+ );
360
+
361
+ moveFunds(self, walletPubKeyHash);
362
+ }
363
+
364
+ /// @notice Handles a notification about a wallet redemption timeout
365
+ /// and requests slashing of the wallet operators. Triggers the
366
+ /// wallet moving funds process only if the wallet is still in the
367
+ /// Live state. That means multiple action timeouts can be reported
368
+ /// for the same wallet but only the first report requests the
369
+ /// wallet to move their funds.
370
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
371
+ /// @dev Requirements:
372
+ /// - The wallet must be in the `Live` or `MovingFunds` state
373
+ function notifyRedemptionTimedOut(
374
+ Data storage self,
375
+ bytes20 walletPubKeyHash
376
+ ) external {
377
+ WalletState walletState = self
378
+ .registeredWallets[walletPubKeyHash]
379
+ .state;
380
+
381
+ require(
382
+ walletState == WalletState.Live ||
383
+ walletState == WalletState.MovingFunds,
384
+ "ECDSA wallet must be in Live or MovingFunds state"
385
+ );
386
+
387
+ if (walletState == WalletState.Live) {
388
+ moveFunds(self, walletPubKeyHash);
389
+ }
390
+
391
+ // TODO: Perform slashing of wallet operators and transfer some of the
392
+ // slashed tokens to the caller of this function.
393
+ }
394
+
395
+ /// @notice Notifies that the wallet is either old enough or has too few
396
+ /// satoshis left and qualifies to be closed.
397
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
398
+ /// @param walletMainUtxo Data of the wallet's main UTXO, as currently
399
+ /// known on the Ethereum chain.
400
+ /// @dev Requirements:
401
+ /// - Wallet must not be set as the current active wallet
402
+ /// - Wallet must exceed the wallet maximum age OR the wallet BTC
403
+ /// balance must be lesser than the minimum threshold. If the latter
404
+ /// case is true, the `walletMainUtxo` components must point to the
405
+ /// recent main UTXO of the given wallet, as currently known on the
406
+ /// Ethereum chain. If the wallet has no main UTXO, this parameter
407
+ /// can be empty as it is ignored since the wallet balance is
408
+ /// assumed to be zero.
409
+ /// - Wallet must be in Live state
410
+ function notifyCloseableWallet(
411
+ Data storage self,
412
+ bytes20 walletPubKeyHash,
413
+ BitcoinTx.UTXO calldata walletMainUtxo
414
+ ) external {
415
+ require(
416
+ self.activeWalletPubKeyHash != walletPubKeyHash,
417
+ "Active wallet cannot be considered closeable"
418
+ );
419
+
420
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
421
+ require(
422
+ wallet.state == WalletState.Live,
423
+ "ECDSA wallet must be in Live state"
424
+ );
425
+
426
+ /* solhint-disable-next-line not-rely-on-time */
427
+ bool walletOldEnough = block.timestamp >=
428
+ wallet.createdAt + self.maxAge;
429
+
430
+ require(
431
+ walletOldEnough ||
432
+ getWalletBtcBalance(self, walletPubKeyHash, walletMainUtxo) <
433
+ self.minBtcBalance,
434
+ "Wallet needs to be old enough or have too few satoshis"
435
+ );
436
+
437
+ moveFunds(self, walletPubKeyHash);
438
+ }
439
+
440
+ /// @notice Requests a wallet to move their funds. If the wallet balance
441
+ /// is zero, the wallet is closed immediately and the ECDSA
442
+ /// registry is notified about this fact. If the move funds
443
+ /// request refers to the current active wallet, such a wallet
444
+ /// is no longer considered active and the active wallet slot
445
+ /// is unset allowing to trigger a new wallet creation immediately.
446
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
447
+ /// @dev Requirements:
448
+ /// - The caller must make sure that the wallet is in the Live state
449
+ function moveFunds(Data storage self, bytes20 walletPubKeyHash) internal {
450
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
451
+
452
+ if (wallet.mainUtxoHash == bytes32(0)) {
453
+ // If the wallet has no main UTXO, that means its BTC balance
454
+ // is zero and it should be closed immediately.
455
+ closeWallet(self, walletPubKeyHash);
456
+ } else {
457
+ // Otherwise, initialize the moving funds process.
458
+ wallet.state = WalletState.MovingFunds;
459
+ /* solhint-disable-next-line not-rely-on-time */
460
+ wallet.movingFundsRequestedAt = uint32(block.timestamp);
461
+
462
+ emit WalletMovingFunds(wallet.ecdsaWalletID, walletPubKeyHash);
463
+ }
464
+
465
+ if (self.activeWalletPubKeyHash == walletPubKeyHash) {
466
+ // If the move funds request refers to the current active wallet,
467
+ // unset the active wallet and make the wallet creation process
468
+ // possible in order to get a new healthy active wallet.
469
+ delete self.activeWalletPubKeyHash;
470
+ }
471
+ }
472
+
473
+ /// @notice Closes the given wallet and notifies the ECDSA registry
474
+ /// about this fact.
475
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
476
+ /// @dev Requirements:
477
+ /// - The caller must make sure that the wallet is in the
478
+ /// Live or MovingFunds state.
479
+ function closeWallet(Data storage self, bytes20 walletPubKeyHash) internal {
480
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
481
+
482
+ wallet.state = WalletState.Closed;
483
+
484
+ emit WalletClosed(wallet.ecdsaWalletID, walletPubKeyHash);
485
+
486
+ self.registry.closeWallet(wallet.ecdsaWalletID);
487
+ }
488
+
489
+ /// @notice Reports about a fraud committed by the given wallet. This
490
+ /// function performs slashing and wallet termination in reaction
491
+ /// to a proven fraud and it should only be called when the fraud
492
+ /// was confirmed.
493
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
494
+ /// @dev Requirements:
495
+ /// - Wallet must be in Live or MovingFunds state
496
+ function notifyFraud(Data storage self, bytes20 walletPubKeyHash) external {
497
+ WalletState walletState = self
498
+ .registeredWallets[walletPubKeyHash]
499
+ .state;
500
+
501
+ require(
502
+ walletState == WalletState.Live ||
503
+ walletState == WalletState.MovingFunds,
504
+ "ECDSA wallet must be in Live or MovingFunds state"
505
+ );
506
+
507
+ terminateWallet(self, walletPubKeyHash);
508
+
509
+ // TODO: Perform slashing of wallet operators and add unit tests for that.
510
+ }
511
+
512
+ /// @notice Terminates the given wallet and notifies the ECDSA registry
513
+ /// about this fact. If the wallet termination refers to the current
514
+ /// active wallet, such a wallet is no longer considered active and
515
+ /// the active wallet slot is unset allowing to trigger a new wallet
516
+ /// creation immediately.
517
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
518
+ /// @dev Requirements:
519
+ /// - The caller must make sure that the wallet is in the
520
+ /// Live or MovingFunds state.
521
+ function terminateWallet(Data storage self, bytes20 walletPubKeyHash)
522
+ internal
523
+ {
524
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
525
+
526
+ wallet.state = WalletState.Terminated;
527
+
528
+ emit WalletTerminated(wallet.ecdsaWalletID, walletPubKeyHash);
529
+
530
+ if (self.activeWalletPubKeyHash == walletPubKeyHash) {
531
+ // If termination refers to the current active wallet,
532
+ // unset the active wallet and make the wallet creation process
533
+ // possible in order to get a new healthy active wallet.
534
+ delete self.activeWalletPubKeyHash;
535
+ }
536
+
537
+ self.registry.closeWallet(wallet.ecdsaWalletID);
538
+ }
539
+
540
+ /// @notice Notifies that the wallet completed the moving funds process
541
+ /// successfully. Checks if the funds were moved to the expected
542
+ /// target wallets. Closes the source wallet if everything went
543
+ /// good and reverts otherwise.
544
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
545
+ /// @param targetWalletsHash 32-byte keccak256 hash over the list of
546
+ /// 20-byte public key hashes of the target wallets actually used
547
+ /// within the moving funds transactions.
548
+ /// @dev Requirements:
549
+ /// - The caller must make sure the moving funds transaction actually
550
+ /// happened on Bitcoin chain and fits the protocol requirements.
551
+ /// - The source wallet must be in the MovingFunds state
552
+ /// - The target wallets commitment must be submitted by the source
553
+ /// wallet.
554
+ /// - The actual target wallets used in the moving funds transaction
555
+ /// must be exactly the same as the target wallets commitment.
556
+ function notifyFundsMoved(
557
+ Data storage self,
558
+ bytes20 walletPubKeyHash,
559
+ bytes32 targetWalletsHash
560
+ ) external {
561
+ Wallet storage wallet = self.registeredWallets[walletPubKeyHash];
562
+ // Check that the wallet is in the MovingFunds state but don't check
563
+ // if the moving funds timeout is exceeded. That should give a
564
+ // possibility to move funds in case when timeout was hit but was
565
+ // not reported yet.
566
+ require(
567
+ wallet.state == WalletState.MovingFunds,
568
+ "ECDSA wallet must be in MovingFunds state"
569
+ );
570
+
571
+ bytes32 targetWalletsCommitmentHash = wallet
572
+ .movingFundsTargetWalletsCommitmentHash;
573
+
574
+ require(
575
+ targetWalletsCommitmentHash != bytes32(0),
576
+ "Target wallets commitment not submitted yet"
577
+ );
578
+
579
+ // Make sure that the target wallets where funds were moved to are
580
+ // exactly the same as the ones the source wallet committed to.
581
+ require(
582
+ targetWalletsCommitmentHash == targetWalletsHash,
583
+ "Target wallets don't correspond to the commitment"
584
+ );
585
+
586
+ // If funds were moved, the wallet has no longer a main UTXO.
587
+ delete wallet.mainUtxoHash;
588
+
589
+ closeWallet(self, walletPubKeyHash);
590
+ }
591
+ }
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: MIT
2
2
 
3
- pragma solidity 0.8.4;
3
+ pragma solidity ^0.8.9;
4
4
 
5
5
  import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol";
6
6
  import "@thesis/solidity-contracts/contracts/token/MisfundRecovery.sol";
@@ -13,25 +13,47 @@
13
13
  // ▐████▌ ▐████▌
14
14
  // ▐████▌ ▐████▌
15
15
 
16
- pragma solidity 0.8.4;
16
+ pragma solidity ^0.8.9;
17
17
 
18
18
  /// @title Bank Vault interface
19
19
  /// @notice `IVault` is an interface for a smart contract consuming Bank
20
- /// balances allowing the smart contract to receive Bank balances right
21
- /// after sweeping the deposit by the Bridge. This method allows the
22
- /// depositor to route their deposit revealed to the Bridge to the
23
- /// particular smart contract in the same transaction the deposit is
24
- /// revealed. This way, the depositor does not have to execute
25
- /// additional transaction after the deposit gets swept by the Bridge.
20
+ /// balances of other contracts or externally owned accounts (EOA).
26
21
  interface IVault {
22
+ /// @notice Called by the Bank in `approveBalanceAndCall` function after
23
+ /// the balance `owner` approved `amount` of their balance in the
24
+ /// Bank for the vault. This way, the depositor can approve balance
25
+ /// and call the vault to use the approved balance in a single
26
+ /// transaction.
27
+ /// @param owner Address of the Bank balance owner who approved their
28
+ /// balance to be used by the vault
29
+ /// @param amount The amount of the Bank balance approved by the owner
30
+ /// to be used by the vault
31
+ // @dev The implementation must ensure this function can only be called
32
+ /// by the Bank. The Bank does _not_ guarantee that the `amount`
33
+ /// approved by the `owner` currently exists on their balance. That is,
34
+ /// the `owner` could approve more balance than they currently have.
35
+ /// This works the same as `Bank.approve` function. The vault must
36
+ /// ensure the actual balance is checked before performing any action
37
+ /// based on it.
38
+ function receiveBalanceApproval(address owner, uint256 amount) external;
39
+
27
40
  /// @notice Called by the Bank in `increaseBalanceAndCall` function after
28
- /// increasing the balance in the Bank for the vault.
41
+ /// increasing the balance in the Bank for the vault. It happens in
42
+ /// the same transaction in which deposits were swept by the Bridge.
43
+ /// This allows the depositor to route their deposit revealed to the
44
+ /// Bridge to the particular smart contract (vault) in the same
45
+ /// transaction in which the deposit is revealed. This way, the
46
+ /// depositor does not have to execute additional transaction after
47
+ /// the deposit gets swept by the Bridge to approve and transfer
48
+ /// their balance to the vault.
29
49
  /// @param depositors Addresses of depositors whose deposits have been swept
30
50
  /// @param depositedAmounts Amounts deposited by individual depositors and
31
51
  /// swept
32
52
  /// @dev The implementation must ensure this function can only be called
33
- /// by the Bank.
34
- function onBalanceIncreased(
53
+ /// by the Bank. The Bank guarantees that the vault's balance was
54
+ /// increased by the sum of all deposited amounts before this function
55
+ /// is called, in the same transaction.
56
+ function receiveBalanceIncrease(
35
57
  address[] calldata depositors,
36
58
  uint256[] calldata depositedAmounts
37
59
  ) external;