@keep-network/tbtc-v2 0.1.1-dev.2 → 0.1.1-dev.22

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 (32) hide show
  1. package/artifacts/TBTC.json +18 -18
  2. package/artifacts/TBTCToken.json +18 -18
  3. package/artifacts/VendingMachine.json +19 -19
  4. package/artifacts/solcInputs/e2b5f983e9c69369a4f41eb2f0688e3c.json +140 -0
  5. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  6. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  7. package/build/contracts/bank/Bank.sol/Bank.dbg.json +4 -0
  8. package/build/contracts/bank/Bank.sol/Bank.json +537 -0
  9. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +96 -0
  11. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  12. package/build/contracts/bridge/Bridge.sol/Bridge.json +767 -50
  13. package/build/contracts/bridge/Bridge.sol/IRelay.dbg.json +4 -0
  14. package/build/contracts/bridge/Bridge.sol/IRelay.json +37 -0
  15. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  16. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  17. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  18. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  19. package/build/contracts/vault/IVault.sol/IVault.dbg.json +4 -0
  20. package/build/contracts/vault/IVault.sol/IVault.json +47 -0
  21. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +4 -0
  22. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +181 -0
  23. package/contracts/GovernanceUtils.sol +1 -1
  24. package/contracts/bank/Bank.sol +390 -0
  25. package/contracts/bridge/BitcoinTx.sol +231 -0
  26. package/contracts/bridge/Bridge.sol +1562 -104
  27. package/contracts/bridge/VendingMachine.sol +1 -1
  28. package/contracts/token/TBTC.sol +1 -1
  29. package/contracts/vault/IVault.sol +60 -0
  30. package/contracts/vault/TBTCVault.sol +146 -0
  31. package/package.json +10 -9
  32. package/artifacts/solcInputs/02b9e185d8beb23545e98201d474fc6b.json +0 -107
@@ -1,105 +1,575 @@
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
+
23
+ import "../bank/Bank.sol";
24
+ import "./BitcoinTx.sol";
25
+
26
+ /// @title Interface for the Bitcoin relay
27
+ /// @notice Contains only the methods needed by tBTC v2. The Bitcoin relay
28
+ /// provides the difficulty of the previous and current epoch. One
29
+ /// difficulty epoch spans 2016 blocks.
30
+ interface IRelay {
31
+ /// @notice Returns the difficulty of the current epoch.
32
+ function getCurrentEpochDifficulty() external view returns (uint256);
33
+
34
+ /// @notice Returns the difficulty of the previous epoch.
35
+ function getPrevEpochDifficulty() external view returns (uint256);
36
+ }
37
+
38
+ /// @title Bitcoin Bridge
39
+ /// @notice Bridge manages BTC deposit and redemption flow and is increasing and
5
40
  /// decreasing balances in the Bank as a result of BTC deposit and
6
- /// redemption operations.
41
+ /// redemption operations performed by depositors and redeemers.
7
42
  ///
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.
43
+ /// Depositors send BTC funds to the most recently created off-chain
44
+ /// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or
45
+ /// pay-to-witness-script-hash (P2WSH) containing hashed information
46
+ /// about the depositor’s Ethereum address. Then, the depositor reveals
47
+ /// their Ethereum address along with their deposit blinding factor,
48
+ /// refund public key hash and refund locktime to the Bridge on Ethereum
49
+ /// chain. The off-chain ECDSA wallet listens for these sorts of
50
+ /// messages and when it gets one, it checks the Bitcoin network to make
51
+ /// sure the deposit lines up. If it does, the off-chain ECDSA wallet
52
+ /// may decide to pick the deposit transaction for sweeping, and when
53
+ /// the sweep operation is confirmed on the Bitcoin network, the ECDSA
54
+ /// wallet informs the Bridge about the sweep increasing appropriate
55
+ /// balances in the Bank.
18
56
  /// @dev Bridge is an upgradeable component of the Bank.
