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

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