@keep-network/tbtc-v2 0.1.1-dev.3 → 0.1.1-dev.30

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 (42) 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/087a7a27c8cd210b7c63e594263dfed9.json +197 -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 +43 -2
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  11. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +96 -0
  12. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  13. package/build/contracts/bridge/Bridge.sol/Bridge.json +1598 -71
  14. package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +4 -0
  15. package/build/contracts/bridge/Bridge.sol/IRelay.json +37 -0
  16. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  17. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  18. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +4 -0
  19. package/build/contracts/bridge/Frauds.sol/Frauds.json +138 -0
  20. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  21. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  22. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  23. package/build/contracts/bridge/Wallets.sol/Wallets.json +138 -0
  24. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  25. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  26. package/build/contracts/vault/IVault.sol/IVault.dbg.json +4 -0
  27. package/build/contracts/vault/IVault.sol/IVault.json +47 -0
  28. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  29. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +38 -2
  30. package/contracts/GovernanceUtils.sol +1 -1
  31. package/contracts/bank/Bank.sol +69 -18
  32. package/contracts/bridge/BitcoinTx.sol +241 -0
  33. package/contracts/bridge/Bridge.sol +1956 -104
  34. package/contracts/bridge/EcdsaLib.sol +30 -0
  35. package/contracts/bridge/Frauds.sol +531 -0
  36. package/contracts/bridge/VendingMachine.sol +1 -1
  37. package/contracts/bridge/Wallets.sol +521 -0
  38. package/contracts/token/TBTC.sol +1 -1
  39. package/contracts/vault/IVault.sol +60 -0
  40. package/contracts/vault/TBTCVault.sol +50 -8
  41. package/package.json +28 -24
  42. package/artifacts/solcInputs/cebfa5efa019cb9c8c5e23e38703b883.json +0 -113
@@ -1,105 +1,777 @@
1
- pragma solidity 0.8.4;
1
+ // SPDX-License-Identifier: MIT
2
2
 
3
- /// @title BTC Bridge
4
- /// @notice Bridge manages BTC deposit and redemption and is increasing and
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity ^0.8.9;
17
+
18
+ import "@openzeppelin/contracts/access/Ownable.sol";
19
+
20
+ import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
21
+ import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
22
+ import {IWalletOwner as EcdsaWalletOwner} from "@keep-network/ecdsa/contracts/api/IWalletOwner.sol";
23
+
24
+ import "../bank/Bank.sol";
25
+ import "./BitcoinTx.sol";
26
+ import "./EcdsaLib.sol";
27
+ import "./Wallets.sol";
28
+ import "./Frauds.sol";
29
+
30
+ /// @title Interface for the Bitcoin relay
31
+ /// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay
32
+ /// provides the difficulty of the previous and current epoch. One
33
+ /// difficulty epoch spans 2016 blocks.
34
+ interface IRelay {
35
+ /// @notice Returns the difficulty of the current epoch.
36
+ function getCurrentEpochDifficulty() external view returns (uint256);
37
+
38
+ /// @notice Returns the difficulty of the previous epoch.
39
+ function getPrevEpochDifficulty() external view returns (uint256);
40
+ }
41
+
42
+ /// @title Bitcoin Bridge
43
+ /// @notice Bridge manages BTC deposit and redemption flow and is increasing and
5
44
  /// decreasing balances in the Bank as a result of BTC deposit and
6
- /// redemption operations.
45
+ /// redemption operations performed by depositors and redeemers.
7
46
  ///
8
- /// Depositors send BTC funds to the most-recently-created-wallet of the
9
- /// bridge using pay-to-script-hash (P2SH) which contains hashed
10
- /// information about the depositor’s minting Ethereum address. Then,
11
- /// the depositor reveals their desired Ethereum minting address to the
12
- /// Ethereum chain. The Bridge listens for these sorts of messages and
13
- /// when it gets one, it checks the Bitcoin network to make sure the
14
- /// funds line up. If they do, the off-chain wallet may decide to pick
15
- /// this transaction for sweeping, and when the sweep operation is
16
- /// confirmed on the Bitcoin network, the wallet informs the Bridge
17
- /// about the sweep increasing appropriate balances in the Bank.
47
+ /// Depositors send BTC funds to the most recently created off-chain
48
+ /// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or
49
+ /// pay-to-witness-script-hash (P2WSH) containing hashed information
50
+ /// about the depositor’s Ethereum address. Then, the depositor reveals
51
+ /// their Ethereum address along with their deposit blinding factor,
52
+ /// refund public key hash and refund locktime to the Bridge on Ethereum
53
+ /// chain. The off-chain ECDSA wallet listens for these sorts of
54
+ /// messages and when it gets one, it checks the Bitcoin network to make
55
+ /// sure the deposit lines up. If it does, the off-chain ECDSA wallet
56
+ /// may decide to pick the deposit transaction for sweeping, and when
57
+ /// the sweep operation is confirmed on the Bitcoin network, the ECDSA
58
+ /// wallet informs the Bridge about the sweep increasing appropriate
59
+ /// balances in the Bank.
18
60
  /// @dev Bridge is an upgradeable component of the Bank.