19
- contract Bridge {
20
- struct DepositInfo {
21
- uint64 amount;
57
+ contract Bridge is Ownable {
58
+ using BTCUtils for bytes;
59
+ using BTCUtils for uint256;
60
+ using BytesLib for bytes;
61
+
62
+ /// @notice Represents data which must be revealed by the depositor during
63
+ /// deposit reveal.
64
+ struct RevealInfo {
65
+ // Index of the funding output belonging to the funding transaction.
66
+ uint32 fundingOutputIndex;
67
+ // Ethereum depositor address.
68
+ address depositor;
69
+ // The blinding factor as 8 bytes. Byte endianness doesn't matter
70
+ // as this factor is not interpreted as uint.
71
+ bytes8 blindingFactor;
72
+ // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)
73
+ // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.
74
+ bytes20 walletPubKeyHash;
75
+ // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)
76
+ // that can be used to make the deposit refund after the refund
77
+ // locktime passes. Hashed in the HASH160 Bitcoin opcode style.
78
+ bytes20 refundPubKeyHash;
79
+ // The refund locktime (4-byte LE). Interpreted according to locktime
80
+ // parsing rules described in:
81
+ // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number
82
+ // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:
83
+ // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki
84
+ bytes4 refundLocktime;
85
+ // Address of the Bank vault to which the deposit is routed to.
86
+ // Optional, can be 0x0. The vault must be trusted by the Bridge.
22
87
  address vault;
88
+ }
89
+
90
+ /// @notice Represents tBTC deposit data.
91
+ struct DepositRequest {
92
+ // Ethereum depositor address.
93
+ address depositor;
94
+ // Deposit amount in satoshi.
95
+ uint64 amount;
96
+ // UNIX timestamp the deposit was revealed at.
23
97
  uint32 revealedAt;
98
+ // Address of the Bank vault the deposit is routed to.
99
+ // Optional, can be 0x0.
100
+ address vault;
101
+ // Treasury TBTC fee in satoshi at the moment of deposit reveal.
102
+ uint64 treasuryFee;
103
+ // UNIX timestamp the deposit was swept at. Note this is not the
104
+ // time when the deposit was swept on the Bitcoin chain but actually
105
+ // the time when the sweep proof was delivered to the Ethereum chain.
106
+ uint32 sweptAt;
24
107
  }
25
108
 
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;
109
+ /// @notice Represents an outcome of the sweep Bitcoin transaction
110
+ /// inputs processing.
111
+ struct SweepTxInputsInfo {
112
+ // Sum of all inputs values i.e. all deposits and main UTXO value,
113
+ // if present.
114
+ uint256 inputsTotalValue;
115
+ // Addresses of depositors who performed processed deposits. Ordered in
116
+ // the same order as deposits inputs in the input vector. Size of this
117
+ // array is either equal to the number of inputs (main UTXO doesn't
118
+ // exist) or less by one (main UTXO exists and is pointed by one of
119
+ // the inputs).
120
+ address[] depositors;
121
+ // Amounts of deposits corresponding to 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
+ uint256[] depositedAmounts;
127
+ // Values of the treasury fee corresponding to processed deposits.
128
+ // Ordered in the same order as deposits inputs in the input vector.
129
+ // Size of this array is either equal to the number of inputs (main
130
+ // UTXO doesn't exist) or less by one (main UTXO exists and is pointed
131
+ // by one of the inputs).
132
+ uint256[] treasuryFees;
133
+ }
134
+
135
+ /// @notice Represents a redemption request.
136
+ struct RedemptionRequest {
137
+ // ETH address of the redeemer who created the request.
138
+ address redeemer;
139
+ // Requested TBTC amount in satoshi.
140
+ uint64 requestedAmount;
141
+ // Treasury TBTC fee in satoshi at the moment of request creation.
142
+ uint64 treasuryFee;
143
+ // Transaction maximum BTC fee in satoshi at the moment of request
144
+ // creation.
145
+ uint64 txMaxFee;
146
+ // UNIX timestamp the request was created at.
147
+ uint32 requestedAt;
148
+ }
149
+
150
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
151
+ /// outputs processing.
152
+ struct RedemptionTxOutputsInfo {
153
+ // Total TBTC value in satoshi that should be burned by the Bridge.
154
+ // It includes the total amount of all BTC redeemed in the transaction
155
+ // and the fee paid to BTC miners for the redemption transaction.
156
+ uint64 totalBurnableValue;
157
+ // Total TBTC value in satoshi that should be transferred to
158
+ // the treasury. It is a sum of all treasury fees paid by all
159
+ // redeemers included in the redemption transaction.
160
+ uint64 totalTreasuryFee;
161
+ // Index of the change output. The change output becomes
162
+ // the new main wallet's UTXO.
163
+ uint32 changeIndex;
164
+ // Value in satoshi of the change output.
165
+ uint64 changeValue;
166
+ }
167
+
168
+ /// @notice Represents wallet state:
169
+ enum WalletState {
170
+ /// @dev The wallet is unknown to the Bridge.
171
+ Unknown,
172
+ /// @dev The wallet can sweep deposits and accept redemption requests.
173
+ Active,
174
+ /// @dev The wallet was deemed unhealthy and is expected to move their
175
+ /// outstanding funds to another wallet. The wallet can still
176
+ /// fulfill their pending redemption requests although new
177
+ /// redemption requests and new deposit reveals are not accepted.
178
+ MovingFunds,
179
+ /// @dev The wallet moved or redeemed all their funds and cannot
180
+ /// perform any action.
181
+ Closed,
182
+ /// @dev The wallet committed a fraud that was reported. The wallet is
183
+ /// blocked and can not perform any actions in the Bridge.
184
+ /// Off-chain coordination with the wallet operators is needed to
185
+ /// recover funds.
186
+ Terminated
187
+ }
188
+
189
+ /// @notice Holds information about a wallet.
190
+ struct Wallet {
191
+ // Current state of the wallet.
192
+ WalletState state;
193
+ // The total redeemable value of pending redemption requests targeting
194
+ // that wallet.
195
+ uint64 pendingRedemptionsValue;
196
+ }
197
+
198
+ /// @notice The number of confirmations on the Bitcoin chain required to
199
+ /// successfully evaluate an SPV proof.
200
+ uint256 public immutable txProofDifficultyFactor;
201
+
202
+ /// TODO: Revisit whether it should be governable or not.
203
+ /// @notice Address of the Bank this Bridge belongs to.
204
+ Bank public immutable bank;
205
+
206
+ /// TODO: Make it governable.
207
+ /// @notice Handle to the Bitcoin relay.
208
+ IRelay public immutable relay;
209
+
210
+ /// TODO: Revisit whether it should be governable or not.
211
+ /// @notice Address where the redemptions treasury fees will be sent to.
212
+ /// Treasury takes part in the operators rewarding process.
213
+ address public immutable treasury;
214
+
215
+ /// TODO: Make it governable.
216
+ /// @notice Divisor used to compute the treasury fee taken from each
217
+ /// deposit and transferred to the treasury upon sweep proof
218
+ /// submission. That fee is computed as follows:
219
+ /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`
220
+ /// For example, if the treasury fee needs to be 2% of each deposit,
221
+ /// the `redemptionTreasuryFeeDivisor` should be set to `50`
222
+ /// because `1/50 = 0.02 = 2%`.
223
+ uint64 public depositTreasuryFeeDivisor;
224
+
225
+ /// TODO: Make it governable.
226
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
227
+ /// each swept deposit being part of the given sweep
228
+ /// transaction. If the maximum BTC transaction fee is exceeded,
229
+ /// such transaction is considered a fraud.
230
+ uint64 public depositTxMaxFee;
231
+
232
+ /// TODO: Make it governable.
233
+ /// @notice The minimal amount that can be requested for redemption.
234
+ /// Value of this parameter must take into account the value of
235
+ /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
236
+ /// parameters in order to make requests that can incur the
237
+ /// treasury and transaction fee and still satisfy the redeemer.
238
+ uint64 public redemptionDustThreshold;
239
+
240
+ /// TODO: Make it governable.
241
+ /// @notice Divisor used to compute the treasury fee taken from each
242
+ /// redemption request and transferred to the treasury upon
243
+ /// successful request finalization. That fee is computed as follows:
244
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
245
+ /// For example, if the treasury fee needs to be 2% of each
246
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
247
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
248
+ uint64 public redemptionTreasuryFeeDivisor;
249
+
250
+ /// TODO: Make it governable.
251
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
252
+ /// each redemption request being part of the given redemption
253
+ /// transaction. If the maximum BTC transaction fee is exceeded, such
254
+ /// transaction is considered a fraud.
255
+ uint64 public redemptionTxMaxFee;
256
+
257
+ /// TODO: Make it governable.
258
+ /// @notice Time after which the redemption request can be reported as
259
+ /// timed out. It is counted from the moment when the redemption
260
+ /// request was created via `requestRedemption` call. Reported
261
+ /// timed out requests are cancelled and locked TBTC is returned
262
+ /// to the redeemer in full amount.
263
+ uint256 public redemptionTimeout;
264
+
265
+ /// @notice Indicates if the vault with the given address is trusted or not.
266
+ /// Depositors can route their revealed deposits only to trusted
267
+ /// vaults and have trusted vaults notified about new deposits as
268
+ /// soon as these deposits get swept. Vaults not trusted by the
269
+ /// Bridge can still be used by Bank balance owners on their own
270
+ /// responsibility - anyone can approve their Bank balance to any
271
+ /// address.
272
+ mapping(address => bool) public isVaultTrusted;
273
+
274
+ /// @notice Collection of all revealed deposits indexed by
275
+ /// keccak256(fundingTxHash | fundingOutputIndex).
276
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
277
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
278
+ /// and invalid deposits and the wallet is responsible for
279
+ /// validating them before attempting to execute a sweep.
280
+ mapping(uint256 => DepositRequest) public deposits;
281
+
282
+ /// @notice Maps the 20-byte wallet public key hash (computed using
283
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to
284
+ /// the latest wallet's main UTXO computed as
285
+ /// keccak256(txHash | txOutputIndex | txOutputValue). The `tx`
286
+ /// prefix refers to the transaction which created that main UTXO.
287
+ /// The txHash is bytes32 (ordered as in Bitcoin internally),
288
+ /// txOutputIndex an uint32, and txOutputValue an uint64 value.
289
+ mapping(bytes20 => bytes32) public mainUtxos;
290
+
291
+ /// @notice Collection of all pending redemption requests indexed by
292
+ /// redemption key built as
293
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
294
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
295
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
296
+ /// public key) and redeemerOutputScript is a Bitcoin script
297
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
298
+ /// redeemed BTC as requested by the redeemer. Requests are added
299
+ /// to this mapping by the `requestRedemption` method (duplicates
300
+ /// not allowed) and are removed by one of the following methods:
301
+ /// - `submitRedemptionProof` in case the request was handled
302
+ /// successfully
303
+ /// - `notifyRedemptionTimeout` in case the request was reported
304
+ /// to be timed out
305
+ /// - `submitRedemptionFraudProof` in case the request was handled
306
+ /// in an fraudulent way amount-wise.
307
+ mapping(uint256 => RedemptionRequest) public pendingRedemptions;
308
+
309
+ /// @notice Collection of all timed out redemptions requests indexed by
310
+ /// redemption key built as
311
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
312
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
313
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
314
+ /// public key) and redeemerOutputScript is the Bitcoin script
315
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
316
+ /// out request. Timed out requests are stored in this mapping to
317
+ /// avoid slashing the wallets multiple times for the same timeout.
318
+ /// Only one method can add to this mapping:
319
+ /// - `notifyRedemptionTimeout` which puts the redemption key
320
+ /// to this mapping basing on a timed out request stored
321
+ /// previously in `pendingRedemptions` mapping.
322
+ ///
323
+ // TODO: Remove that Slither disable once this variable is used.
324
+ // slither-disable-next-line uninitialized-state
325
+ mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
326
+
327
+ /// @notice Maps the 20-byte wallet public key hash (computed using
328
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to the
329
+ /// basic wallet information like state and pending
330
+ /// redemptions value.
331
+ ///
332
+ // TODO: Remove that Slither disable once this variable is used.
333
+ // slither-disable-next-line uninitialized-state
334
+ mapping(bytes20 => Wallet) public wallets;
335
+
336
+ event VaultStatusUpdated(address indexed vault, bool isTrusted);
32
337
 
33
338
  event DepositRevealed(
34
- uint256 depositId,
35
339
  bytes32 fundingTxHash,
36
- uint8 fundingOutputIndex,
340
+ uint32 fundingOutputIndex,
37
341
  address depositor,
38
- uint64 blindingFactor,
39
- bytes refundPubKey,
40
342
  uint64 amount,
343
+ bytes8 blindingFactor,
344
+ bytes20 walletPubKeyHash,
345
+ bytes20 refundPubKeyHash,
346
+ bytes4 refundLocktime,
41
347
  address vault
42
348
  );
43
349
 
44
- /// @notice Used by the depositor to reveal information about their P2SH
350
+ event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
351
+
352
+ event RedemptionRequested(
353
+ bytes20 walletPubKeyHash,
354
+ bytes redeemerOutputScript,
355
+ address redeemer,
356
+ uint64 requestedAmount,
357
+ uint64 treasuryFee,
358
+ uint64 txMaxFee
359
+ );
360
+
361
+ event RedemptionsCompleted(
362
+ bytes20 walletPubKeyHash,
363
+ bytes32 redemptionTxHash
364
+ );
365
+
366
+ constructor(
367
+ address _bank,
368
+ address _relay,
369
+ address _treasury,
370
+ uint256 _txProofDifficultyFactor
371
+ ) {
372
+ require(_bank != address(0), "Bank address cannot be zero");
373
+ bank = Bank(_bank);
374
+
375
+ require(_relay != address(0), "Relay address cannot be zero");
376
+ relay = IRelay(_relay);
377
+
378
+ require(_treasury != address(0), "Treasury address cannot be zero");
379
+ treasury = _treasury;
380
+
381
+ txProofDifficultyFactor = _txProofDifficultyFactor;
382
+
383
+ // TODO: Revisit initial values.
384
+ depositTxMaxFee = 1000; // 1000 satoshi
385
+ depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
386
+ redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
387
+ redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
388
+ redemptionTxMaxFee = 1000; // 1000 satoshi
389
+ redemptionTimeout = 172800; // 48 hours
390
+ }
391
+
392
+ // TODO: Add function `onNewWalletCreated` according to discussion:
393
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r809885230
394
+
395
+ /// @notice Allows the Governance to mark the given vault address as trusted
396
+ /// or no longer trusted. Vaults are not trusted by default.
397
+ /// Trusted vault must meet the following criteria:
398
+ /// - `IVault.receiveBalanceIncrease` must have a known, low gas
399
+ /// cost.
400
+ /// - `IVault.receiveBalanceIncrease` must never revert.
401
+ /// @dev Without restricting reveal only to trusted vaults, malicious
402
+ /// vaults not meeting the criteria would be able to nuke sweep proof
403
+ /// transactions executed by ECDSA wallet with deposits routed to
404
+ /// them.
405
+ /// @param vault The address of the vault
406
+ /// @param isTrusted flag indicating whether the vault is trusted or not
407
+ /// @dev Can only be called by the Governance.
408
+ function setVaultStatus(address vault, bool isTrusted) external onlyOwner {
409
+ isVaultTrusted[vault] = isTrusted;
410
+ emit VaultStatusUpdated(vault, isTrusted);
411
+ }
412
+
413
+ /// @notice Determines the current Bitcoin SPV proof difficulty context.
414
+ /// @return proofDifficulty Bitcoin proof difficulty context.
415
+ function proofDifficultyContext()
416
+ internal
417
+ view
418
+ returns (BitcoinTx.ProofDifficulty memory proofDifficulty)
419
+ {
420
+ proofDifficulty.currentEpochDifficulty = relay
421
+ .getCurrentEpochDifficulty();
422
+ proofDifficulty.previousEpochDifficulty = relay
423
+ .getPrevEpochDifficulty();
424
+ proofDifficulty.difficultyFactor = txProofDifficultyFactor;
425
+
426
+ return proofDifficulty;
427
+ }
428
+
429
+ /// @notice Used by the depositor to reveal information about their P2(W)SH
45
430
  /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain
46
431
  /// wallet listens for revealed deposit events and may decide to
47
432
  /// include the revealed deposit in the next executed sweep.
48
433
  /// 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
434
+ /// after the Bitcoin transaction with P2(W)SH deposit is mined on
435
+ /// the Bitcoin chain. Worth noting, the gas cost of this function
436
+ /// scales with the number of P2(W)SH transaction inputs and
437
+ /// outputs. The deposit may be routed to one of the trusted vaults.
438
+ /// When a deposit is routed to a vault, vault gets notified when
439
+ /// the deposit gets swept and it may execute the appropriate action.
440
+ /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`
441
+ /// @param reveal Deposit reveal data, see `RevealInfo struct
60
442
  /// @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,
443
+ /// - `reveal.vault` must be 0x0 or point to a trusted vault
444
+ /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH
445
+ /// output of the BTC deposit transaction
446
+ /// - `reveal.depositor` must be the Ethereum address used in the
447
+ /// P2(W)SH BTC deposit transaction,
448
+ /// - `reveal.blindingFactor` must be the blinding factor used in the
449
+ /// P2(W)SH BTC deposit transaction,
450
+ /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in
451
+ /// the P2(W)SH BTC deposit transaction,
452
+ /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in
453
+ /// the P2(W)SH BTC deposit transaction,
454
+ /// - `reveal.refundLocktime` must be the refund locktime used in the
455
+ /// P2(W)SH BTC deposit transaction,
65
456
  /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`
66
- /// can be revealed by `msg.sender` only one time.
457
+ /// can be revealed only one time.
67
458
  ///
68
459
  /// If any of these requirements is not met, the wallet _must_ refuse
69
460
  /// to sweep the deposit and the depositor has to wait until the
70
461
  /// deposit script unlocks to receive their BTC back.
71
462
  function revealDeposit(
72
- bytes32 fundingTxHash,
73
- uint8 fundingOutputIndex,
74
- uint64 blindingFactor,
75
- bytes calldata refundPubKey,
76
- uint64 amount,
77
- address vault
463
+ BitcoinTx.Info calldata fundingTx,
464
+ RevealInfo calldata reveal
78
465
  ) external {
79
- uint256 depositId =
466
+ require(
467
+ reveal.vault == address(0) || isVaultTrusted[reveal.vault],
468
+ "Vault is not trusted"
469
+ );
470
+
471
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
472
+ // TODO: Should we enforce a specific locktime at contract level?
473
+
474
+ bytes memory expectedScript = abi.encodePacked(
475
+ hex"14", // Byte length of depositor Ethereum address.
476
+ reveal.depositor,
477
+ hex"75", // OP_DROP
478
+ hex"08", // Byte length of blinding factor value.
479
+ reveal.blindingFactor,
480
+ hex"75", // OP_DROP
481
+ hex"76", // OP_DUP
482
+ hex"a9", // OP_HASH160
483
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
484
+ reveal.walletPubKeyHash,
485
+ hex"87", // OP_EQUAL
486
+ hex"63", // OP_IF
487
+ hex"ac", // OP_CHECKSIG
488
+ hex"67", // OP_ELSE
489
+ hex"76", // OP_DUP
490
+ hex"a9", // OP_HASH160
491
+ hex"14", // Byte length of a compressed Bitcoin public key hash.
492
+ reveal.refundPubKeyHash,
493
+ hex"88", // OP_EQUALVERIFY
494
+ hex"04", // Byte length of refund locktime value.
495
+ reveal.refundLocktime,
496
+ hex"b1", // OP_CHECKLOCKTIMEVERIFY
497
+ hex"75", // OP_DROP
498
+ hex"ac", // OP_CHECKSIG
499
+ hex"68" // OP_ENDIF
500
+ );
501
+
502
+ bytes memory fundingOutput = fundingTx
503
+ .outputVector
504
+ .extractOutputAtIndex(reveal.fundingOutputIndex);
505
+ bytes memory fundingOutputHash = fundingOutput.extractHash();
506
+
507
+ if (fundingOutputHash.length == 20) {
508
+ // A 20-byte output hash is used by P2SH. That hash is constructed
509
+ // by applying OP_HASH160 on the locking script. A 20-byte output
510
+ // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the
511
+ // public key). However, since we compare the actual output hash
512
+ // with an expected locking script hash, this check will succeed only
513
+ // for P2SH transaction type with expected script hash value. For
514
+ // P2PKH and P2WPKH, it will fail on the output hash comparison with
515
+ // the expected locking script hash.
516
+ require(
517
+ fundingOutputHash.slice20(0) == expectedScript.hash160View(),
518
+ "Wrong 20-byte script hash"
519
+ );
520
+ } else if (fundingOutputHash.length == 32) {
521
+ // A 32-byte output hash is used by P2WSH. That hash is constructed
522
+ // by applying OP_SHA256 on the locking script.
523
+ require(
524
+ fundingOutputHash.toBytes32() == sha256(expectedScript),
525
+ "Wrong 32-byte script hash"
526
+ );
527
+ } else {
528
+ revert("Wrong script hash length");
529
+ }
530
+
531
+ // Resulting TX hash is in native Bitcoin little-endian format.
532
+ bytes32 fundingTxHash = abi
533
+ .encodePacked(
534
+ fundingTx.version,
535
+ fundingTx.inputVector,
536
+ fundingTx.outputVector,
537
+ fundingTx.locktime
538
+ )
539
+ .hash256View();
540
+
541
+ DepositRequest storage deposit = deposits[
80
542
  uint256(
81
543
  keccak256(
82
- abi.encode(fundingTxHash, fundingOutputIndex, msg.sender)
544
+ abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)
83
545
  )
84
- );
85
-
86
- DepositInfo storage deposit = unswept[depositId];
546
+ )
547
+ ];
87
548
  require(deposit.revealedAt == 0, "Deposit already revealed");
88
549
 
89
- deposit.amount = amount;
90
- deposit.vault = vault;
550
+ uint64 fundingOutputAmount = fundingOutput.extractValue();
551
+
552
+ // TODO: Check the amount against the dust threshold.
553
+
554
+ deposit.amount = fundingOutputAmount;
555
+ deposit.depositor = reveal.depositor;
91
556
  /* solhint-disable-next-line not-rely-on-time */
92
557
  deposit.revealedAt = uint32(block.timestamp);
558
+ deposit.vault = reveal.vault;
559
+ deposit.treasuryFee = depositTreasuryFeeDivisor > 0
560
+ ? fundingOutputAmount / depositTreasuryFeeDivisor
561
+ : 0;
93
562
 
94
563
  emit DepositRevealed(
95
- depositId,
96
564
  fundingTxHash,
97
- fundingOutputIndex,
98
- msg.sender,
99
- blindingFactor,
100
- refundPubKey,
101
- amount,
102
- vault
565
+ reveal.fundingOutputIndex,
566
+ reveal.depositor,
567
+ fundingOutputAmount,
568
+ reveal.blindingFactor,
569
+ reveal.walletPubKeyHash,
570
+ reveal.refundPubKeyHash,
571
+ reveal.refundLocktime,
572
+ reveal.vault
103
573
  );
104
574
  }
105
575
 
@@ -110,52 +580,1040 @@ contract Bridge {
110
580
  /// The function is performing Bank balance updates by first
111
581
  /// computing the Bitcoin fee for the sweep transaction. The fee is
112
582
  /// 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.
583
+ /// receives a balance in the bank equal to the amount inferred
584
+ /// during the reveal transaction, minus their fee share.
115
585
  ///
116
586
  /// 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
587
+ /// @param sweepTx Bitcoin sweep transaction data
588
+ /// @param sweepProof Bitcoin sweep proof data
589
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
590
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
591
+ /// this parameter is ignored
592
+ /// @dev Requirements:
593
+ /// - `sweepTx` components must match the expected structure. See
594
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
595
+ /// correspond to appropriate Bitcoin transaction fields to produce
596
+ /// a provable transaction hash.
597
+ /// - The `sweepTx` should represent a Bitcoin transaction with 1..n
598
+ /// inputs. If the wallet has no main UTXO, all n inputs should
599
+ /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has
600
+ /// an existing main UTXO, one of the n inputs must point to that
601
+ /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH
602
+ /// revealed deposits UTXOs. That transaction must have only
603
+ /// one P2(W)PKH output locking funds on the 20-byte wallet public
604
+ /// key hash.
605
+ /// - `sweepProof` components must match the expected structure. See
606
+ /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
607
+ /// field must contain a valid number of block headers, not less
608
+ /// than the `txProofDifficultyFactor` contract constant.
609
+ /// - `mainUtxo` components must point to the recent main UTXO
610
+ /// of the given wallet, as currently known on the Ethereum chain.
611
+ /// If there is no main UTXO, this parameter is ignored.
612
+ function submitSweepProof(
613
+ BitcoinTx.Info calldata sweepTx,
614
+ BitcoinTx.Proof calldata sweepProof,
615
+ BitcoinTx.UTXO calldata mainUtxo
616
+ ) external {
617
+ // TODO: Fail early if the function call gets frontrunned. See discussion:
618
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
619
+
620
+ // The actual transaction proof is performed here. After that point, we
621
+ // can assume the transaction happened on Bitcoin chain and has
622
+ // a sufficient number of confirmations as determined by
623
+ // `txProofDifficultyFactor` constant.
624
+ bytes32 sweepTxHash = BitcoinTx.validateProof(
625
+ sweepTx,
626
+ sweepProof,
627
+ proofDifficultyContext()
628
+ );
629
+
630
+ // Process sweep transaction output and extract its target wallet
631
+ // public key hash and value.
632
+ (
633
+ bytes20 walletPubKeyHash,
634
+ uint64 sweepTxOutputValue
635
+ ) = processSweepTxOutput(sweepTx.outputVector);
636
+
637
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
638
+
639
+ // Check if the main UTXO for given wallet exists. If so, validate
640
+ // passed main UTXO data against the stored hash and use them for
641
+ // further processing. If no main UTXO exists, use empty data.
642
+ BitcoinTx.UTXO memory resolvedMainUtxo = BitcoinTx.UTXO(
643
+ bytes32(0),
644
+ 0,
645
+ 0
646
+ );
647
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
648
+ if (mainUtxoHash != bytes32(0)) {
649
+ require(
650
+ keccak256(
651
+ abi.encodePacked(
652
+ mainUtxo.txHash,
653
+ mainUtxo.txOutputIndex,
654
+ mainUtxo.txOutputValue
655
+ )
656
+ ) == mainUtxoHash,
657
+ "Invalid main UTXO data"
658
+ );
659
+ resolvedMainUtxo = mainUtxo;
660
+ }
661
+
662
+ // Process sweep transaction inputs and extract all information needed
663
+ // to perform deposit bookkeeping.
664
+ SweepTxInputsInfo memory inputsInfo = processSweepTxInputs(
665
+ sweepTx.inputVector,
666
+ resolvedMainUtxo
667
+ );
668
+
669
+ // Helper variable that will hold the sum of treasury fees paid by
670
+ // all deposits.
671
+ uint256 totalTreasuryFee = 0;
672
+
673
+ // Determine the transaction fee that should be incurred by each deposit
674
+ // and the indivisible remainder that should be additionally incurred
675
+ // by the last deposit.
676
+ (
677
+ uint256 depositTxFee,
678
+ uint256 depositTxFeeRemainder
679
+ ) = sweepTxFeeDistribution(
680
+ inputsInfo.inputsTotalValue,
681
+ sweepTxOutputValue,
682
+ inputsInfo.depositedAmounts.length
683
+ );
684
+
685
+ // Make sure the highest value of the deposit transaction fee does not
686
+ // exceed the maximum value limited by the governable parameter.
687
+ require(
688
+ depositTxFee + depositTxFeeRemainder <= depositTxMaxFee,
689
+ "Transaction fee is too high"
690
+ );
691
+
692
+ // Reduce each deposit amount by treasury fee and transaction fee.
693
+ for (uint256 i = 0; i < inputsInfo.depositedAmounts.length; i++) {
694
+ // The last deposit should incur the deposit transaction fee
695
+ // remainder.
696
+ uint256 depositTxFeeIncurred = i ==
697
+ inputsInfo.depositedAmounts.length - 1
698
+ ? depositTxFee + depositTxFeeRemainder
699
+ : depositTxFee;
700
+
701
+ // There is no need to check whether
702
+ // `inputsInfo.depositedAmounts[i] - inputsInfo.treasuryFees[i] - txFee > 0`
703
+ // since the `depositDustThreshold` should force that condition
704
+ // to be always true.
705
+ inputsInfo.depositedAmounts[i] =
706
+ inputsInfo.depositedAmounts[i] -
707
+ inputsInfo.treasuryFees[i] -
708
+ depositTxFeeIncurred;
709
+ totalTreasuryFee += inputsInfo.treasuryFees[i];
710
+ }
711
+
712
+ // Record this sweep data and assign them to the wallet public key hash
713
+ // as new main UTXO. Transaction output index is always 0 as sweep
714
+ // transaction always contains only one output.
715
+ mainUtxos[walletPubKeyHash] = keccak256(
716
+ abi.encodePacked(sweepTxHash, uint32(0), sweepTxOutputValue)
717
+ );
718
+
719
+ emit DepositsSwept(walletPubKeyHash, sweepTxHash);
720
+
721
+ // Update depositors balances in the Bank.
722
+ bank.increaseBalances(
723
+ inputsInfo.depositors,
724
+ inputsInfo.depositedAmounts
725
+ );
726
+ // Pass the treasury fee to the treasury address.
727
+ bank.increaseBalance(treasury, totalTreasuryFee);
728
+
729
+ // TODO: Handle deposits having `vault` set.
730
+ }
731
+
732
+ /// @notice Processes the Bitcoin sweep transaction output vector by
733
+ /// extracting the single output and using it to gain additional
734
+ /// information required for further processing (e.g. value and
735
+ /// wallet public key hash).
736
+ /// @param sweepTxOutputVector Bitcoin sweep transaction output vector.
737
+ /// This function assumes vector's structure is valid so it must be
738
+ /// validated using e.g. `BTCUtils.validateVout` function before
739
+ /// it is passed here
740
+ /// @return walletPubKeyHash 20-byte wallet public key hash.
741
+ /// @return value 8-byte sweep transaction output value.
742
+ function processSweepTxOutput(bytes memory sweepTxOutputVector)
743
+ internal
744
+ pure
745
+ returns (bytes20 walletPubKeyHash, uint64 value)
746
+ {
747
+ // To determine the total number of sweep transaction outputs, we need to
748
+ // parse the compactSize uint (VarInt) the output vector is prepended by.
749
+ // That compactSize uint encodes the number of vector elements using the
750
+ // format presented in:
751
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
752
+ // We don't need asserting the compactSize uint is parseable since it
753
+ // was already checked during `validateVout` validation.
754
+ // See `BitcoinTx.outputVector` docs for more details.
755
+ (, uint256 outputsCount) = sweepTxOutputVector.parseVarInt();
756
+ require(
757
+ outputsCount == 1,
758
+ "Sweep transaction must have a single output"
759
+ );
760
+
761
+ bytes memory output = sweepTxOutputVector.extractOutputAtIndex(0);
762
+ value = output.extractValue();
763
+ bytes memory walletPubKeyHashBytes = output.extractHash();
764
+ // The sweep transaction output should always be P2PKH or P2WPKH.
765
+ // In both cases, the wallet public key hash should be 20 bytes length.
766
+ require(
767
+ walletPubKeyHashBytes.length == 20,
768
+ "Wallet public key hash should have 20 bytes"
769
+ );
770
+ /* solhint-disable-next-line no-inline-assembly */
771
+ assembly {
772
+ walletPubKeyHash := mload(add(walletPubKeyHashBytes, 32))
773
+ }
774
+
775
+ return (walletPubKeyHash, value);
776
+ }
777
+
778
+ /// @notice Processes the Bitcoin sweep transaction input vector. It
779
+ /// extracts each input and tries to obtain associated deposit or
780
+ /// main UTXO data, depending on the input type. Reverts
781
+ /// if one of the inputs cannot be recognized as a pointer to a
782
+ /// revealed deposit or expected main UTXO.
783
+ /// This function also marks each processed deposit as swept.
784
+ /// @param sweepTxInputVector Bitcoin sweep transaction input vector.
785
+ /// This function assumes vector's structure is valid so it must be
786
+ /// validated using e.g. `BTCUtils.validateVin` function before
787
+ /// it is passed here
788
+ /// @param mainUtxo Data of the wallet's main UTXO. If no main UTXO
789
+ /// exists for the given the wallet, this parameter's fields should
790
+ /// be zeroed to bypass the main UTXO validation
791
+ /// @return info Outcomes of the processing.
792
+ function processSweepTxInputs(
793
+ bytes memory sweepTxInputVector,
794
+ BitcoinTx.UTXO memory mainUtxo
795
+ ) internal returns (SweepTxInputsInfo memory info) {
796
+ // If the passed `mainUtxo` parameter's values are zeroed, the main UTXO
797
+ // for the given wallet doesn't exist and it is not expected to be
798
+ // included in the sweep transaction input vector.
799
+ bool mainUtxoExpected = mainUtxo.txHash != bytes32(0);
800
+ bool mainUtxoFound = false;
801
+
802
+ // Determining the total number of sweep transaction inputs in the same
803
+ // way as for number of outputs. See `BitcoinTx.inputVector` docs for
804
+ // more details.
805
+ (
806
+ uint256 inputsCompactSizeUintLength,
807
+ uint256 inputsCount
808
+ ) = sweepTxInputVector.parseVarInt();
809
+
810
+ // To determine the first input starting index, we must jump over
811
+ // the compactSize uint which prepends the input vector. One byte
812
+ // must be added because `BtcUtils.parseVarInt` does not include
813
+ // compactSize uint tag in the returned length.
814
+ //
815
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
816
+ // returns `0`, so we jump over one byte of compactSize uint.
817
+ //
818
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
819
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
820
+ // tag byte included) so we need to jump over 1+2 bytes of
821
+ // compactSize uint.
822
+ //
823
+ // Please refer `BTCUtils` library and compactSize uint
824
+ // docs in `BitcoinTx` library for more details.
825
+ uint256 inputStartingIndex = 1 + inputsCompactSizeUintLength;
826
+
827
+ // Determine the swept deposits count. If main UTXO is NOT expected,
828
+ // all inputs should be deposits. If main UTXO is expected, one input
829
+ // should point to that main UTXO.
830
+ info.depositors = new address[](
831
+ !mainUtxoExpected ? inputsCount : inputsCount - 1
832
+ );
833
+ info.depositedAmounts = new uint256[](info.depositors.length);
834
+ info.treasuryFees = new uint256[](info.depositors.length);
835
+
836
+ // Initialize helper variables.
837
+ uint256 processedDepositsCount = 0;
838
+
839
+ // Inputs processing loop.
840
+ for (uint256 i = 0; i < inputsCount; i++) {
841
+ (
842
+ bytes32 outpointTxHash,
843
+ uint32 outpointIndex,
844
+ uint256 inputLength
845
+ ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
846
+
847
+ DepositRequest storage deposit = deposits[
848
+ uint256(
849
+ keccak256(abi.encodePacked(outpointTxHash, outpointIndex))
850
+ )
851
+ ];
852
+
853
+ if (deposit.revealedAt != 0) {
854
+ // If we entered here, that means the input was identified as
855
+ // a revealed deposit.
856
+ require(deposit.sweptAt == 0, "Deposit already swept");
857
+
858
+ if (processedDepositsCount == info.depositors.length) {
859
+ // If this condition is true, that means a deposit input
860
+ // took place of an expected main UTXO input.
861
+ // In other words, there is no expected main UTXO
862
+ // input and all inputs come from valid, revealed deposits.
863
+ revert(
864
+ "Expected main UTXO not present in sweep transaction inputs"
865
+ );
866
+ }
867
+
868
+ /* solhint-disable-next-line not-rely-on-time */
869
+ deposit.sweptAt = uint32(block.timestamp);
870
+
871
+ info.depositors[processedDepositsCount] = deposit.depositor;
872
+ info.depositedAmounts[processedDepositsCount] = deposit.amount;
873
+ info.inputsTotalValue += info.depositedAmounts[
874
+ processedDepositsCount
875
+ ];
876
+ info.treasuryFees[processedDepositsCount] = deposit.treasuryFee;
877
+
878
+ processedDepositsCount++;
879
+ } else if (
880
+ mainUtxoExpected != mainUtxoFound &&
881
+ mainUtxo.txHash == outpointTxHash
882
+ ) {
883
+ // If we entered here, that means the input was identified as
884
+ // the expected main UTXO.
885
+ info.inputsTotalValue += mainUtxo.txOutputValue;
886
+ mainUtxoFound = true;
887
+ } else {
888
+ revert("Unknown input type");
889
+ }
890
+
891
+ // Make the `inputStartingIndex` pointing to the next input by
892
+ // increasing it by current input's length.
893
+ inputStartingIndex += inputLength;
894
+ }
895
+
896
+ // Construction of the input processing loop guarantees that:
897
+ // `processedDepositsCount == info.depositors.length == info.depositedAmounts.length`
898
+ // is always true at this point. We just use the first variable
899
+ // to assert the total count of swept deposit is bigger than zero.
900
+ require(
901
+ processedDepositsCount > 0,
902
+ "Sweep transaction must process at least one deposit"
903
+ );
904
+
905
+ // Assert the main UTXO was used as one of current sweep's inputs if
906
+ // it was actually expected.
907
+ require(
908
+ mainUtxoExpected == mainUtxoFound,
909
+ "Expected main UTXO not present in sweep transaction inputs"
910
+ );
911
+
912
+ return info;
913
+ }
914
+
915
+ /// @notice Parses a Bitcoin transaction input starting at the given index.
916
+ /// @param inputVector Bitcoin transaction input vector
917
+ /// @param inputStartingIndex Index the given input starts at
918
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
919
+ /// pointed in the given input's outpoint.
920
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
921
+ /// which is pointed in the given input's outpoint.
922
+ /// @return inputLength Byte length of the given input.
923
+ /// @dev This function assumes vector's structure is valid so it must be
924
+ /// validated using e.g. `BTCUtils.validateVin` function before it
925
+ /// is passed here.
926
+ function parseTxInputAt(
927
+ bytes memory inputVector,
928
+ uint256 inputStartingIndex
929
+ )
930
+ internal
931
+ pure
932
+ returns (
933
+ bytes32 outpointTxHash,
934
+ uint32 outpointIndex,
935
+ uint256 inputLength
936
+ )
937
+ {
938
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
939
+
940
+ outpointIndex = BTCUtils.reverseUint32(
941
+ uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
942
+ );
943
+
944
+ inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
945
+
946
+ return (outpointTxHash, outpointIndex, inputLength);
947
+ }
948
+
949
+ /// @notice Determines the distribution of the sweep transaction fee
950
+ /// over swept deposits.
951
+ /// @param sweepTxInputsTotalValue Total value of all sweep transaction inputs.
952
+ /// @param sweepTxOutputValue Value of the sweep transaction output.
953
+ /// @param depositsCount Count of the deposits swept by the sweep transaction.
954
+ /// @return depositTxFee Transaction fee per deposit determined by evenly
955
+ /// spreading the divisible part of the sweep transaction fee
956
+ /// over all deposits.
957
+ /// @return depositTxFeeRemainder The indivisible part of the sweep
958
+ /// transaction fee than cannot be distributed over all deposits.
959
+ /// @dev It is up to the caller to decide how the remainder should be
960
+ /// counted in. This function only computes its value.
961
+ function sweepTxFeeDistribution(
962
+ uint256 sweepTxInputsTotalValue,
963
+ uint256 sweepTxOutputValue,
964
+ uint256 depositsCount
965
+ )
966
+ internal
967
+ pure
968
+ returns (uint256 depositTxFee, uint256 depositTxFeeRemainder)
969
+ {
970
+ // The sweep transaction fee is just the difference between inputs
971
+ // amounts sum and the output amount.
972
+ uint256 sweepTxFee = sweepTxInputsTotalValue - sweepTxOutputValue;
973
+ // Compute the indivisible remainder that remains after dividing the
974
+ // sweep transaction fee over all deposits evenly.
975
+ depositTxFeeRemainder = sweepTxFee % depositsCount;
976
+ // Compute the transaction fee per deposit by dividing the sweep
977
+ // transaction fee (reduced by the remainder) by the number of deposits.
978
+ depositTxFee = (sweepTxFee - depositTxFeeRemainder) / depositsCount;
979
+
980
+ return (depositTxFee, depositTxFeeRemainder);
981
+ }
982
+
983
+ /// @notice Requests redemption of the given amount from the specified
984
+ /// wallet to the redeemer Bitcoin output script.
985
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
986
+ // using Bitcoin HASH160 over the compressed ECDSA public key)
987
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
988
+ /// the Ethereum chain
989
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
990
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
991
+ /// redeemed BTC
992
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
993
+ /// that is taken from redeemer's balance in the Bank upon request.
994
+ /// Once the request is handled, the actual amount of BTC locked
995
+ /// on the redeemer output script will be always lower than this value
996
+ /// since the treasury and Bitcoin transaction fees must be incurred.
997
+ /// The minimal amount satisfying the request can be computed as:
998
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
999
+ /// Fees values are taken at the moment of request creation.
1000
+ /// @dev Requirements:
1001
+ /// - Wallet behind `walletPubKeyHash` must be active
1002
+ /// - `mainUtxo` components must point to the recent main UTXO
1003
+ /// of the given wallet, as currently known on the Ethereum chain.
1004
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
1005
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
1006
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
1007
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
1008
+ /// used for only one pending request at the same time
1009
+ /// - Wallet must have enough Bitcoin balance to proceed the request
1010
+ /// - Redeemer must make an allowance in the Bank that the Bridge
1011
+ /// contract can spend the given `amount`.
1012
+ function requestRedemption(
1013
+ bytes20 walletPubKeyHash,
1014
+ BitcoinTx.UTXO calldata mainUtxo,
1015
+ bytes calldata redeemerOutputScript,
1016
+ uint64 amount
134
1017
  ) 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.
1018
+ require(
1019
+ wallets[walletPubKeyHash].state == WalletState.Active,
1020
+ "Wallet must be in Active state"
1021
+ );
1022
+
1023
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1024
+ require(
1025
+ mainUtxoHash != bytes32(0),
1026
+ "No main UTXO for the given wallet"
1027
+ );
1028
+ require(
1029
+ keccak256(
1030
+ abi.encodePacked(
1031
+ mainUtxo.txHash,
1032
+ mainUtxo.txOutputIndex,
1033
+ mainUtxo.txOutputValue
1034
+ )
1035
+ ) == mainUtxoHash,
1036
+ "Invalid main UTXO data"
1037
+ );
1038
+
1039
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1040
+ // if it is the oldest one who can handle the request. This will
1041
+ // be suggested by the dApp but may not be respected by users who
1042
+ // interact directly with the contract. Do we need to enforce it
1043
+ // here? One option is not to enforce it, to save on gas, but if
1044
+ // we see this rule is not respected, upgrade Bridge contract to
1045
+ // require it.
1046
+
1047
+ // Validate if redeemer output script is a correct standard type
1048
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1049
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1050
+ // a function extracts the payload properly only from standard outputs
1051
+ // so if it succeeds, we have a guarantee the redeemer output script
1052
+ // is proper. Worth to note `extractHash` ignores the value at all
1053
+ // so this is why we can use 0 safely. This way of validation is the
1054
+ // same as in tBTC v1.
1055
+ bytes memory redeemerOutputScriptPayload = abi
1056
+ .encodePacked(bytes8(0), redeemerOutputScript)
1057
+ .extractHash();
1058
+ require(
1059
+ redeemerOutputScriptPayload.length > 0,
1060
+ "Redeemer output script must be a standard type"
1061
+ );
1062
+ // Check if the redeemer output script payload does not point to the
1063
+ // wallet public key hash.
1064
+ require(
1065
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
1066
+ keccak256(redeemerOutputScriptPayload),
1067
+ "Redeemer output script must not point to the wallet PKH"
1068
+ );
1069
+
1070
+ require(
1071
+ amount >= redemptionDustThreshold,
1072
+ "Redemption amount too small"
1073
+ );
1074
+
1075
+ // The redemption key is built on top of the wallet public key hash
1076
+ // and redeemer output script pair. That means there can be only one
1077
+ // request asking for redemption from the given wallet to the given
1078
+ // BTC script at the same time.
1079
+ uint256 redemptionKey = uint256(
1080
+ keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1081
+ );
1082
+
1083
+ // Check if given redemption key is not used by a pending redemption.
1084
+ // There is no need to check for existence in `timedOutRedemptions`
1085
+ // since the wallet's state is changed to other than Active after
1086
+ // first time out is reported so making new requests is not possible.
1087
+ // slither-disable-next-line incorrect-equality
1088
+ require(
1089
+ pendingRedemptions[redemptionKey].requestedAt == 0,
1090
+ "There is a pending redemption request from this wallet to the same address"
1091
+ );
1092
+
1093
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
1094
+ // since the `redemptionDustThreshold` should force that condition
1095
+ // to be always true.
1096
+ uint64 treasuryFee = redemptionTreasuryFeeDivisor > 0
1097
+ ? amount / redemptionTreasuryFeeDivisor
1098
+ : 0;
1099
+ uint64 txMaxFee = redemptionTxMaxFee;
1100
+
1101
+ // The main wallet UTXO's value doesn't include all pending redemptions.
1102
+ // To determine if the requested redemption can be performed by the
1103
+ // wallet we need to subtract the total value of all pending redemptions
1104
+ // from that wallet's main UTXO value. Given that the treasury fee is
1105
+ // not redeemed from the wallet, we are subtracting it.
1106
+ wallets[walletPubKeyHash].pendingRedemptionsValue +=
1107
+ amount -
1108
+ treasuryFee;
1109
+ require(
1110
+ mainUtxo.txOutputValue >=
1111
+ wallets[walletPubKeyHash].pendingRedemptionsValue,
1112
+ "Insufficient wallet funds"
1113
+ );
1114
+
1115
+ pendingRedemptions[redemptionKey] = RedemptionRequest(
1116
+ msg.sender,
1117
+ amount,
1118
+ treasuryFee,
1119
+ txMaxFee,
1120
+ /* solhint-disable-next-line not-rely-on-time */
1121
+ uint32(block.timestamp)
1122
+ );
1123
+
1124
+ emit RedemptionRequested(
1125
+ walletPubKeyHash,
1126
+ redeemerOutputScript,
1127
+ msg.sender,
1128
+ amount,
1129
+ treasuryFee,
1130
+ txMaxFee
1131
+ );
1132
+
1133
+ bank.transferBalanceFrom(msg.sender, address(this), amount);
1134
+ }
1135
+
1136
+ /// @notice Used by the wallet to prove the BTC redemption transaction
1137
+ /// and to make the necessary bookkeeping. Redemption is only
1138
+ /// accepted if it satisfies SPV proof.
1139
+ ///
1140
+ /// The function is performing Bank balance updates by burning
1141
+ /// the total redeemed Bitcoin amount from Bridge balance and
1142
+ /// transferring the treasury fee sum to the treasury address.
1143
+ ///
1144
+ /// It is possible to prove the given redemption only one time.
1145
+ /// @param redemptionTx Bitcoin redemption transaction data
1146
+ /// @param redemptionProof Bitcoin redemption proof data
1147
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1148
+ /// the Ethereum chain
1149
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1150
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
1151
+ /// performed the redemption transaction
1152
+ /// @dev Requirements:
1153
+ /// - `redemptionTx` components must match the expected structure. See
1154
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
1155
+ /// correspond to appropriate Bitcoin transaction fields to produce
1156
+ /// a provable transaction hash.
1157
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
1158
+ /// exactly 1 input that refers to the wallet's main UTXO. That
1159
+ /// transaction should have 1..n outputs handling existing pending
1160
+ /// redemption requests or pointing to reported timed out requests.
1161
+ /// There can be also 1 optional output representing the
1162
+ /// change and pointing back to the 20-byte wallet public key hash.
1163
+ /// The change should be always present if the redeemed value sum
1164
+ /// is lower than the total wallet's BTC balance.
1165
+ /// - `redemptionProof` components must match the expected structure.
1166
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
1167
+ /// field must contain a valid number of block headers, not less
1168
+ /// than the `txProofDifficultyFactor` contract constant.
1169
+ /// - `mainUtxo` components must point to the recent main UTXO
1170
+ /// of the given wallet, as currently known on the Ethereum chain.
1171
+ /// Additionally, the recent main UTXO on Ethereum must be set.
1172
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
1173
+ /// as transaction single input.
1174
+ /// Other remarks:
1175
+ /// - Putting the change output as the first transaction output can
1176
+ /// save some gas because the output processing loop begins each
1177
+ /// iteration by checking whether the given output is the change
1178
+ /// thus uses some gas for making the comparison. Once the change
1179
+ /// is identified, that check is omitted in further iterations.
1180
+ function submitRedemptionProof(
1181
+ BitcoinTx.Info calldata redemptionTx,
1182
+ BitcoinTx.Proof calldata redemptionProof,
1183
+ BitcoinTx.UTXO calldata mainUtxo,
1184
+ bytes20 walletPubKeyHash
1185
+ ) external {
1186
+ // TODO: Just as for `submitSweepProof`, fail early if the function
1187
+ // call gets frontrunned. See discussion:
1188
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1189
+
1190
+ // The actual transaction proof is performed here. After that point, we
1191
+ // can assume the transaction happened on Bitcoin chain and has
1192
+ // a sufficient number of confirmations as determined by
1193
+ // `txProofDifficultyFactor` constant.
1194
+ bytes32 redemptionTxHash = BitcoinTx.validateProof(
1195
+ redemptionTx,
1196
+ redemptionProof,
1197
+ proofDifficultyContext()
1198
+ );
1199
+
1200
+ // Perform validation of the redemption transaction input. Specifically,
1201
+ // check if it refers to the expected wallet's main UTXO.
1202
+ validateRedemptionTxInput(
1203
+ redemptionTx.inputVector,
1204
+ mainUtxo,
1205
+ walletPubKeyHash
1206
+ );
1207
+
1208
+ WalletState walletState = wallets[walletPubKeyHash].state;
1209
+ require(
1210
+ walletState == WalletState.Active ||
1211
+ walletState == WalletState.MovingFunds,
1212
+ "Wallet must be in Active or MovingFuds state"
1213
+ );
1214
+
1215
+ // Process redemption transaction outputs to extract some info required
1216
+ // for further processing.
1217
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
1218
+ redemptionTx.outputVector,
1219
+ walletPubKeyHash
1220
+ );
1221
+
1222
+ if (outputsInfo.changeValue > 0) {
1223
+ // If the change value is grater than zero, it means the change
1224
+ // output exists and can be used as new wallet's main UTXO.
1225
+ mainUtxos[walletPubKeyHash] = keccak256(
1226
+ abi.encodePacked(
1227
+ redemptionTxHash,
1228
+ outputsInfo.changeIndex,
1229
+ outputsInfo.changeValue
1230
+ )
1231
+ );
1232
+ } else {
1233
+ // If the change value is zero, it means the change output doesn't
1234
+ // exists and no funds left on the wallet. Delete the main UTXO
1235
+ // for that wallet to represent that state in a proper way.
1236
+ delete mainUtxos[walletPubKeyHash];
1237
+ }
1238
+
1239
+ wallets[walletPubKeyHash].pendingRedemptionsValue -= outputsInfo
1240
+ .totalBurnableValue;
1241
+
1242
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1243
+
1244
+ bank.decreaseBalance(outputsInfo.totalBurnableValue);
1245
+ bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1246
+ }
1247
+
1248
+ /// @notice Validates whether the redemption Bitcoin transaction input
1249
+ /// vector contains a single input referring to the wallet's main
1250
+ /// UTXO. Reverts in case the validation fails.
1251
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1252
+ /// vector. This function assumes vector's structure is valid so it
1253
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1254
+ /// before it is passed here
1255
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1256
+ /// the Ethereum chain.
1257
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1258
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1259
+ /// performed the redemption transaction.
1260
+ function validateRedemptionTxInput(
1261
+ bytes memory redemptionTxInputVector,
1262
+ BitcoinTx.UTXO calldata mainUtxo,
1263
+ bytes20 walletPubKeyHash
1264
+ ) internal view {
1265
+ // Assert that main UTXO for passed wallet exists in storage.
1266
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1267
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1268
+
1269
+ // Assert that passed main UTXO parameter is the same as in storage and
1270
+ // can be used for further processing.
1271
+ require(
1272
+ keccak256(
1273
+ abi.encodePacked(
1274
+ mainUtxo.txHash,
1275
+ mainUtxo.txOutputIndex,
1276
+ mainUtxo.txOutputValue
1277
+ )
1278
+ ) == mainUtxoHash,
1279
+ "Invalid main UTXO data"
1280
+ );
1281
+
1282
+ // Assert that the single redemption transaction input actually
1283
+ // refers to the wallet's main UTXO.
1284
+ (
1285
+ bytes32 redemptionTxOutpointTxHash,
1286
+ uint32 redemptionTxOutpointIndex
1287
+ ) = processRedemptionTxInput(redemptionTxInputVector);
1288
+ require(
1289
+ mainUtxo.txHash == redemptionTxOutpointTxHash &&
1290
+ mainUtxo.txOutputIndex == redemptionTxOutpointIndex,
1291
+ "Redemption transaction input must point to the wallet's main UTXO"
1292
+ );
1293
+ }
1294
+
1295
+ /// @notice Processes the Bitcoin redemption transaction input vector. It
1296
+ /// extracts the single input then the transaction hash and output
1297
+ /// index from its outpoint.
1298
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1299
+ /// vector. This function assumes vector's structure is valid so it
1300
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1301
+ /// before it is passed here
1302
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1303
+ /// pointed in the input's outpoint.
1304
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1305
+ /// which is pointed in the input's outpoint.
1306
+ function processRedemptionTxInput(bytes memory redemptionTxInputVector)
1307
+ internal
1308
+ pure
1309
+ returns (bytes32 outpointTxHash, uint32 outpointIndex)
1310
+ {
1311
+ // To determine the total number of redemption transaction inputs,
1312
+ // we need to parse the compactSize uint (VarInt) the input vector is
1313
+ // prepended by. That compactSize uint encodes the number of vector
1314
+ // elements using the format presented in:
1315
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1316
+ // We don't need asserting the compactSize uint is parseable since it
1317
+ // was already checked during `validateVin` validation.
1318
+ // See `BitcoinTx.inputVector` docs for more details.
1319
+ (, uint256 inputsCount) = redemptionTxInputVector.parseVarInt();
1320
+ require(
1321
+ inputsCount == 1,
1322
+ "Redemption transaction must have a single input"
1323
+ );
1324
+
1325
+ bytes memory input = redemptionTxInputVector.extractInputAtIndex(0);
1326
+
1327
+ outpointTxHash = input.extractInputTxIdLE();
1328
+
1329
+ outpointIndex = BTCUtils.reverseUint32(
1330
+ uint32(input.extractTxIndexLE())
1331
+ );
1332
+
1333
+ // There is only one input in the transaction. Input has an outpoint
1334
+ // field that is a reference to the transaction being spent (see
1335
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1336
+ // to spend (`outpointTxHash`) and the index of the specific output
1337
+ // from that transaction (`outpointIndex`).
1338
+ return (outpointTxHash, outpointIndex);
1339
+ }
1340
+
1341
+ /// @notice Processes the Bitcoin redemption transaction output vector.
1342
+ /// It extracts each output and tries to identify it as a pending
1343
+ /// redemption request, reported timed out request, or change.
1344
+ /// Reverts if one of the outputs cannot be recognized properly.
1345
+ /// This function also marks each request as processed by removing
1346
+ /// them from `pendingRedemptions` mapping.
1347
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1348
+ /// vector. This function assumes vector's structure is valid so it
1349
+ /// must be validated using e.g. `BTCUtils.validateVout` function
1350
+ /// before it is passed here
1351
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1352
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1353
+ /// performed the redemption transaction.
1354
+ /// @return info Outcomes of the processing.
1355
+ function processRedemptionTxOutputs(
1356
+ bytes memory redemptionTxOutputVector,
1357
+ bytes20 walletPubKeyHash
1358
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
1359
+ // Determining the total number of redemption transaction outputs in
1360
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
1361
+ // docs for more details.
1362
+ (
1363
+ uint256 outputsCompactSizeUintLength,
1364
+ uint256 outputsCount
1365
+ ) = redemptionTxOutputVector.parseVarInt();
1366
+
1367
+ // To determine the first output starting index, we must jump over
1368
+ // the compactSize uint which prepends the output vector. One byte
1369
+ // must be added because `BtcUtils.parseVarInt` does not include
1370
+ // compactSize uint tag in the returned length.
1371
+ //
1372
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1373
+ // returns `0`, so we jump over one byte of compactSize uint.
141
1374
  //
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.
1375
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1376
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1377
+ // tag byte included) so we need to jump over 1+2 bytes of
1378
+ // compactSize uint.
145
1379
  //
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.
1380
+ // Please refer `BTCUtils` library and compactSize uint
1381
+ // docs in `BitcoinTx` library for more details.
1382
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1383
+
1384
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1385
+ // scripts that can be used to lock the change. This is done upfront to
1386
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
149
1387
  //
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.
1388
+ // The P2PKH script has format <0x1976a914> <20-byte PKH> <0x88ac>.
1389
+ bytes32 walletP2PKHScriptKeccak = keccak256(
1390
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1391
+ );
1392
+ // The P2WPKH script has format <0x160014> <20-byte PKH>.
1393
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
1394
+ abi.encodePacked(hex"160014", walletPubKeyHash)
1395
+ );
1396
+
1397
+ // Helper variable that counts the number of processed redemption
1398
+ // outputs. Redemptions can be either pending or reported as timed out.
1399
+ // TODO: Revisit the approach with redemptions count according to
1400
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1401
+ uint256 processedRedemptionsCount = 0;
1402
+
1403
+ // Outputs processing loop.
1404
+ for (uint256 i = 0; i < outputsCount; i++) {
1405
+ // TODO: Check if we can optimize gas costs by adding
1406
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1407
+ // in order to avoid allocating bytes in memory.
1408
+ uint256 outputLength = redemptionTxOutputVector
1409
+ .determineOutputLengthAt(outputStartingIndex);
1410
+ bytes memory output = redemptionTxOutputVector.slice(
1411
+ outputStartingIndex,
1412
+ outputLength
1413
+ );
1414
+
1415
+ // Extract the value from given output.
1416
+ uint64 outputValue = output.extractValue();
1417
+ // The output consists of an 8-byte value and a variable length
1418
+ // script. To extract that script we slice the output staring from
1419
+ // 9th byte until the end.
1420
+ bytes memory outputScript = output.slice(8, output.length - 8);
1421
+
1422
+ if (
1423
+ info.changeValue == 0 &&
1424
+ (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1425
+ keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1426
+ outputValue > 0
1427
+ ) {
1428
+ // If we entered here, that means the change output with a
1429
+ // proper non-zero value was found.
1430
+ info.changeIndex = uint32(i);
1431
+ info.changeValue = outputValue;
1432
+ } else {
1433
+ // If we entered here, that the means the given output is
1434
+ // supposed to represent a redemption. Build the redemption key
1435
+ // to perform that check.
1436
+ uint256 redemptionKey = uint256(
1437
+ keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
1438
+ );
1439
+
1440
+ if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1441
+ // If we entered here, that means the output was identified
1442
+ // as a pending redemption request.
1443
+ RedemptionRequest storage request = pendingRedemptions[
1444
+ redemptionKey
1445
+ ];
1446
+ // Compute the request's redeemable amount as the requested
1447
+ // amount reduced by the treasury fee. The request's
1448
+ // minimal amount is then the redeemable amount reduced by
1449
+ // the maximum transaction fee.
1450
+ uint64 redeemableAmount = request.requestedAmount -
1451
+ request.treasuryFee;
1452
+ // Output value must fit between the request's redeemable
1453
+ // and minimal amounts to be deemed valid.
1454
+ require(
1455
+ redeemableAmount - request.txMaxFee <= outputValue &&
1456
+ outputValue <= redeemableAmount,
1457
+ "Output value is not within the acceptable range of the pending request"
1458
+ );
1459
+ // Add the redeemable amount to the total burnable value
1460
+ // the Bridge will use to decrease its balance in the Bank.
1461
+ info.totalBurnableValue += redeemableAmount;
1462
+ // Add the request's treasury fee to the total treasury fee
1463
+ // value the Bridge will transfer to the treasury.
1464
+ info.totalTreasuryFee += request.treasuryFee;
1465
+ // Request was properly handled so remove its redemption
1466
+ // key from the mapping to make it reusable for further
1467
+ // requests.
1468
+ delete pendingRedemptions[redemptionKey];
1469
+
1470
+ processedRedemptionsCount++;
1471
+ } else {
1472
+ // If we entered here, the output is not a redemption
1473
+ // request but there is still a chance the given output is
1474
+ // related to a reported timed out redemption request.
1475
+ // If so, check if the output value matches the request
1476
+ // amount to confirm this is an overdue request fulfillment
1477
+ // then bypass this output and process the subsequent
1478
+ // ones. That also means the wallet was already punished
1479
+ // for the inactivity. Otherwise, just revert.
1480
+ RedemptionRequest storage request = timedOutRedemptions[
1481
+ redemptionKey
1482
+ ];
1483
+
1484
+ require(
1485
+ request.requestedAt != 0,
1486
+ "Output is a non-requested redemption"
1487
+ );
1488
+
1489
+ uint64 redeemableAmount = request.requestedAmount -
1490
+ request.treasuryFee;
1491
+
1492
+ require(
1493
+ redeemableAmount - request.txMaxFee <= outputValue &&
1494
+ outputValue <= redeemableAmount,
1495
+ "Output value is not within the acceptable range of the timed out request"
1496
+ );
1497
+
1498
+ processedRedemptionsCount++;
1499
+ }
1500
+ }
1501
+
1502
+ // Make the `outputStartingIndex` pointing to the next output by
1503
+ // increasing it by current output's length.
1504
+ outputStartingIndex += outputLength;
1505
+ }
1506
+
1507
+ // Protect against the cases when there is only a single change output
1508
+ // referring back to the wallet PKH and just burning main UTXO value
1509
+ // for transaction fees.
1510
+ require(
1511
+ processedRedemptionsCount > 0,
1512
+ "Redemption transaction must process at least one redemption"
1513
+ );
1514
+
1515
+ return info;
154
1516
  }
155
1517
 
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.
1518
+ // TODO: Function `notifyRedemptionTimeout. That function must:
1519
+ // 1. Take a the `walletPubKey` and `redeemerOutputScript` as params.
1520
+ // 2. Build the redemption key using those params.
1521
+ // 3. Use the redemption key and take the request from
1522
+ // `pendingRedemptions` mapping.
1523
+ // 4. If request doesn't exist in mapping - revert.
1524
+ // 5. If request exits, and is timed out - remove the redemption key
1525
+ // from `pendingRedemptions` and put it to `timedOutRedemptions`
1526
+ // by copying the entire `RedemptionRequest` struct there. No need
1527
+ // to check if `timedOutRedemptions` mapping already contains
1528
+ // that key because `requestRedemption` blocks requests targeting
1529
+ // non-active wallets. Because `notifyRedemptionTimeout` changes
1530
+ // wallet state after first call (point 9), there is no possibility
1531
+ // that the given redemption key could be reported as timed out
1532
+ // multiple times. At the same time, if the given redemption key
1533
+ // was already marked as fraudulent due to an amount-related fraud,
1534
+ // it will not be possible to report a time out on it since it
1535
+ // won't be present in `pendingRedemptions` mapping.
1536
+ // 6. Return the `requestedAmount` to the `redeemer`.
1537
+ // 7. Reduce the `pendingRedemptionsValue` (`wallets` mapping) for
1538
+ // given wallet by request's redeemable amount computed as
1539
+ // `requestedAmount - treasuryFee`.
1540
+ // 8. Punish the wallet, probably by slashing its operators.
1541
+ // 9. Change wallet's state in `wallets` mapping to `MovingFunds` in
1542
+ // order to prevent against new redemption requests hitting
1543
+ // that wallet.
1544
+ // 10. Expect the wallet to transfer its funds to another healthy
1545
+ // wallet (just as in case of failed heartbeat). The wallet is
1546
+ // expected to finish the already queued redemption requests
1547
+ // before moving funds but we are not going to enforce it on-chain.
1548
+
1549
+ // TODO: Function `submitRedemptionFraudProof`
1550
+ //
1551
+ // Deposit and redemption fraud proofs are challenging to implement
1552
+ // and it may happen we will have to rely on the coverage pool
1553
+ // (https://github.com/keep-network/coverage-pools) and DAO to
1554
+ // reimburse unlucky depositors and bring back the balance to the
1555
+ // system in case of a wallet fraud by liquidating a part of the
1556
+ // coverage pool manually.
1557
+ //
1558
+ // The probability of 51-of-100 wallet being fraudulent is negligible:
1559
+ // https://github.com/keep-network/tbtc-v2/blob/main/docs/rfc/rfc-2.adoc#111-group-size-and-threshold
1560
+ // and the coverage pool would be there to bring the balance back in
1561
+ // case we are unlucky and malicious wallet emerges.
1562
+ //
1563
+ // We do not want to slash for a misbehavior that is not provable
1564
+ // on-chain and it is possible to construct such a Bitcoin transaction
1565
+ // that is not provable on Ethereum, see
1566
+ // https://consensys.net/diligence/blog/2020/05/tbtc-navigating-the-cross-chain-conundrum
1567
+ //
1568
+ // The algorithm described below assumes we will be able to prove the
1569
+ // TX on Ethereum which may not always be the case. Consider the steps
1570
+ // below as an idea, and not necessarily how this function will be
1571
+ // implemented because it may happen this function will never be
1572
+ // implemented, given the Bitcoin transaction size problems.
1573
+ //
1574
+ // The algorithm:
1575
+ // 1. Take a `BitcoinTx.Info` and `BitcoinTx.Proof` of the
1576
+ // fraudulent transaction. It should also accept `walletPubKeyHash`
1577
+ // and index of fraudulent output. Probably index of fraudulent
1578
+ // input will be also required if the transaction is supposed
1579
+ // to have a bad input vector.
1580
+ // 2. Perform SPV proof to make sure it occurred on Bitcoin chain.
1581
+ // If not - revert.
1582
+ // 3. Check if wallet state is Active or MovingFunds. If not, revert.
1583
+ // 4. Validate the number of inputs. If there is one input and it
1584
+ // points to the wallet's main UTXO - move to point 5. If there
1585
+ // are multiple inputs and there is wallet's main UTXO in the set,
1586
+ // check if this is a sweep transaction. If it's not a sweep,
1587
+ // consider it as fraudulent and move to point 6.
1588
+ // In all other cases revert the call.
1589
+ // 5. Extract the output and analyze its type. The output is not
1590
+ // a fraud and the call should be reverted ONLY IF one of the
1591
+ // following conditions is true:
1592
+ // - Output is a requested redemption held by `pendingRedemptions`
1593
+ // and output value fulfills the request range. There is an
1594
+ // open question if a misfunded request should be removed
1595
+ // from `pendingRedemptions` (probably yes) and whether the
1596
+ // redeemer should be reimbursed in case of an underfund.
1597
+ // - Output is a timed out redemption held by `timedOutRedemptions`
1598
+ // and output value fulfills the request range.
1599
+ // - Output is a proper change i.e. a single output targeting
1600
+ // the wallet PKH back and having a non-zero value.
1601
+ // - Wallet is in MovingFunds state, the output points to the
1602
+ // expected target wallet, have non-zero value, and is a single
1603
+ // output in the vector.
1604
+ // In all other cases consider the transaction as fraud and
1605
+ // proceed to point 6.
1606
+ // 6. Punish the wallet, probably by severely slashing its operators.
1607
+ // 7. Change wallet's state in `wallets` mapping to `Terminated` in
1608
+ // order to prevent against new redemption requests hitting
1609
+ // that wallet. This also prevents against reporting a fraud
1610
+ // multiple times for one transaction (see point 3) and blocks
1611
+ // submission of sweep and redemption proofs. `Terminated` wallet
1612
+ // is blocked in the Bridge forever. If the fraud was a mistake
1613
+ // done by the wallet and the wallet is still honest deep in its
1614
+ // heart, the wallet can coordinate off-chain to recover the BTC
1615
+ // and donate it to another wallet. If they recover all of the
1616
+ // remaining BTC, DAO might decide to reward them with tokens so
1617
+ // that they can have at least some portion of their slashed
1618
+ // tokens back.
161
1619
  }