19
- contract Bridge {
20
- struct DepositInfo {
21
- uint64 amount;
61
+ contract Bridge is Ownable, EcdsaWalletOwner {
62
+ using BTCUtils for bytes;
63
+ using BTCUtils for uint256;
64
+ using BytesLib for bytes;
65
+ using Frauds for Frauds.Data;
66
+ using Wallets for Wallets.Data;
67
+
68
+ /// @notice Represents data which must be revealed by the depositor during
69
+ /// deposit reveal.
70
+ struct RevealInfo {
71
+ // Index of the funding output belonging to the funding transaction.
72
+ uint32 fundingOutputIndex;
73
+ // Ethereum depositor address.
74
+ address depositor;
75
+ // The blinding factor as 8 bytes. Byte endianness doesn't matter
76
+ // as this factor is not interpreted as uint.
77
+ bytes8 blindingFactor;
78
+ // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)
79
+ // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.
80
+ bytes20 walletPubKeyHash;
81
+ // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)
82
+ // that can be used to make the deposit refund after the refund
83
+ // locktime passes. Hashed in the HASH160 Bitcoin opcode style.
84
+ bytes20 refundPubKeyHash;
85
+ // The refund locktime (4-byte LE). Interpreted according to locktime
86
+ // parsing rules described in:
87
+ // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number
88
+ // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:
89
+ // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki
90
+ bytes4 refundLocktime;
91
+ // Address of the Bank vault to which the deposit is routed to.
92
+ // Optional, can be 0x0. The vault must be trusted by the Bridge.
22
93
  address vault;
94
+ }
95
+
96
+ /// @notice Represents tBTC deposit data.
97
+ struct DepositRequest {
98
+ // Ethereum depositor address.
99
+ address depositor;
100
+ // Deposit amount in satoshi.
101
+ uint64 amount;
102
+ // UNIX timestamp the deposit was revealed at.
23
103
  uint32 revealedAt;
104
+ // Address of the Bank vault the deposit is routed to.
105
+ // Optional, can be 0x0.
106
+ address vault;
107
+ // Treasury TBTC fee in satoshi at the moment of deposit reveal.
108
+ uint64 treasuryFee;
109
+ // UNIX timestamp the deposit was swept at. Note this is not the
110
+ // time when the deposit was swept on the Bitcoin chain but actually
111
+ // the time when the sweep proof was delivered to the Ethereum chain.
112
+ uint32 sweptAt;
113
+ }
114
+
115
+ /// @notice Represents an outcome of the sweep Bitcoin transaction
116
+ /// inputs processing.
117
+ struct SweepTxInputsInfo {
118
+ // Sum of all inputs values i.e. all deposits and main UTXO value,
119
+ // if present.
120
+ uint256 inputsTotalValue;
121
+ // Addresses of depositors who performed processed deposits. Ordered in
122
+ // the same order as deposits inputs in the input vector. Size of this
123
+ // array is either equal to the number of inputs (main UTXO doesn't
124
+ // exist) or less by one (main UTXO exists and is pointed by one of
125
+ // the inputs).
126
+ address[] depositors;
127
+ // Amounts of deposits corresponding to processed deposits. Ordered in
128
+ // the same order as deposits inputs in the input vector. Size of this
129
+ // array is either equal to the number of inputs (main UTXO doesn't
130
+ // exist) or less by one (main UTXO exists and is pointed by one of
131
+ // the inputs).
132
+ uint256[] depositedAmounts;
133
+ // Values of the treasury fee corresponding to processed deposits.
134
+ // Ordered in the same order as deposits inputs in the input vector.
135
+ // Size of this array is either equal to the number of inputs (main
136
+ // UTXO doesn't exist) or less by one (main UTXO exists and is pointed
137
+ // by one of the inputs).
138
+ uint256[] treasuryFees;
24
139
  }
25
140
 
26
- /// @notice Collection of all unswept deposits indexed by
27
- /// keccak256(fundingTxHash | fundingOutputIndex | depositorAddress).
28
- /// This mapping may contain valid and invalid deposits and the
29
- /// wallet is responsible for validating them before attempting to
30
- /// execute a sweep.
31
- mapping(uint256 => DepositInfo) public unswept;
141
+ /// @notice Represents a redemption request.
142
+ struct RedemptionRequest {
143
+ // ETH address of the redeemer who created the request.
144
+ address redeemer;
145
+ // Requested TBTC amount in satoshi.
146
+ uint64 requestedAmount;
147
+ // Treasury TBTC fee in satoshi at the moment of request creation.
148
+ uint64 treasuryFee;
149
+ // Transaction maximum BTC fee in satoshi at the moment of request
150
+ // creation.
151
+ uint64 txMaxFee;
152
+ // UNIX timestamp the request was created at.
153
+ uint32 requestedAt;
154
+ }
155
+
156
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
157
+ /// outputs processing.
158
+ struct RedemptionTxOutputsInfo {
159
+ // Total TBTC value in satoshi that should be burned by the Bridge.
160
+ // It includes the total amount of all BTC redeemed in the transaction
161
+ // and the fee paid to BTC miners for the redemption transaction.
162
+ uint64 totalBurnableValue;
163
+ // Total TBTC value in satoshi that should be transferred to
164
+ // the treasury. It is a sum of all treasury fees paid by all
165
+ // redeemers included in the redemption transaction.
166
+ uint64 totalTreasuryFee;
167
+ // Index of the change output. The change output becomes
168
+ // the new main wallet's UTXO.
169
+ uint32 changeIndex;
170
+ // Value in satoshi of the change output.
171
+ uint64 changeValue;
172
+ }
173
+
174
+ /// @notice The number of confirmations on the Bitcoin chain required to
175
+ /// successfully evaluate an SPV proof.
176
+ uint256 public immutable txProofDifficultyFactor;
177
+
178
+ /// TODO: Revisit whether it should be governable or not.
179
+ /// @notice Address of the Bank this Bridge belongs to.
180
+ Bank public immutable bank;
181
+
182
+ /// TODO: Make it governable.
183
+ /// @notice Handle to the Bitcoin relay.
184
+ IRelay public immutable relay;
185
+
186
+ /// TODO: Revisit whether it should be governable or not.
187
+ /// @notice Address where the redemptions treasury fees will be sent to.
188
+ /// Treasury takes part in the operators rewarding process.
189
+ address public immutable treasury;
190
+
191
+ /// TODO: Make it governable.
192
+ /// @notice The minimal amount that can be requested for deposit.
193
+ /// Value of this parameter must take into account the value of
194
+ /// `depositTreasuryFeeDivisor` and `depositTxMaxFee`
195
+ /// parameters in order to make requests that can incur the
196
+ /// treasury and transaction fee and still satisfy the depositor.
197
+ uint64 public depositDustThreshold;
198
+
199
+ /// TODO: Make it governable.
200
+ /// @notice Divisor used to compute the treasury fee taken from each
201
+ /// deposit and transferred to the treasury upon sweep proof
202
+ /// submission. That fee is computed as follows:
203
+ /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`
204
+ /// For example, if the treasury fee needs to be 2% of each deposit,
205
+ /// the `depositTreasuryFeeDivisor` should be set to `50`
206
+ /// because `1/50 = 0.02 = 2%`.
207
+ uint64 public depositTreasuryFeeDivisor;
208
+
209
+ /// TODO: Make it governable.
210
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
211
+ /// each swept deposit being part of the given sweep
212
+ /// transaction. If the maximum BTC transaction fee is exceeded,
213
+ /// such transaction is considered a fraud.
214
+ uint64 public depositTxMaxFee;
215
+
216
+ /// TODO: Make it governable.
217
+ /// @notice The minimal amount that can be requested for redemption.
218
+ /// Value of this parameter must take into account the value of
219
+ /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
220
+ /// parameters in order to make requests that can incur the
221
+ /// treasury and transaction fee and still satisfy the redeemer.
222
+ uint64 public redemptionDustThreshold;
223
+
224
+ /// TODO: Make it governable.
225
+ /// @notice Divisor used to compute the treasury fee taken from each
226
+ /// redemption request and transferred to the treasury upon
227
+ /// successful request finalization. That fee is computed as follows:
228
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
229
+ /// For example, if the treasury fee needs to be 2% of each
230
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
231
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
232
+ uint64 public redemptionTreasuryFeeDivisor;
233
+
234
+ /// TODO: Make it governable.
235
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
236
+ /// each redemption request being part of the given redemption
237
+ /// transaction. If the maximum BTC transaction fee is exceeded, such
238
+ /// transaction is considered a fraud.
239
+ uint64 public redemptionTxMaxFee;
240
+
241
+ /// TODO: Make it governable.
242
+ /// @notice Time after which the redemption request can be reported as
243
+ /// timed out. It is counted from the moment when the redemption
244
+ /// request was created via `requestRedemption` call. Reported
245
+ /// timed out requests are cancelled and locked TBTC is returned
246
+ /// to the redeemer in full amount.
247
+ uint256 public redemptionTimeout;
248
+
249
+ /// @notice Indicates if the vault with the given address is trusted or not.
250
+ /// Depositors can route their revealed deposits only to trusted
251
+ /// vaults and have trusted vaults notified about new deposits as
252
+ /// soon as these deposits get swept. Vaults not trusted by the
253
+ /// Bridge can still be used by Bank balance owners on their own
254
+ /// responsibility - anyone can approve their Bank balance to any
255
+ /// address.
256
+ mapping(address => bool) public isVaultTrusted;
257
+
258
+ /// @notice Collection of all revealed deposits indexed by
259
+ /// keccak256(fundingTxHash | fundingOutputIndex).
260
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
261
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
262
+ /// and invalid deposits and the wallet is responsible for
263
+ /// validating them before attempting to execute a sweep.
264
+ mapping(uint256 => DepositRequest) public deposits;
265
+
266
+ //TODO: Remember to update this map when implementing transferring funds
267
+ // between wallets (insert the main UTXO that was used as the input).
268
+ /// @notice Collection of main UTXOs that are honestly spent indexed by
269
+ /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash
270
+ /// is bytes32 (ordered as in Bitcoin internally) and
271
+ /// fundingOutputIndex an uint32. A main UTXO is considered honestly
272
+ /// spent if it was used as an input of a transaction that have been
273
+ /// proven in the Bridge.
274
+ mapping(uint256 => bool) public spentMainUTXOs;
275
+
276
+ /// @notice Collection of all pending redemption requests indexed by
277
+ /// redemption key built as
278
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
279
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
280
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
281
+ /// public key) and redeemerOutputScript is a Bitcoin script
282
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
283
+ /// redeemed BTC as requested by the redeemer. Requests are added
284
+ /// to this mapping by the `requestRedemption` method (duplicates
285
+ /// not allowed) and are removed by one of the following methods:
286
+ /// - `submitRedemptionProof` in case the request was handled
287
+ /// successfully
288
+ /// - `notifyRedemptionTimeout` in case the request was reported
289
+ /// to be timed out
290
+ mapping(uint256 => RedemptionRequest) public pendingRedemptions;
291
+
292
+ /// @notice Collection of all timed out redemptions requests indexed by
293
+ /// redemption key built as
294
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
295
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
296
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
297
+ /// public key) and redeemerOutputScript is the Bitcoin script
298
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
299
+ /// out request. Timed out requests are stored in this mapping to
300
+ /// avoid slashing the wallets multiple times for the same timeout.
301
+ /// Only one method can add to this mapping:
302
+ /// - `notifyRedemptionTimeout` which puts the redemption key
303
+ /// to this mapping basing on a timed out request stored
304
+ /// previously in `pendingRedemptions` mapping.
305
+ mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
306
+
307
+ /// @notice Contains parameters related to frauds and the collection of all
308
+ /// submitted fraud challenges.
309
+ Frauds.Data internal frauds;
310
+
311
+ /// @notice State related with wallets.
312
+ Wallets.Data internal wallets;
313
+
314
+ event WalletCreationPeriodUpdated(uint32 newCreationPeriod);
315
+
316
+ event WalletBtcBalanceRangeUpdated(
317
+ uint64 newMinBtcBalance,
318
+ uint64 newMaxBtcBalance
319
+ );
320
+
321
+ event WalletMaxAgeUpdated(uint32 newMaxAge);
322
+
323
+ event NewWalletRequested();
324
+
325
+ event NewWalletRegistered(
326
+ bytes32 indexed ecdsaWalletID,
327
+ bytes20 indexed walletPubKeyHash
328
+ );
329
+
330
+ event WalletMovingFunds(
331
+ bytes32 indexed ecdsaWalletID,
332
+ bytes20 indexed walletPubKeyHash
333
+ );
334
+
335
+ event WalletClosed(
336
+ bytes32 indexed ecdsaWalletID,
337
+ bytes20 indexed walletPubKeyHash
338
+ );
339
+
340
+ event WalletTerminated(
341
+ bytes32 indexed ecdsaWalletID,
342
+ bytes20 indexed walletPubKeyHash
343
+ );
344
+
345
+ event VaultStatusUpdated(address indexed vault, bool isTrusted);
346
+
347
+ event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);
348
+
349
+ event FraudNotifierRewardMultiplierUpdated(
350
+ uint256 newFraudNotifierRewardMultiplier
351
+ );
352
+
353
+ event FraudChallengeDefeatTimeoutUpdated(
354
+ uint256 newFraudChallengeDefeatTimeout
355
+ );
356
+
357
+ event FraudChallengeDepositAmountUpdated(
358
+ uint256 newFraudChallengeDepositAmount
359
+ );
32
360
 
33
361
  event DepositRevealed(
34
- uint256 depositId,
35
362
  bytes32 fundingTxHash,
36
- uint8 fundingOutputIndex,
363
+ uint32 fundingOutputIndex,
37
364
  address depositor,
38
- uint64 blindingFactor,
39
- bytes refundPubKey,
40
365
  uint64 amount,
366
+ bytes8 blindingFactor,
367
+ bytes20 walletPubKeyHash,
368
+ bytes20 refundPubKeyHash,
369
+ bytes4 refundLocktime,
41
370
  address vault
42
371
  );
43
372
 
44
- /// @notice Used by the depositor to reveal information about their P2SH
373
+ event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
374
+
375
+ event RedemptionRequested(
376
+ bytes20 walletPubKeyHash,
377
+ bytes redeemerOutputScript,
378
+ address redeemer,
379
+ uint64 requestedAmount,
380
+ uint64 treasuryFee,
381
+ uint64 txMaxFee
382
+ );
383
+
384
+ event RedemptionsCompleted(
385
+ bytes20 walletPubKeyHash,
386
+ bytes32 redemptionTxHash
387
+ );
388
+
389
+ event RedemptionTimedOut(
390
+ bytes20 walletPubKeyHash,
391
+ bytes redeemerOutputScript
392
+ );
393
+
394
+ event FraudChallengeSubmitted(
395
+ bytes20 walletPublicKeyHash,
396
+ bytes32 sighash,
397
+ uint8 v,
398
+ bytes32 r,
399
+ bytes32 s
400
+ );
401
+
402
+ event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);
403
+
404
+ event FraudChallengeDefeatTimedOut(
405
+ bytes20 walletPublicKeyHash,
406
+ bytes32 sighash
407
+ );
408
+
409
+ constructor(
410
+ address _bank,
411
+ address _relay,
412
+ address _treasury,
413
+ address _ecdsaWalletRegistry,
414
+ uint256 _txProofDifficultyFactor
415
+ ) {
416
+ require(_bank != address(0), "Bank address cannot be zero");
417
+ bank = Bank(_bank);
418
+
419
+ require(_relay != address(0), "Relay address cannot be zero");
420
+ relay = IRelay(_relay);
421
+
422
+ require(_treasury != address(0), "Treasury address cannot be zero");
423
+ treasury = _treasury;
424
+
425
+ txProofDifficultyFactor = _txProofDifficultyFactor;
426
+
427
+ // TODO: Revisit initial values.
428
+ depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
429
+ depositTxMaxFee = 1000; // 1000 satoshi
430
+ depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
431
+ redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
432
+ redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
433
+ redemptionTxMaxFee = 1000; // 1000 satoshi
434
+ redemptionTimeout = 172800; // 48 hours
435
+ frauds.setSlashingAmount(10000 * 1e18); // 10000 T
436
+ frauds.setNotifierRewardMultiplier(100); // 100%
437
+ frauds.setChallengeDefeatTimeout(7 days);
438
+ frauds.setChallengeDepositAmount(2 ether);
439
+
440
+ // TODO: Revisit initial values.
441
+ wallets.init(_ecdsaWalletRegistry);
442
+ wallets.setCreationPeriod(1 weeks);
443
+ wallets.setBtcBalanceRange(1 * 1e8, 10 * 1e8); // [1 BTC, 10 BTC]
444
+ wallets.setMaxAge(26 weeks); // ~6 months
445
+ }
446
+
447
+ /// @notice Updates parameters used by the `Wallets` library.
448
+ /// @param creationPeriod New value of the wallet creation period
449
+ /// @param minBtcBalance New value of the minimum BTC balance
450
+ /// @param maxBtcBalance New value of the maximum BTC balance
451
+ /// @param maxAge New value of the wallet maximum age
452
+ /// @dev Requirements:
453
+ /// - Caller must be the contract owner.
454
+ /// - Minimum BTC balance must be greater than zero
455
+ /// - Maximum BTC balance must be greater than minimum BTC balance
456
+ function updateWalletsParameters(
457
+ uint32 creationPeriod,
458
+ uint64 minBtcBalance,
459
+ uint64 maxBtcBalance,
460
+ uint32 maxAge
461
+ ) external onlyOwner {
462
+ wallets.setCreationPeriod(creationPeriod);
463
+ wallets.setBtcBalanceRange(minBtcBalance, maxBtcBalance);
464
+ wallets.setMaxAge(maxAge);
465
+ }
466
+
467
+ /// @return creationPeriod Value of the wallet creation period
468
+ /// @return minBtcBalance Value of the minimum BTC balance
469
+ /// @return maxBtcBalance Value of the maximum BTC balance
470
+ /// @return maxAge Value of the wallet max age
471
+ function getWalletsParameters()
472
+ external
473
+ view
474
+ returns (
475
+ uint32 creationPeriod,
476
+ uint64 minBtcBalance,
477
+ uint64 maxBtcBalance,
478
+ uint32 maxAge
479
+ )
480
+ {
481
+ creationPeriod = wallets.creationPeriod;
482
+ minBtcBalance = wallets.minBtcBalance;
483
+ maxBtcBalance = wallets.maxBtcBalance;
484
+ maxAge = wallets.maxAge;
485
+
486
+ return (creationPeriod, minBtcBalance, maxBtcBalance, maxAge);
487
+ }
488
+
489
+ /// @notice Allows the Governance to mark the given vault address as trusted
490
+ /// or no longer trusted. Vaults are not trusted by default.
491
+ /// Trusted vault must meet the following criteria:
492
+ /// - `IVault.receiveBalanceIncrease` must have a known, low gas
493
+ /// cost.
494
+ /// - `IVault.receiveBalanceIncrease` must never revert.
495
+ /// @dev Without restricting reveal only to trusted vaults, malicious
496
+ /// vaults not meeting the criteria would be able to nuke sweep proof
497
+ /// transactions executed by ECDSA wallet with deposits routed to
498
+ /// them.
499
+ /// @param vault The address of the vault
500
+ /// @param isTrusted flag indicating whether the vault is trusted or not
501
+ /// @dev Can only be called by the Governance.
502
+ function setVaultStatus(address vault, bool isTrusted) external onlyOwner {
503
+ isVaultTrusted[vault] = isTrusted;
504
+ emit VaultStatusUpdated(vault, isTrusted);
505
+ }
506
+
507
+ /// @notice Requests creation of a new wallet. This function just
508
+ /// forms a request and the creation process is performed
509
+ /// asynchronously. Once a wallet is created, the ECDSA Wallet
510
+ /// Registry will notify this contract by calling the
511
+ /// `__ecdsaWalletCreatedCallback` function.
512
+ /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as
513
+ /// currently known on the Ethereum chain.
514
+ /// @dev Requirements:
515
+ /// - `activeWalletMainUtxo` components must point to the recent main
516
+ /// UTXO of the given active wallet, as currently known on the
517
+ /// Ethereum chain. If there is no active wallet at the moment, or
518
+ /// the active wallet has no main UTXO, this parameter can be
519
+ /// empty as it is ignored.
520
+ /// - Wallet creation must not be in progress
521
+ /// - If the active wallet is set, one of the following
522
+ /// conditions must be true:
523
+ /// - The active wallet BTC balance is above the minimum threshold
524
+ /// and the active wallet is old enough, i.e. the creation period
525
+ /// was elapsed since its creation time
526
+ /// - The active wallet BTC balance is above the maximum threshold
527
+ function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)
528
+ external
529
+ {
530
+ wallets.requestNewWallet(activeWalletMainUtxo);
531
+ }
532
+
533
+ /// @notice A callback function that is called by the ECDSA Wallet Registry
534
+ /// once a new ECDSA wallet is created.
535
+ /// @param ecdsaWalletID Wallet's unique identifier.
536
+ /// @param publicKeyX Wallet's public key's X coordinate.
537
+ /// @param publicKeyY Wallet's public key's Y coordinate.
538
+ /// @dev Requirements:
539
+ /// - The only caller authorized to call this function is `registry`
540
+ /// - Given wallet data must not belong to an already registered wallet
541
+ function __ecdsaWalletCreatedCallback(
542
+ bytes32 ecdsaWalletID,
543
+ bytes32 publicKeyX,
544
+ bytes32 publicKeyY
545
+ ) external override {
546
+ wallets.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);
547
+ }
548
+
549
+ /// @notice A callback function that is called by the ECDSA Wallet Registry
550
+ /// once a wallet heartbeat failure is detected.
551
+ /// @param publicKeyX Wallet's public key's X coordinate
552
+ /// @param publicKeyY Wallet's public key's Y coordinate
553
+ /// @dev Requirements:
554
+ /// - The only caller authorized to call this function is `registry`
555
+ /// - Wallet must be in Live state
556
+ function __ecdsaWalletHeartbeatFailedCallback(
557
+ bytes32,
558
+ bytes32 publicKeyX,
559
+ bytes32 publicKeyY
560
+ ) external override {
561
+ wallets.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);
562
+ }
563
+
564
+ /// @notice Notifies that the wallet is either old enough or has too few
565
+ /// satoshis left and qualifies to be closed.
566
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
567
+ /// @param walletMainUtxo Data of the wallet's main UTXO, as currently
568
+ /// known on the Ethereum chain.
569
+ /// @dev Requirements:
570
+ /// - Wallet must not be set as the current active wallet
571
+ /// - Wallet must exceed the wallet maximum age OR the wallet BTC
572
+ /// balance must be lesser than the minimum threshold. If the latter
573
+ /// case is true, the `walletMainUtxo` components must point to the
574
+ /// recent main UTXO of the given wallet, as currently known on the
575
+ /// Ethereum chain. If the wallet has no main UTXO, this parameter
576
+ /// can be empty as it is ignored since the wallet balance is
577
+ /// assumed to be zero.
578
+ /// - Wallet must be in Live state
579
+ function notifyCloseableWallet(
580
+ bytes20 walletPubKeyHash,
581
+ BitcoinTx.UTXO calldata walletMainUtxo
582
+ ) external {
583
+ wallets.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);
584
+ }
585
+
586
+ /// @notice Gets details about a registered wallet.
587
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
588
+ /// using Bitcoin HASH160 over the compressed ECDSA public key)
589
+ /// @return Wallet details.
590
+ function getWallet(bytes20 walletPubKeyHash)
591
+ external
592
+ view
593
+ returns (Wallets.Wallet memory)
594
+ {
595
+ return wallets.registeredWallets[walletPubKeyHash];
596
+ }
597
+
598
+ /// @notice Gets the public key hash of the active wallet.
599
+ /// @return The 20-byte public key hash (computed using Bitcoin HASH160
600
+ /// over the compressed ECDSA public key) of the active wallet.
601
+ /// Returns bytes20(0) if there is no active wallet at the moment.
602
+ function getActiveWalletPubKeyHash() external view returns (bytes20) {
603
+ return wallets.activeWalletPubKeyHash;
604
+ }
605
+
606
+ /// @notice Determines the current Bitcoin SPV proof difficulty context.
607
+ /// @return proofDifficulty Bitcoin proof difficulty context.
608
+ function proofDifficultyContext()
609
+ internal
610
+ view
611
+ returns (BitcoinTx.ProofDifficulty memory proofDifficulty)
612
+ {
613
+ proofDifficulty.currentEpochDifficulty = relay
614
+ .getCurrentEpochDifficulty();
615
+ proofDifficulty.previousEpochDifficulty = relay
616
+ .getPrevEpochDifficulty();
617
+ proofDifficulty.difficultyFactor = txProofDifficultyFactor;
618
+
619
+ return proofDifficulty;
620
+ }
621
+
622
+ /// @notice Used by the depositor to reveal information about their P2(W)SH
45
623
  /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain
46
624
  /// wallet listens for revealed deposit events and may decide to
47
625
  /// include the revealed deposit in the next executed sweep.
48
626
  /// Information about the Bitcoin deposit can be revealed before or
49
- /// after the Bitcoin transaction with P2SH deposit is mined on the
50
- /// Bitcoin chain.
51
- /// @param fundingTxHash The BTC transaction hash containing BTC P2SH
52
- /// deposit funding transaction
53
- /// @param fundingOutputIndex The index of the transaction output in the
54
- /// funding TX with P2SH deposit, max 256
55
- /// @param blindingFactor The blinding factor used in the BTC P2SH deposit,
56
- /// max 2^64
57
- /// @param refundPubKey The refund pub key used in the BTC P2SH deposit
58
- /// @param amount The amount locked in the BTC P2SH deposit
59
- /// @param vault Bank vault to which the swept deposit should be routed
627
+ /// after the Bitcoin transaction with P2(W)SH deposit is mined on
628
+ /// the Bitcoin chain. Worth noting, the gas cost of this function
629
+ /// scales with the number of P2(W)SH transaction inputs and
630
+ /// outputs. The deposit may be routed to one of the trusted vaults.
631
+ /// When a deposit is routed to a vault, vault gets notified when
632
+ /// the deposit gets swept and it may execute the appropriate action.
633
+ /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`
634
+ /// @param reveal Deposit reveal data, see `RevealInfo struct
60
635
  /// @dev Requirements:
61
- /// - `msg.sender` must be the Ethereum address used in the P2SH BTC deposit,
62
- /// - `blindingFactor` must be the blinding factor used in the P2SH BTC deposit,
63
- /// - `refundPubKey` must be the refund pub key used in the P2SH BTC deposit,
64
- /// - `amount` must be the same as locked in the P2SH BTC deposit,
636
+ /// - `reveal.walletPubKeyHash` must identify a `Live` wallet
637
+ /// - `reveal.vault` must be 0x0 or point to a trusted vault
638
+ /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH
639
+ /// output of the BTC deposit transaction
640
+ /// - `reveal.depositor` must be the Ethereum address used in the
641
+ /// P2(W)SH BTC deposit transaction,
642
+ /// - `reveal.blindingFactor` must be the blinding factor used in the
643
+ /// P2(W)SH BTC deposit transaction,
644
+ /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in
645
+ /// the P2(W)SH BTC deposit transaction,
646
+ /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in
647
+ /// the P2(W)SH BTC deposit transaction,
648
+ /// - `reveal.refundLocktime` must be the refund locktime used in the
649
+ /// P2(W)SH BTC deposit transaction,
65
650
  /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`
66
- /// can be revealed by `msg.sender` only one time.
651
+ /// can be revealed only one time.
67
652
  ///
68
653
  /// If any of these requirements is not met, the wallet _must_ refuse
69
654
  /// to sweep the deposit and the depositor has to wait until the
70
655
  /// deposit script unlocks to receive their BTC back.
71
656
  function revealDeposit(
72
- bytes32 fundingTxHash,
73
- uint8 fundingOutputIndex,
74
- uint64 blindingFactor,
75
- bytes calldata refundPubKey,
76
- uint64 amount,
77
- address vault
657
+ BitcoinTx.Info calldata fundingTx,
658
+ RevealInfo calldata reveal
78
659
  ) external {
79
- uint256 depositId =
660
+ require(
661
+ wallets.registeredWallets[reveal.walletPubKeyHash].state ==
662
+ Wallets.WalletState.Live,
663
+ "Wallet is not in Live state"
664
+ );
665
+
666
+ require(
667
+ reveal.vault == address(0) || isVaultTrusted[reveal.vault],
668
+ "Vault is not trusted"
669
+ );
670
+
671
+ // TODO: Should we enforce a specific locktime at contract level?
672
+
673
+ bytes memory expectedScript = abi.encodePacked(
674
+ hex"14", // Byte length of depositor Ethereum address.
675
+ reveal.depositor,
676
+ hex"75", // OP_DROP
677
+ hex"08", // Byte length of blinding factor value.
678
+ reveal.blindingFactor,
679
+ hex"75", // OP_DROP
680
+ hex"76", // OP_DUP
681
+ hex"a9", // OP_HASH160
682
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
683
+ reveal.walletPubKeyHash,
684
+ hex"87", // OP_EQUAL
685
+ hex"63", // OP_IF
686
+ hex"ac", // OP_CHECKSIG
687
+ hex"67", // OP_ELSE
688
+ hex"76", // OP_DUP
689
+ hex"a9", // OP_HASH160
690
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
691
+ reveal.refundPubKeyHash,
692
+ hex"88", // OP_EQUALVERIFY
693
+ hex"04", // Byte length of refund locktime value.
694
+ reveal.refundLocktime,
695
+ hex"b1", // OP_CHECKLOCKTIMEVERIFY
696
+ hex"75", // OP_DROP
697
+ hex"ac", // OP_CHECKSIG
698
+ hex"68" // OP_ENDIF
699
+ );
700
+
701
+ bytes memory fundingOutput = fundingTx
702
+ .outputVector
703
+ .extractOutputAtIndex(reveal.fundingOutputIndex);
704
+ bytes memory fundingOutputHash = fundingOutput.extractHash();
705
+
706
+ if (fundingOutputHash.length == 20) {
707
+ // A 20-byte output hash is used by P2SH. That hash is constructed
708
+ // by applying OP_HASH160 on the locking script. A 20-byte output
709
+ // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the
710
+ // public key). However, since we compare the actual output hash
711
+ // with an expected locking script hash, this check will succeed only
712
+ // for P2SH transaction type with expected script hash value. For
713
+ // P2PKH and P2WPKH, it will fail on the output hash comparison with
714
+ // the expected locking script hash.
715
+ require(
716
+ fundingOutputHash.slice20(0) == expectedScript.hash160View(),
717
+ "Wrong 20-byte script hash"
718
+ );
719
+ } else if (fundingOutputHash.length == 32) {
720
+ // A 32-byte output hash is used by P2WSH. That hash is constructed
721
+ // by applying OP_SHA256 on the locking script.
722
+ require(
723
+ fundingOutputHash.toBytes32() == sha256(expectedScript),
724
+ "Wrong 32-byte script hash"
725
+ );
726
+ } else {
727
+ revert("Wrong script hash length");
728
+ }
729
+
730
+ // Resulting TX hash is in native Bitcoin little-endian format.
731
+ bytes32 fundingTxHash = abi
732
+ .encodePacked(
733
+ fundingTx.version,
734
+ fundingTx.inputVector,
735
+ fundingTx.outputVector,
736
+ fundingTx.locktime
737
+ )
738
+ .hash256View();
739
+
740
+ DepositRequest storage deposit = deposits[
80
741
  uint256(
81
742
  keccak256(
82
- abi.encode(fundingTxHash, fundingOutputIndex, msg.sender)
743
+ abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)
83
744
  )
84
- );
85
-
86
- DepositInfo storage deposit = unswept[depositId];
745
+ )
746
+ ];
87
747
  require(deposit.revealedAt == 0, "Deposit already revealed");
88
748
 
89
- deposit.amount = amount;
90
- deposit.vault = vault;
749
+ uint64 fundingOutputAmount = fundingOutput.extractValue();
750
+
751
+ require(
752
+ fundingOutputAmount >= depositDustThreshold,
753
+ "Deposit amount too small"
754
+ );
755
+
756
+ deposit.amount = fundingOutputAmount;
757
+ deposit.depositor = reveal.depositor;
91
758
  /* solhint-disable-next-line not-rely-on-time */
92
759
  deposit.revealedAt = uint32(block.timestamp);
760
+ deposit.vault = reveal.vault;
761
+ deposit.treasuryFee = depositTreasuryFeeDivisor > 0
762
+ ? fundingOutputAmount / depositTreasuryFeeDivisor
763
+ : 0;
93
764
 
94
765
  emit DepositRevealed(
95
- depositId,
96
766
  fundingTxHash,
97
- fundingOutputIndex,
98
- msg.sender,
99
- blindingFactor,
100
- refundPubKey,
101
- amount,
102
- vault
767
+ reveal.fundingOutputIndex,
768
+ reveal.depositor,
769
+ fundingOutputAmount,
770
+ reveal.blindingFactor,
771
+ reveal.walletPubKeyHash,
772
+ reveal.refundPubKeyHash,
773
+ reveal.refundLocktime,
774
+ reveal.vault
103
775
  );
104
776
  }
105
777
 
@@ -110,52 +782,1232 @@ contract Bridge {
110
782
  /// The function is performing Bank balance updates by first
111
783
  /// computing the Bitcoin fee for the sweep transaction. The fee is
112
784
  /// divided evenly between all swept deposits. Each depositor
113
- /// receives a balance in the bank equal to the amount they have
114
- /// declared during the reveal transaction, minus their fee share.
785
+ /// receives a balance in the bank equal to the amount inferred
786
+ /// during the reveal transaction, minus their fee share.
115
787
  ///
116
788
  /// It is possible to prove the given sweep only one time.
117
- /// @param txVersion Transaction version number (4-byte LE)
118
- /// @param txInputVector All transaction inputs prepended by the number of
119
- /// inputs encoded as a VarInt, max 0xFC(252) inputs
120
- /// @param txOutput Single sweep transaction output
121
- /// @param txLocktime Final 4 bytes of the transaction
122
- /// @param merkleProof The merkle proof of transaction inclusion in a block
123
- /// @param txIndexInBlock Transaction index in the block (0-indexed)
124
- /// @param bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
125
- /// lowest height first
126
- function sweep(
127
- bytes4 txVersion,
128
- bytes memory txInputVector,
129
- bytes memory txOutput,
130
- bytes4 txLocktime,
131
- bytes memory merkleProof,
132
- uint256 txIndexInBlock,
133
- bytes memory bitcoinHeaders
789
+ /// @param sweepTx Bitcoin sweep transaction data
790
+ /// @param sweepProof Bitcoin sweep proof data
791
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
792
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
793
+ /// this parameter is ignored
794
+ /// @dev Requirements:
795
+ /// - `sweepTx` components must match the expected structure. See
796
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
797
+ /// correspond to appropriate Bitcoin transaction fields to produce
798
+ /// a provable transaction hash.
799
+ /// - The `sweepTx` should represent a Bitcoin transaction with 1..n
800
+ /// inputs. If the wallet has no main UTXO, all n inputs should
801
+ /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has
802
+ /// an existing main UTXO, one of the n inputs must point to that
803
+ /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH
804
+ /// revealed deposits UTXOs. That transaction must have only
805
+ /// one P2(W)PKH output locking funds on the 20-byte wallet public
806
+ /// key hash.
807
+ /// - `sweepProof` components must match the expected structure. See
808
+ /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
809
+ /// field must contain a valid number of block headers, not less
810
+ /// than the `txProofDifficultyFactor` contract constant.
811
+ /// - `mainUtxo` components must point to the recent main UTXO
812
+ /// of the given wallet, as currently known on the Ethereum chain.
813
+ /// If there is no main UTXO, this parameter is ignored.
814
+ function submitSweepProof(
815
+ BitcoinTx.Info calldata sweepTx,
816
+ BitcoinTx.Proof calldata sweepProof,
817
+ BitcoinTx.UTXO calldata mainUtxo
818
+ ) external {
819
+ // TODO: Fail early if the function call gets frontrunned. See discussion:
820
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
821
+
822
+ // The actual transaction proof is performed here. After that point, we
823
+ // can assume the transaction happened on Bitcoin chain and has
824
+ // a sufficient number of confirmations as determined by
825
+ // `txProofDifficultyFactor` constant.
826
+ bytes32 sweepTxHash = BitcoinTx.validateProof(
827
+ sweepTx,
828
+ sweepProof,
829
+ proofDifficultyContext()
830
+ );
831
+
832
+ // Process sweep transaction output and extract its target wallet
833
+ // public key hash and value.
834
+ (
835
+ bytes20 walletPubKeyHash,
836
+ uint64 sweepTxOutputValue
837
+ ) = processSweepTxOutput(sweepTx.outputVector);
838
+
839
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
840
+ walletPubKeyHash
841
+ ];
842
+
843
+ Wallets.WalletState walletState = wallet.state;
844
+ require(
845
+ walletState == Wallets.WalletState.Live ||
846
+ walletState == Wallets.WalletState.MovingFunds,
847
+ "Wallet must be in Live or MovingFunds state"
848
+ );
849
+
850
+ // Check if the main UTXO for given wallet exists. If so, validate
851
+ // passed main UTXO data against the stored hash and use them for
852
+ // further processing. If no main UTXO exists, use empty data.
853
+ BitcoinTx.UTXO memory resolvedMainUtxo = BitcoinTx.UTXO(
854
+ bytes32(0),
855
+ 0,
856
+ 0
857
+ );
858
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
859
+ if (mainUtxoHash != bytes32(0)) {
860
+ require(
861
+ keccak256(
862
+ abi.encodePacked(
863
+ mainUtxo.txHash,
864
+ mainUtxo.txOutputIndex,
865
+ mainUtxo.txOutputValue
866
+ )
867
+ ) == mainUtxoHash,
868
+ "Invalid main UTXO data"
869
+ );
870
+ resolvedMainUtxo = mainUtxo;
871
+ }
872
+
873
+ // Process sweep transaction inputs and extract all information needed
874
+ // to perform deposit bookkeeping.
875
+ SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(
876
+ sweepTx.inputVector,
877
+ resolvedMainUtxo
878
+ );
879
+
880
+ // Helper variable that will hold the sum of treasury fees paid by
881
+ // all deposits.
882
+ uint256 totalTreasuryFee = 0;
883
+
884
+ // Determine the transaction fee that should be incurred by each deposit
885
+ // and the indivisible remainder that should be additionally incurred
886
+ // by the last deposit.
887
+ (
888
+ uint256 depositTxFee,
889
+ uint256 depositTxFeeRemainder
890
+ ) = sweepTxFeeDistribution(
891
+ inputsInfo.inputsTotalValue,
892
+ sweepTxOutputValue,
893
+ inputsInfo.depositedAmounts.length
894
+ );
895
+
896
+ // Make sure the highest value of the deposit transaction fee does not
897
+ // exceed the maximum value limited by the governable parameter.
898
+ require(
899
+ depositTxFee + depositTxFeeRemainder <= depositTxMaxFee,
900
+ "Transaction fee is too high"
901
+ );
902
+
903
+ // Reduce each deposit amount by treasury fee and transaction fee.
904
+ for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {
905
+ // The last deposit should incur the deposit transaction fee
906
+ // remainder.
907
+ uint256 depositTxFeeIncurred = i ==
908
+ inputsInfo.depositedAmounts.length - 1
909
+ ? depositTxFee + depositTxFeeRemainder
910
+ : depositTxFee;
911
+
912
+ // There is no need to check whether
913
+ // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`
914
+ // since the `depositDustThreshold` should force that condition
915
+ // to be always true.
916
+ inputsInfo.depositedAmounts[i] =
917
+ inputsInfo.depositedAmounts[i] -
918
+ inputsInfo.treasuryFees[i] -
919
+ depositTxFeeIncurred;
920
+ totalTreasuryFee += inputsInfo.treasuryFees[i];
921
+ }
922
+
923
+ // Record this sweep data and assign them to the wallet public key hash
924
+ // as new main UTXO. Transaction output index is always 0 as sweep
925
+ // transaction always contains only one output.
926
+ wallet.mainUtxoHash = keccak256(
927
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
928
+ );
929
+
930
+ emit DepositsSwept(walletPubKeyHash, sweepTxHash);
931
+
932
+ // Update depositors balances in the Bank.
933
+ bank.increaseBalances(
934
+ inputsInfo.depositors,
935
+ inputsInfo.depositedAmounts
936
+ );
937
+ // Pass the treasury fee to the treasury address.
938
+ bank.increaseBalance(treasury, totalTreasuryFee);
939
+
940
+ // TODO: Handle deposits having `vault` set.
941
+ }
942
+
943
+ /// @notice Processes the Bitcoin sweep transaction output vector by
944
+ /// extracting the single output and using it to gain additional
945
+ /// information required for further processing (e.g. value and
946
+ /// wallet public key hash).
947
+ /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.
948
+ /// This function assumes vector's structure is valid so it must be
949
+ /// validated using e.g. `BTCUtils.validateVout` function before
950
+ /// it is passed here
951
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
952
+ /// @return value 8-byte sweep transaction output value.
953
+ function processSweepTxOutput(bytes memory sweepTxOutputVector)
954
+ internal
955
+ pure
956
+ returns (bytes20 walletPubKeyHash, uint64 value)
957
+ {
958
+ // To determine the total number of sweep transaction outputs, we need to
959
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
960
+ // That compactSize uint encodes the number of vector elements using the
961
+ // format presented in:
962
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
963
+ // We don't need asserting the compactSize uint is parseable since it
964
+ // was already checked during `validateVout` validation.
965
+ // See `BitcoinTx.outputVector` docs for more details.
966
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
967
+ require(
968
+ outputsCount == 1,
969
+ "Sweep transaction must have a single output"
970
+ );
971
+
972
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
973
+ value = output.extractValue();
974
+ bytes memory walletPubKeyHashBytes = output.extractHash();
975
+ // The sweep transaction output should always be P2PKH or P2WPKH.
976
+ // In both cases, the wallet public key hash should be 20 bytes length.
977
+ require(
978
+ walletPubKeyHashBytes.length == 20,
979
+ "Wallet public key hash should have 20 bytes"
980
+ );
981
+ /* solhint-disable-next-line no-inline-assembly */
982
+ assembly {
983
+ walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))
984
+ }
985
+
986
+ return (walletPubKeyHash, value);
987
+ }
988
+
989
+ /// @notice Processes the Bitcoin sweep transaction input vector. It
990
+ /// extracts each input and tries to obtain associated deposit or
991
+ /// main UTXO data, depending on the input type. Reverts
992
+ /// if one of the inputs cannot be recognized as a pointer to a
993
+ /// revealed deposit or expected main UTXO.
994
+ /// This function also marks each processed deposit as swept.
995
+ /// @param sweepTxInputVector Bitcoin sweep transaction input vector.
996
+ /// This function assumes vector's structure is valid so it must be
997
+ /// validated using e.g. `BTCUtils.validateVin` function before
998
+ /// it is passed here
999
+ /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO
1000
+ /// exists for the given the wallet, this parameter's fields should
1001
+ /// be zeroed to bypass the main UTXO validation
1002
+ /// @return info Outcomes of the processing.
1003
+ function processSweepTxInputs(
1004
+ bytes memory sweepTxInputVector,
1005
+ BitcoinTx.UTXO memory mainUtxo
1006
+ ) internal returns (SweepTxInputsInfo memory info) {
1007
+ // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO
1008
+ // for the given wallet doesn't exist and it is not expected to be
1009
+ // included in the sweep transaction input vector.
1010
+ bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);
1011
+ bool mainUtxoFound = false;
1012
+
1013
+ // Determining the total number of sweep transaction inputs in the same
1014
+ // way as for number of outputs. See `BitcoinTx.inputVector` docs for
1015
+ // more details.
1016
+ (
1017
+ uint256 inputsCompactSizeUintLength,
1018
+ uint256 inputsCount
1019
+ ) = sweepTxInputVector.parseVarInt();
1020
+
1021
+ // To determine the first input starting index, we must jump over
1022
+ // the compactSize uint which prepends the input vector. One byte
1023
+ // must be added because `BtcUtils.parseVarInt` does not include
1024
+ // compactSize uint tag in the returned length.
1025
+ //
1026
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1027
+ // returns `0`, so we jump over one byte of compactSize uint.
1028
+ //
1029
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1030
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1031
+ // tag byte included) so we need to jump over 1+2 bytes of
1032
+ // compactSize uint.
1033
+ //
1034
+ // Please refer `BTCUtils` library and compactSize uint
1035
+ // docs in `BitcoinTx` library for more details.
1036
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
1037
+
1038
+ // Determine the swept deposits count. If main UTXO is NOT expected,
1039
+ // all inputs should be deposits. If main UTXO is expected, one input
1040
+ // should point to that main UTXO.
1041
+ info.depositors = new address[](
1042
+ !mainUtxoExpected ? inputsCount : inputsCount - 1
1043
+ );
1044
+ info.depositedAmounts = new uint256[](info.depositors.length);
1045
+ info.treasuryFees = new uint256[](info.depositors.length);
1046
+
1047
+ // Initialize helper variables.
1048
+ uint256 processedDepositsCount = 0;
1049
+
1050
+ // Inputs processing loop.
1051
+ for (uint256 i = 0; i < inputsCount; i++) {
1052
+ (
1053
+ bytes32 outpointTxHash,
1054
+ uint32 outpointIndex,
1055
+ uint256 inputLength
1056
+ ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
1057
+
1058
+ DepositRequest storage deposit = deposits[
1059
+ uint256(
1060
+ keccak256(abi.encodePacked(outpointTxHash, outpointIndex))
1061
+ )
1062
+ ];
1063
+
1064
+ if (deposit.revealedAt != 0) {
1065
+ // If we entered here, that means the input was identified as
1066
+ // a revealed deposit.
1067
+ require(deposit.sweptAt == 0, "Deposit already swept");
1068
+
1069
+ if (processedDepositsCount == info.depositors.length) {
1070
+ // If this condition is true, that means a deposit input
1071
+ // took place of an expected main UTXO input.
1072
+ // In other words, there is no expected main UTXO
1073
+ // input and all inputs come from valid, revealed deposits.
1074
+ revert(
1075
+ "Expected main UTXO not present in sweep transaction inputs"
1076
+ );
1077
+ }
1078
+
1079
+ /* solhint-disable-next-line not-rely-on-time */
1080
+ deposit.sweptAt = uint32(block.timestamp);
1081
+
1082
+ info.depositors[processedDepositsCount] = deposit.depositor;
1083
+ info.depositedAmounts[processedDepositsCount] = deposit.amount;
1084
+ info.inputsTotalValue += info.depositedAmounts[
1085
+ processedDepositsCount
1086
+ ];
1087
+ info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;
1088
+
1089
+ processedDepositsCount++;
1090
+ } else if (
1091
+ mainUtxoExpected != mainUtxoFound &&
1092
+ mainUtxo.txHash == outpointTxHash
1093
+ ) {
1094
+ // If we entered here, that means the input was identified as
1095
+ // the expected main UTXO.
1096
+ info.inputsTotalValue += mainUtxo.txOutputValue;
1097
+ mainUtxoFound = true;
1098
+
1099
+ // Main UTXO used as an input, mark it as spent.
1100
+ spentMainUTXOs[
1101
+ uint256(
1102
+ keccak256(
1103
+ abi.encodePacked(outpointTxHash, outpointIndex)
1104
+ )
1105
+ )
1106
+ ] = true;
1107
+ } else {
1108
+ revert("Unknown input type");
1109
+ }
1110
+
1111
+ // Make the `inputStartingIndex` pointing to the next input by
1112
+ // increasing it by current input's length.
1113
+ inputStartingIndex += inputLength;
1114
+ }
1115
+
1116
+ // Construction of the input processing loop guarantees that:
1117
+ // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`
1118
+ // is always true at this point. We just use the first variable
1119
+ // to assert the total count of swept deposit is bigger than zero.
1120
+ require(
1121
+ processedDepositsCount > 0,
1122
+ "Sweep transaction must process at least one deposit"
1123
+ );
1124
+
1125
+ // Assert the main UTXO was used as one of current sweep's inputs if
1126
+ // it was actually expected.
1127
+ require(
1128
+ mainUtxoExpected == mainUtxoFound,
1129
+ "Expected main UTXO not present in sweep transaction inputs"
1130
+ );
1131
+
1132
+ return info;
1133
+ }
1134
+
1135
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
1136
+ /// @param inputVector Bitcoin transaction input vector
1137
+ /// @param inputStartingIndex Index the given input starts at
1138
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1139
+ /// pointed in the given input's outpoint.
1140
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1141
+ /// which is pointed in the given input's outpoint.
1142
+ /// @return inputLength Byte length of the given input.
1143
+ /// @dev This function assumes vector's structure is valid so it must be
1144
+ /// validated using e.g. `BTCUtils.validateVin` function before it
1145
+ /// is passed here.
1146
+ function parseTxInputAt(
1147
+ bytes memory inputVector,
1148
+ uint256 inputStartingIndex
1149
+ )
1150
+ internal
1151
+ pure
1152
+ returns (
1153
+ bytes32 outpointTxHash,
1154
+ uint32 outpointIndex,
1155
+ uint256 inputLength
1156
+ )
1157
+ {
1158
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
1159
+
1160
+ outpointIndex = BTCUtils.reverseUint32(
1161
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
1162
+ );
1163
+
1164
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
1165
+
1166
+ return (outpointTxHash, outpointIndex, inputLength);
1167
+ }
1168
+
1169
+ /// @notice Determines the distribution of the sweep transaction fee
1170
+ /// over swept deposits.
1171
+ /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.
1172
+ /// @param sweepTxOutputValue Value of the sweep transaction output.
1173
+ /// @param depositsCount Count of the deposits swept by the sweep transaction.
1174
+ /// @return depositTxFee Transaction fee per deposit determined by evenly
1175
+ /// spreading the divisible part of the sweep transaction fee
1176
+ /// over all deposits.
1177
+ /// @return depositTxFeeRemainder The indivisible part of the sweep
1178
+ /// transaction fee than cannot be distributed over all deposits.
1179
+ /// @dev It is up to the caller to decide how the remainder should be
1180
+ /// counted in. This function only computes its value.
1181
+ function sweepTxFeeDistribution(
1182
+ uint256 sweepTxInputsTotalValue,
1183
+ uint256 sweepTxOutputValue,
1184
+ uint256 depositsCount
1185
+ )
1186
+ internal
1187
+ pure
1188
+ returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)
1189
+ {
1190
+ // The sweep transaction fee is just the difference between inputs
1191
+ // amounts sum and the output amount.
1192
+ uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;
1193
+ // Compute the indivisible remainder that remains after dividing the
1194
+ // sweep transaction fee over all deposits evenly.
1195
+ depositTxFeeRemainder = sweepTxFee % depositsCount;
1196
+ // Compute the transaction fee per deposit by dividing the sweep
1197
+ // transaction fee (reduced by the remainder) by the number of deposits.
1198
+ depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;
1199
+
1200
+ return (depositTxFee, depositTxFeeRemainder);
1201
+ }
1202
+
1203
+ /// @notice Requests redemption of the given amount from the specified
1204
+ /// wallet to the redeemer Bitcoin output script.
1205
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
1206
+ /// using Bitcoin HASH160 over the compressed ECDSA public key)
1207
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1208
+ /// the Ethereum chain
1209
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
1210
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
1211
+ /// redeemed BTC
1212
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
1213
+ /// that is taken from redeemer's balance in the Bank upon request.
1214
+ /// Once the request is handled, the actual amount of BTC locked
1215
+ /// on the redeemer output script will be always lower than this value
1216
+ /// since the treasury and Bitcoin transaction fees must be incurred.
1217
+ /// The minimal amount satisfying the request can be computed as:
1218
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
1219
+ /// Fees values are taken at the moment of request creation.
1220
+ /// @dev Requirements:
1221
+ /// - Wallet behind `walletPubKeyHash` must be live
1222
+ /// - `mainUtxo` components must point to the recent main UTXO
1223
+ /// of the given wallet, as currently known on the Ethereum chain.
1224
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
1225
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
1226
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
1227
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
1228
+ /// used for only one pending request at the same time
1229
+ /// - Wallet must have enough Bitcoin balance to proceed the request
1230
+ /// - Redeemer must make an allowance in the Bank that the Bridge
1231
+ /// contract can spend the given `amount`.
1232
+ function requestRedemption(
1233
+ bytes20 walletPubKeyHash,
1234
+ BitcoinTx.UTXO calldata mainUtxo,
1235
+ bytes calldata redeemerOutputScript,
1236
+ uint64 amount
1237
+ ) external {
1238
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
1239
+ walletPubKeyHash
1240
+ ];
1241
+
1242
+ require(
1243
+ wallet.state == Wallets.WalletState.Live,
1244
+ "Wallet must be in Live state"
1245
+ );
1246
+
1247
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
1248
+ require(
1249
+ mainUtxoHash != bytes32(0),
1250
+ "No main UTXO for the given wallet"
1251
+ );
1252
+ require(
1253
+ keccak256(
1254
+ abi.encodePacked(
1255
+ mainUtxo.txHash,
1256
+ mainUtxo.txOutputIndex,
1257
+ mainUtxo.txOutputValue
1258
+ )
1259
+ ) == mainUtxoHash,
1260
+ "Invalid main UTXO data"
1261
+ );
1262
+
1263
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1264
+ // if it is the oldest one who can handle the request. This will
1265
+ // be suggested by the dApp but may not be respected by users who
1266
+ // interact directly with the contract. Do we need to enforce it
1267
+ // here? One option is not to enforce it, to save on gas, but if
1268
+ // we see this rule is not respected, upgrade Bridge contract to
1269
+ // require it.
1270
+
1271
+ // Validate if redeemer output script is a correct standard type
1272
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1273
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1274
+ // a function extracts the payload properly only from standard outputs
1275
+ // so if it succeeds, we have a guarantee the redeemer output script
1276
+ // is proper. Worth to note `extractHash` ignores the value at all
1277
+ // so this is why we can use 0 safely. This way of validation is the
1278
+ // same as in tBTC v1.
1279
+ bytes memory redeemerOutputScriptPayload = abi
1280
+ .encodePacked(bytes8(0), redeemerOutputScript)
1281
+ .extractHash();
1282
+ require(
1283
+ redeemerOutputScriptPayload.length > 0,
1284
+ "Redeemer output script must be a standard type"
1285
+ );
1286
+ // Check if the redeemer output script payload does not point to the
1287
+ // wallet public key hash.
1288
+ require(
1289
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
1290
+ keccak256(redeemerOutputScriptPayload),
1291
+ "Redeemer output script must not point to the wallet PKH"
1292
+ );
1293
+
1294
+ require(
1295
+ amount >= redemptionDustThreshold,
1296
+ "Redemption amount too small"
1297
+ );
1298
+
1299
+ // The redemption key is built on top of the wallet public key hash
1300
+ // and redeemer output script pair. That means there can be only one
1301
+ // request asking for redemption from the given wallet to the given
1302
+ // BTC script at the same time.
1303
+ uint256 redemptionKey = uint256(
1304
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1305
+ );
1306
+
1307
+ // Check if given redemption key is not used by a pending redemption.
1308
+ // There is no need to check for existence in `timedOutRedemptions`
1309
+ // since the wallet's state is changed to other than Live after
1310
+ // first time out is reported so making new requests is not possible.
1311
+ // slither-disable-next-line incorrect-equality
1312
+ require(
1313
+ pendingRedemptions[redemptionKey].requestedAt == 0,
1314
+ "There is a pending redemption request from this wallet to the same address"
1315
+ );
1316
+
1317
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
1318
+ // since the `redemptionDustThreshold` should force that condition
1319
+ // to be always true.
1320
+ uint64 treasuryFee = redemptionTreasuryFeeDivisor > 0
1321
+ ? amount / redemptionTreasuryFeeDivisor
1322
+ : 0;
1323
+ uint64 txMaxFee = redemptionTxMaxFee;
1324
+
1325
+ // The main wallet UTXO's value doesn't include all pending redemptions.
1326
+ // To determine if the requested redemption can be performed by the
1327
+ // wallet we need to subtract the total value of all pending redemptions
1328
+ // from that wallet's main UTXO value. Given that the treasury fee is
1329
+ // not redeemed from the wallet, we are subtracting it.
1330
+ wallet.pendingRedemptionsValue += amount - treasuryFee;
1331
+ require(
1332
+ mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
1333
+ "Insufficient wallet funds"
1334
+ );
1335
+
1336
+ pendingRedemptions[redemptionKey] = RedemptionRequest(
1337
+ msg.sender,
1338
+ amount,
1339
+ treasuryFee,
1340
+ txMaxFee,
1341
+ /* solhint-disable-next-line not-rely-on-time */
1342
+ uint32(block.timestamp)
1343
+ );
1344
+
1345
+ emit RedemptionRequested(
1346
+ walletPubKeyHash,
1347
+ redeemerOutputScript,
1348
+ msg.sender,
1349
+ amount,
1350
+ treasuryFee,
1351
+ txMaxFee
1352
+ );
1353
+
1354
+ bank.transferBalanceFrom(msg.sender, address(this), amount);
1355
+ }
1356
+
1357
+ /// @notice Used by the wallet to prove the BTC redemption transaction
1358
+ /// and to make the necessary bookkeeping. Redemption is only
1359
+ /// accepted if it satisfies SPV proof.
1360
+ ///
1361
+ /// The function is performing Bank balance updates by burning
1362
+ /// the total redeemed Bitcoin amount from Bridge balance and
1363
+ /// transferring the treasury fee sum to the treasury address.
1364
+ ///
1365
+ /// It is possible to prove the given redemption only one time.
1366
+ /// @param redemptionTx Bitcoin redemption transaction data
1367
+ /// @param redemptionProof Bitcoin redemption proof data
1368
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1369
+ /// the Ethereum chain
1370
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1371
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
1372
+ /// performed the redemption transaction
1373
+ /// @dev Requirements:
1374
+ /// - `redemptionTx` components must match the expected structure. See
1375
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
1376
+ /// correspond to appropriate Bitcoin transaction fields to produce
1377
+ /// a provable transaction hash.
1378
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
1379
+ /// exactly 1 input that refers to the wallet's main UTXO. That
1380
+ /// transaction should have 1..n outputs handling existing pending
1381
+ /// redemption requests or pointing to reported timed out requests.
1382
+ /// There can be also 1 optional output representing the
1383
+ /// change and pointing back to the 20-byte wallet public key hash.
1384
+ /// The change should be always present if the redeemed value sum
1385
+ /// is lower than the total wallet's BTC balance.
1386
+ /// - `redemptionProof` components must match the expected structure.
1387
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
1388
+ /// field must contain a valid number of block headers, not less
1389
+ /// than the `txProofDifficultyFactor` contract constant.
1390
+ /// - `mainUtxo` components must point to the recent main UTXO
1391
+ /// of the given wallet, as currently known on the Ethereum chain.
1392
+ /// Additionally, the recent main UTXO on Ethereum must be set.
1393
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
1394
+ /// as transaction single input.
1395
+ /// Other remarks:
1396
+ /// - Putting the change output as the first transaction output can
1397
+ /// save some gas because the output processing loop begins each
1398
+ /// iteration by checking whether the given output is the change
1399
+ /// thus uses some gas for making the comparison. Once the change
1400
+ /// is identified, that check is omitted in further iterations.
1401
+ function submitRedemptionProof(
1402
+ BitcoinTx.Info calldata redemptionTx,
1403
+ BitcoinTx.Proof calldata redemptionProof,
1404
+ BitcoinTx.UTXO calldata mainUtxo,
1405
+ bytes20 walletPubKeyHash
1406
+ ) external {
1407
+ // TODO: Just as for `submitSweepProof`, fail early if the function
1408
+ // call gets frontrunned. See discussion:
1409
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1410
+
1411
+ // The actual transaction proof is performed here. After that point, we
1412
+ // can assume the transaction happened on Bitcoin chain and has
1413
+ // a sufficient number of confirmations as determined by
1414
+ // `txProofDifficultyFactor` constant.
1415
+ bytes32 redemptionTxHash = BitcoinTx.validateProof(
1416
+ redemptionTx,
1417
+ redemptionProof,
1418
+ proofDifficultyContext()
1419
+ );
1420
+
1421
+ // Perform validation of the redemption transaction input. Specifically,
1422
+ // check if it refers to the expected wallet's main UTXO.
1423
+ validateRedemptionTxInput(
1424
+ redemptionTx.inputVector,
1425
+ mainUtxo,
1426
+ walletPubKeyHash
1427
+ );
1428
+
1429
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
1430
+ walletPubKeyHash
1431
+ ];
1432
+
1433
+ Wallets.WalletState walletState = wallet.state;
1434
+ require(
1435
+ walletState == Wallets.WalletState.Live ||
1436
+ walletState == Wallets.WalletState.MovingFunds,
1437
+ "Wallet must be in Live or MovingFuds state"
1438
+ );
1439
+
1440
+ // Process redemption transaction outputs to extract some info required
1441
+ // for further processing.
1442
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
1443
+ redemptionTx.outputVector,
1444
+ walletPubKeyHash
1445
+ );
1446
+
1447
+ if (outputsInfo.changeValue > 0) {
1448
+ // If the change value is grater than zero, it means the change
1449
+ // output exists and can be used as new wallet's main UTXO.
1450
+ wallet.mainUtxoHash = keccak256(
1451
+ abi.encodePacked(
1452
+ redemptionTxHash,
1453
+ outputsInfo.changeIndex,
1454
+ outputsInfo.changeValue
1455
+ )
1456
+ );
1457
+ } else {
1458
+ // If the change value is zero, it means the change output doesn't
1459
+ // exists and no funds left on the wallet. Delete the main UTXO
1460
+ // for that wallet to represent that state in a proper way.
1461
+ delete wallet.mainUtxoHash;
1462
+ }
1463
+
1464
+ wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
1465
+
1466
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1467
+
1468
+ bank.decreaseBalance(outputsInfo.totalBurnableValue);
1469
+ bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1470
+ }
1471
+
1472
+ /// @notice Submits a fraud challenge indicating that a UTXO being under
1473
+ /// wallet control was unlocked by the wallet but was not used
1474
+ /// according to the protocol rules. That means the wallet signed
1475
+ /// a transaction input pointing to that UTXO and there is a unique
1476
+ /// sighash and signature pair associated with that input. This
1477
+ /// function uses those parameters to create a fraud accusation that
1478
+ /// proves a given transaction input unlocking the given UTXO was
1479
+ /// actually signed by the wallet. This function cannot determine
1480
+ /// whether the transaction was actually broadcast and the input was
1481
+ /// consumed in a fraudulent way so it just opens a challenge period
1482
+ /// during which the wallet can defeat the challenge by submitting
1483
+ /// proof of a transaction that consumes the given input according
1484
+ /// to protocol rules. To prevent spurious allegations, the caller
1485
+ /// must deposit ETH that is returned back upon justified fraud
1486
+ /// challenge or confiscated otherwise.
1487
+ /// @param walletPublicKey The public key of the wallet in the uncompressed
1488
+ /// and unprefixed format (64 bytes)
1489
+ /// @param sighash The hash that was used to produce the ECDSA signature
1490
+ /// that is the subject of the fraud claim. This hash is constructed
1491
+ /// by applying double SHA-256 over a serialized subset of the
1492
+ /// transaction. The exact subset used as hash preimage depends on
1493
+ /// the transaction input the signature is produced for. See BIP-143
1494
+ /// for reference
1495
+ /// @param signature Bitcoin signature in the R/S/V format
1496
+ /// @dev Requirements:
1497
+ /// - Wallet behind `walletPubKey` must be in `Live` or `MovingFunds`
1498
+ /// state
1499
+ /// - The challenger must send appropriate amount of ETH used as
1500
+ /// fraud challenge deposit
1501
+ /// - The signature (represented by r, s and v) must be generated by
1502
+ /// the wallet behind `walletPubKey` during signing of `sighash`
1503
+ /// - Wallet can be challenged for the given signature only once
1504
+ /// TODO: Consider using wallet public key in the X/Y form to avoid slicing.
1505
+ function submitFraudChallenge(
1506
+ bytes calldata walletPublicKey,
1507
+ bytes32 sighash,
1508
+ BitcoinTx.RSVSignature calldata signature
1509
+ ) external payable {
1510
+ bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(
1511
+ walletPublicKey.slice32(0),
1512
+ walletPublicKey.slice32(32)
1513
+ );
1514
+ bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();
1515
+
1516
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
1517
+ walletPubKeyHash
1518
+ ];
1519
+
1520
+ require(
1521
+ wallet.state == Wallets.WalletState.Live ||
1522
+ wallet.state == Wallets.WalletState.MovingFunds,
1523
+ "Wallet is neither in Live nor MovingFunds state"
1524
+ );
1525
+
1526
+ frauds.submitFraudChallenge(
1527
+ walletPublicKey,
1528
+ walletPubKeyHash,
1529
+ sighash,
1530
+ signature
1531
+ );
1532
+ }
1533
+
1534
+ /// @notice Allows to defeat a pending fraud challenge against a wallet if
1535
+ /// the transaction that spends the UTXO follows the protocol rules.
1536
+ /// In order to defeat the challenge the same `walletPublicKey` and
1537
+ /// signature (represented by `r`, `s` and `v`) must be provided as
1538
+ /// were used in the fraud challenge. Additionally a preimage must
1539
+ /// be provided which was used to calculate the sighash during input
1540
+ /// signing. The fraud challenge defeat attempt will only succeed if
1541
+ /// the inputs in the preimage are considered honestly spent by the
1542
+ /// wallet. Therefore the transaction spending the UTXO must be
1543
+ /// proven in the Bridge before a challenge defeat is called.
1544
+ /// If successfully defeated, the fraud challenge is marked as
1545
+ /// resolved and the amount of ether deposited by the challenger is
1546
+ /// sent to the treasury.
1547
+ /// @param walletPublicKey The public key of the wallet in the uncompressed
1548
+ /// and unprefixed format (64 bytes)
1549
+ /// @param preimage The preimage which produces sighash used to generate the
1550
+ /// ECDSA signature that is the subject of the fraud claim. It is a
1551
+ /// serialized subset of the transaction. The exact subset used as
1552
+ /// the preimage depends on the transaction input the signature is
1553
+ /// produced for. See BIP-143 for reference
1554
+ /// @param witness Flag indicating whether the preimage was produced for a
1555
+ /// witness input. True for witness, false for non-witness input
1556
+ /// @dev Requirements:
1557
+ /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`
1558
+ /// must identify an open fraud challenge
1559
+ /// - the preimage must be a valid preimage of a transaction generated
1560
+ /// according to the protocol rules and already proved in the Bridge
1561
+ /// - before a defeat attempt is made the transaction that spends the
1562
+ /// given UTXO must be proven in the Bridge
1563
+ /// TODO: Consider using wallet public key in the X/Y form to avoid slicing.
1564
+ function defeatFraudChallenge(
1565
+ bytes calldata walletPublicKey,
1566
+ bytes calldata preimage,
1567
+ bool witness
1568
+ ) external {
1569
+ uint256 utxoKey = frauds.unwrapChallenge(
1570
+ walletPublicKey,
1571
+ preimage,
1572
+ witness
1573
+ );
1574
+
1575
+ // Check that the UTXO key identifies a correctly spent UTXO.
1576
+ require(
1577
+ deposits[utxoKey].sweptAt > 0 || spentMainUTXOs[utxoKey],
1578
+ "Spent UTXO not found among correctly spent UTXOs"
1579
+ );
1580
+
1581
+ frauds.defeatChallenge(walletPublicKey, preimage, treasury);
1582
+ }
1583
+
1584
+ /// @notice Notifies about defeat timeout for the given fraud challenge.
1585
+ /// Can be called only if there was a fraud challenge identified by
1586
+ /// the provided `walletPublicKey` and `sighash` and it was not
1587
+ /// defeated on time. The amount of time that needs to pass after
1588
+ /// a fraud challenge is reported is indicated by the
1589
+ /// `challengeDefeatTimeout`. After a successful fraud challenge
1590
+ /// defeat timeout notification the fraud challenge is marked as
1591
+ /// resolved, the stake of each operator is slashed, the ether
1592
+ /// deposited is returned to the challenger and the challenger is
1593
+ /// rewarded.
1594
+ /// @param walletPublicKey The public key of the wallet in the uncompressed
1595
+ /// and unprefixed format (64 bytes)
1596
+ /// @param sighash The hash that was used to produce the ECDSA signature
1597
+ /// that is the subject of the fraud claim. This hash is constructed
1598
+ /// by applying double SHA-256 over a serialized subset of the
1599
+ /// transaction. The exact subset used as hash preimage depends on
1600
+ /// the transaction input the signature is produced for. See BIP-143
1601
+ /// for reference
1602
+ /// @dev Requirements:
1603
+ /// - `walletPublicKey`and `sighash` must identify an open fraud
1604
+ /// challenge
1605
+ /// - the amount of time indicated by `challengeDefeatTimeout` must
1606
+ /// pass after the challenge was reported
1607
+ /// TODO: Consider using wallet public key in the X/Y form to avoid slicing.
1608
+ function notifyFraudChallengeDefeatTimeout(
1609
+ bytes calldata walletPublicKey,
1610
+ bytes32 sighash
134
1611
  ) external {
135
- // TODO We need to read `fundingTxHash`, `fundingOutputIndex` and
136
- // P2SH script depositor address from `txInputVector`.
137
- // We then hash them to obtain deposit identifier and read
138
- // DepositInfo. From DepositInfo we know what amount was declared
139
- // by the depositor in their reveal transaction and we use that
140
- // amount to update their Bank balance, minus fee.
1612
+ frauds.notifyFraudChallengeDefeatTimeout(walletPublicKey, sighash);
1613
+ }
1614
+
1615
+ /// @notice Returns parameters used by the `Frauds` library.
1616
+ /// @return slashingAmount Value of the slashing amount
1617
+ /// @return notifierRewardMultiplier Value of the notifier reward multiplier
1618
+ /// @return challengeDefeatTimeout Value of the challenge defeat timeout
1619
+ /// @return challengeDepositAmount Value of the challenge deposit amount
1620
+ function getFraudParameters()
1621
+ external
1622
+ view
1623
+ returns (
1624
+ uint256 slashingAmount,
1625
+ uint256 notifierRewardMultiplier,
1626
+ uint256 challengeDefeatTimeout,
1627
+ uint256 challengeDepositAmount
1628
+ )
1629
+ {
1630
+ slashingAmount = frauds.slashingAmount;
1631
+ notifierRewardMultiplier = frauds.notifierRewardMultiplier;
1632
+ challengeDefeatTimeout = frauds.challengeDefeatTimeout;
1633
+ challengeDepositAmount = frauds.challengeDepositAmount;
1634
+
1635
+ return (
1636
+ slashingAmount,
1637
+ notifierRewardMultiplier,
1638
+ challengeDefeatTimeout,
1639
+ challengeDepositAmount
1640
+ );
1641
+ }
1642
+
1643
+ /// @notice Returns the fraud challenge identified by the given key built
1644
+ /// as keccak256(walletPublicKey|sighash|v|r|s).
1645
+ function fraudChallenges(uint256 challengeKey)
1646
+ external
1647
+ view
1648
+ returns (Frauds.FraudChallenge memory)
1649
+ {
1650
+ return frauds.challenges[challengeKey];
1651
+ }
1652
+
1653
+ /// @notice Validates whether the redemption Bitcoin transaction input
1654
+ /// vector contains a single input referring to the wallet's main
1655
+ /// UTXO. Reverts in case the validation fails.
1656
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1657
+ /// vector. This function assumes vector's structure is valid so it
1658
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1659
+ /// before it is passed here
1660
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1661
+ /// the Ethereum chain.
1662
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1663
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1664
+ /// performed the redemption transaction.
1665
+ function validateRedemptionTxInput(
1666
+ bytes memory redemptionTxInputVector,
1667
+ BitcoinTx.UTXO calldata mainUtxo,
1668
+ bytes20 walletPubKeyHash
1669
+ ) internal {
1670
+ // Assert that main UTXO for passed wallet exists in storage.
1671
+ bytes32 mainUtxoHash = wallets
1672
+ .registeredWallets[walletPubKeyHash]
1673
+ .mainUtxoHash;
1674
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1675
+
1676
+ // Assert that passed main UTXO parameter is the same as in storage and
1677
+ // can be used for further processing.
1678
+ require(
1679
+ keccak256(
1680
+ abi.encodePacked(
1681
+ mainUtxo.txHash,
1682
+ mainUtxo.txOutputIndex,
1683
+ mainUtxo.txOutputValue
1684
+ )
1685
+ ) == mainUtxoHash,
1686
+ "Invalid main UTXO data"
1687
+ );
1688
+
1689
+ // Assert that the single redemption transaction input actually
1690
+ // refers to the wallet's main UTXO.
1691
+ (
1692
+ bytes32 redemptionTxOutpointTxHash,
1693
+ uint32 redemptionTxOutpointIndex
1694
+ ) = processRedemptionTxInput(redemptionTxInputVector);
1695
+ require(
1696
+ mainUtxo.txHash == redemptionTxOutpointTxHash &&
1697
+ mainUtxo.txOutputIndex == redemptionTxOutpointIndex,
1698
+ "Redemption transaction input must point to the wallet's main UTXO"
1699
+ );
1700
+
1701
+ // Main UTXO used as an input, mark it as spent.
1702
+ spentMainUTXOs[
1703
+ uint256(
1704
+ keccak256(
1705
+ abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
1706
+ )
1707
+ )
1708
+ ] = true;
1709
+ }
1710
+
1711
+ /// @notice Processes the Bitcoin redemption transaction input vector. It
1712
+ /// extracts the single input then the transaction hash and output
1713
+ /// index from its outpoint.
1714
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1715
+ /// vector. This function assumes vector's structure is valid so it
1716
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1717
+ /// before it is passed here
1718
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1719
+ /// pointed in the input's outpoint.
1720
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1721
+ /// which is pointed in the input's outpoint.
1722
+ function processRedemptionTxInput(bytes memory redemptionTxInputVector)
1723
+ internal
1724
+ pure
1725
+ returns (bytes32 outpointTxHash, uint32 outpointIndex)
1726
+ {
1727
+ // To determine the total number of redemption transaction inputs,
1728
+ // we need to parse the compactSize uint (VarInt) the input vector is
1729
+ // prepended by. That compactSize uint encodes the number of vector
1730
+ // elements using the format presented in:
1731
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1732
+ // We don't need asserting the compactSize uint is parseable since it
1733
+ // was already checked during `validateVin` validation.
1734
+ // See `BitcoinTx.inputVector` docs for more details.
1735
+ (, uint256 inputsCount) = redemptionTxInputVector.parseVarInt();
1736
+ require(
1737
+ inputsCount == 1,
1738
+ "Redemption transaction must have a single input"
1739
+ );
1740
+
1741
+ bytes memory input = redemptionTxInputVector.extractInputAtIndex(0);
1742
+
1743
+ outpointTxHash = input.extractInputTxIdLE();
1744
+
1745
+ outpointIndex = BTCUtils.reverseUint32(
1746
+ uint32(input.extractTxIndexLE())
1747
+ );
1748
+
1749
+ // There is only one input in the transaction. Input has an outpoint
1750
+ // field that is a reference to the transaction being spent (see
1751
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1752
+ // to spend (`outpointTxHash`) and the index of the specific output
1753
+ // from that transaction (`outpointIndex`).
1754
+ return (outpointTxHash, outpointIndex);
1755
+ }
1756
+
1757
+ /// @notice Processes the Bitcoin redemption transaction output vector.
1758
+ /// It extracts each output and tries to identify it as a pending
1759
+ /// redemption request, reported timed out request, or change.
1760
+ /// Reverts if one of the outputs cannot be recognized properly.
1761
+ /// This function also marks each request as processed by removing
1762
+ /// them from `pendingRedemptions` mapping.
1763
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1764
+ /// vector. This function assumes vector's structure is valid so it
1765
+ /// must be validated using e.g. `BTCUtils.validateVout` function
1766
+ /// before it is passed here
1767
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1768
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1769
+ /// performed the redemption transaction.
1770
+ /// @return info Outcomes of the processing.
1771
+ function processRedemptionTxOutputs(
1772
+ bytes memory redemptionTxOutputVector,
1773
+ bytes20 walletPubKeyHash
1774
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
1775
+ // Determining the total number of redemption transaction outputs in
1776
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
1777
+ // docs for more details.
1778
+ (
1779
+ uint256 outputsCompactSizeUintLength,
1780
+ uint256 outputsCount
1781
+ ) = redemptionTxOutputVector.parseVarInt();
1782
+
1783
+ // To determine the first output starting index, we must jump over
1784
+ // the compactSize uint which prepends the output vector. One byte
1785
+ // must be added because `BtcUtils.parseVarInt` does not include
1786
+ // compactSize uint tag in the returned length.
141
1787
  //
142
- // TODO We need to validate if the sum in the output minus the
143
- // amount from the previous wallet balance input minus fees is
144
- // equal to the amount by which Bank balances were increased.
1788
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1789
+ // returns `0`, so we jump over one byte of compactSize uint.
145
1790
  //
146
- // TODO We need to validate txOutput to see if the balance was not
147
- // transferred away from the wallet before increasing balances in
148
- // the bank.
1791
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1792
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1793
+ // tag byte included) so we need to jump over 1+2 bytes of
1794
+ // compactSize uint.
149
1795
  //
150
- // TODO Delete deposit from unswept mapping or mark it as swept
151
- // depending on the gas costs. Alternativly, do not allow to
152
- // use the same TX input vector twice. Sweep should be provable
153
- // only one time.
1796
+ // Please refer `BTCUtils` library and compactSize uint
1797
+ // docs in `BitcoinTx` library for more details.
1798
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1799
+
1800
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1801
+ // scripts that can be used to lock the change. This is done upfront to
1802
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
1803
+ //
1804
+ // The P2PKH script has format <0x1976a914> <20-byte PKH> <0x88ac>.
1805
+ bytes32 walletP2PKHScriptKeccak = keccak256(
1806
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1807
+ );
1808
+ // The P2WPKH script has format <0x160014> <20-byte PKH>.
1809
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
1810
+ abi.encodePacked(hex"160014", walletPubKeyHash)
1811
+ );
1812
+
1813
+ // Helper variable that counts the number of processed redemption
1814
+ // outputs. Redemptions can be either pending or reported as timed out.
1815
+ // TODO: Revisit the approach with redemptions count according to
1816
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1817
+ uint256 processedRedemptionsCount = 0;
1818
+
1819
+ // Outputs processing loop.
1820
+ for (uint256 i = 0; i < outputsCount; i++) {
1821
+ // TODO: Check if we can optimize gas costs by adding
1822
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1823
+ // in order to avoid allocating bytes in memory.
1824
+ uint256 outputLength = redemptionTxOutputVector
1825
+ .determineOutputLengthAt(outputStartingIndex);
1826
+ bytes memory output = redemptionTxOutputVector.slice(
1827
+ outputStartingIndex,
1828
+ outputLength
1829
+ );
1830
+
1831
+ // Extract the value from given output.
1832
+ uint64 outputValue = output.extractValue();
1833
+ // The output consists of an 8-byte value and a variable length
1834
+ // script. To extract that script we slice the output staring from
1835
+ // 9th byte until the end.
1836
+ bytes memory outputScript = output.slice(8, output.length - 8);
1837
+
1838
+ if (
1839
+ info.changeValue == 0 &&
1840
+ (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1841
+ keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1842
+ outputValue > 0
1843
+ ) {
1844
+ // If we entered here, that means the change output with a
1845
+ // proper non-zero value was found.
1846
+ info.changeIndex = uint32(i);
1847
+ info.changeValue = outputValue;
1848
+ } else {
1849
+ // If we entered here, that the means the given output is
1850
+ // supposed to represent a redemption. Build the redemption key
1851
+ // to perform that check.
1852
+ uint256 redemptionKey = uint256(
1853
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
1854
+ );
1855
+
1856
+ if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1857
+ // If we entered here, that means the output was identified
1858
+ // as a pending redemption request.
1859
+ RedemptionRequest storage request = pendingRedemptions[
1860
+ redemptionKey
1861
+ ];
1862
+ // Compute the request's redeemable amount as the requested
1863
+ // amount reduced by the treasury fee. The request's
1864
+ // minimal amount is then the redeemable amount reduced by
1865
+ // the maximum transaction fee.
1866
+ uint64 redeemableAmount = request.requestedAmount -
1867
+ request.treasuryFee;
1868
+ // Output value must fit between the request's redeemable
1869
+ // and minimal amounts to be deemed valid.
1870
+ require(
1871
+ redeemableAmount - request.txMaxFee <= outputValue &&
1872
+ outputValue <= redeemableAmount,
1873
+ "Output value is not within the acceptable range of the pending request"
1874
+ );
1875
+ // Add the redeemable amount to the total burnable value
1876
+ // the Bridge will use to decrease its balance in the Bank.
1877
+ info.totalBurnableValue += redeemableAmount;
1878
+ // Add the request's treasury fee to the total treasury fee
1879
+ // value the Bridge will transfer to the treasury.
1880
+ info.totalTreasuryFee += request.treasuryFee;
1881
+ // Request was properly handled so remove its redemption
1882
+ // key from the mapping to make it reusable for further
1883
+ // requests.
1884
+ delete pendingRedemptions[redemptionKey];
1885
+
1886
+ processedRedemptionsCount++;
1887
+ } else {
1888
+ // If we entered here, the output is not a redemption
1889
+ // request but there is still a chance the given output is
1890
+ // related to a reported timed out redemption request.
1891
+ // If so, check if the output value matches the request
1892
+ // amount to confirm this is an overdue request fulfillment
1893
+ // then bypass this output and process the subsequent
1894
+ // ones. That also means the wallet was already punished
1895
+ // for the inactivity. Otherwise, just revert.
1896
+ RedemptionRequest storage request = timedOutRedemptions[
1897
+ redemptionKey
1898
+ ];
1899
+
1900
+ require(
1901
+ request.requestedAt != 0,
1902
+ "Output is a non-requested redemption"
1903
+ );
1904
+
1905
+ uint64 redeemableAmount = request.requestedAmount -
1906
+ request.treasuryFee;
1907
+
1908
+ require(
1909
+ redeemableAmount - request.txMaxFee <= outputValue &&
1910
+ outputValue <= redeemableAmount,
1911
+ "Output value is not within the acceptable range of the timed out request"
1912
+ );
1913
+
1914
+ processedRedemptionsCount++;
1915
+ }
1916
+ }
1917
+
1918
+ // Make the `outputStartingIndex` pointing to the next output by
1919
+ // increasing it by current output's length.
1920
+ outputStartingIndex += outputLength;
1921
+ }
1922
+
1923
+ // Protect against the cases when there is only a single change output
1924
+ // referring back to the wallet PKH and just burning main UTXO value
1925
+ // for transaction fees.
1926
+ require(
1927
+ processedRedemptionsCount > 0,
1928
+ "Redemption transaction must process at least one redemption"
1929
+ );
1930
+
1931
+ return info;
154
1932
  }
155
1933
 
156
- // TODO It is possible a malicious wallet can sweep deposits that can not
157
- // be later proved on Ethereum. For example, a deposit with
158
- // an incorrect amount revealed. We need to provide a function for honest
159
- // depositors, next to sweep, to prove their swept balances on Ethereum
160
- // selectively, based on deposits they have earlier received.
1934
+ /// @notice Notifies that there is a pending redemption request associated
1935
+ /// with the given wallet, that has timed out. The redemption
1936
+ /// request is identified by the key built as
1937
+ /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.
1938
+ /// The results of calling this function: the pending redemptions
1939
+ /// value for the wallet will be decreased by the requested amount
1940
+ /// (minus treasury fee), the tokens taken from the redeemer on
1941
+ /// redemption request will be returned to the redeemer, the request
1942
+ /// will be moved from pending redemptions to timed-out redemptions.
1943
+ /// If the state of the wallet is `Live` or `MovingFunds`, the
1944
+ /// wallet operators will be slashed.
1945
+ /// Additionally, if the state of wallet is `Live`, the wallet will
1946
+ /// be closed or marked as `MovingFunds` (depending on the presence
1947
+ /// or absence of the wallet's main UTXO) and the wallet will no
1948
+ /// longer be marked as the active wallet (if it was marked as such).
1949
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
1950
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
1951
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH)
1952
+ /// @dev Requirements:
1953
+ /// - The redemption request identified by `walletPubKeyHash` and
1954
+ /// `redeemerOutputScript` must exist
1955
+ /// - The amount of time defined by `redemptionTimeout` must have
1956
+ /// passed since the redemption was requested (the request must be
1957
+ /// timed-out).
1958
+ function notifyRedemptionTimeout(
1959
+ bytes20 walletPubKeyHash,
1960
+ bytes calldata redeemerOutputScript
1961
+ ) external {
1962
+ uint256 redemptionKey = uint256(
1963
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1964
+ );
1965
+ RedemptionRequest memory request = pendingRedemptions[redemptionKey];
1966
+
1967
+ require(request.requestedAt > 0, "Redemption request does not exist");
1968
+ require(
1969
+ /* solhint-disable-next-line not-rely-on-time */
1970
+ request.requestedAt + redemptionTimeout < block.timestamp,
1971
+ "Redemption request has not timed out"
1972
+ );
1973
+
1974
+ // Update the wallet's pending redemptions value
1975
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
1976
+ walletPubKeyHash
1977
+ ];
1978
+ wallet.pendingRedemptionsValue -=
1979
+ request.requestedAmount -
1980
+ request.treasuryFee;
1981
+
1982
+ require(
1983
+ // TODO: Allow the wallets in `Closing` state when the state is added
1984
+ wallet.state == Wallets.WalletState.Live ||
1985
+ wallet.state == Wallets.WalletState.MovingFunds ||
1986
+ wallet.state == Wallets.WalletState.Terminated,
1987
+ "The wallet must be in Live, MovingFunds or Terminated state"
1988
+ );
1989
+
1990
+ // It is worth noting that there is no need to check if
1991
+ // `timedOutRedemption` mapping already contains the given redemption
1992
+ // key. There is no possibility to re-use a key of a reported timed-out
1993
+ // redemption because the wallet responsible for causing the timeout is
1994
+ // moved to a state that prevents it to receive new redemption requests.
1995
+
1996
+ // Move the redemption from pending redemptions to timed-out redemptions
1997
+ timedOutRedemptions[redemptionKey] = request;
1998
+ delete pendingRedemptions[redemptionKey];
1999
+
2000
+ if (
2001
+ wallet.state == Wallets.WalletState.Live ||
2002
+ wallet.state == Wallets.WalletState.MovingFunds
2003
+ ) {
2004
+ // Propagate timeout consequences to the wallet
2005
+ wallets.notifyRedemptionTimedOut(walletPubKeyHash);
2006
+ }
2007
+
2008
+ emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
2009
+
2010
+ // Return the requested amount of tokens to the redeemer
2011
+ bank.transferBalance(request.redeemer, request.requestedAmount);
2012
+ }
161
2013
  }