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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/TBTC.json +19 -18
  3. package/artifacts/TBTCToken.json +19 -18
  4. package/artifacts/VendingMachine.json +20 -19
  5. package/artifacts/solcInputs/f1a50b67569d88ee54efa3e22c6b484e.json +215 -0
  6. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  7. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  8. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  9. package/build/contracts/bank/Bank.sol/Bank.json +20 -2
  10. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +4 -0
  11. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +10 -0
  12. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  13. package/build/contracts/bridge/Bridge.sol/Bridge.json +1743 -64
  14. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  15. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +10 -0
  16. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  17. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  18. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  19. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  20. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +4 -0
  21. package/build/contracts/bridge/Frauds.sol/Frauds.json +138 -0
  22. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  23. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  24. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  25. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +48 -0
  26. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  27. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  28. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  29. package/build/contracts/bridge/Redeem.sol/Redeem.json +110 -0
  30. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +4 -0
  31. package/build/contracts/bridge/Sweep.sol/Sweep.json +30 -0
  32. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  33. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  34. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  35. package/build/contracts/bridge/Wallets.sol/Wallets.json +138 -0
  36. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  37. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  38. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  39. package/build/contracts/vault/IVault.sol/IVault.json +19 -1
  40. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  41. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +36 -18
  42. package/contracts/GovernanceUtils.sol +1 -1
  43. package/contracts/bank/Bank.sol +34 -18
  44. package/contracts/bridge/BitcoinTx.sol +241 -0
  45. package/contracts/bridge/Bridge.sol +980 -123
  46. package/contracts/bridge/BridgeState.sol +172 -0
  47. package/contracts/bridge/Deposit.sol +247 -0
  48. package/contracts/bridge/EcdsaLib.sol +30 -0
  49. package/contracts/bridge/Frauds.sol +529 -0
  50. package/contracts/bridge/IRelay.sol +28 -0
  51. package/contracts/bridge/MovingFunds.sol +280 -0
  52. package/contracts/bridge/Redeem.sol +849 -0
  53. package/contracts/bridge/Sweep.sol +510 -0
  54. package/contracts/bridge/VendingMachine.sol +1 -1
  55. package/contracts/bridge/Wallets.sol +591 -0
  56. package/contracts/token/TBTC.sol +1 -1
  57. package/contracts/vault/IVault.sol +32 -10
  58. package/contracts/vault/TBTCVault.sol +20 -2
  59. package/package.json +28 -24
  60. package/artifacts/solcInputs/d71966212a658480bad5748ad85b1396.json +0 -116
@@ -13,109 +13,413 @@
13
13
  // ▐████▌ ▐████▌
14
14
  // ▐████▌ ▐████▌
15
15
 
16
- pragma solidity 0.8.4;
16
+ pragma solidity ^0.8.9;
17
17
 
18
- /// @title BTC Bridge
19
- /// @notice Bridge manages BTC deposit and redemption and is increasing and
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 {IWalletOwner as EcdsaWalletOwner} from "@keep-network/ecdsa/contracts/api/IWalletOwner.sol";
24
+
25
+ import "./IRelay.sol";
26
+ import "./BridgeState.sol";
27
+ import "./Deposit.sol";
28
+ import "./Sweep.sol";
29
+ import "./Redeem.sol";
30
+ import "./BitcoinTx.sol";
31
+ import "./EcdsaLib.sol";
32
+ import "./Wallets.sol";
33
+ import "./Frauds.sol";
34
+ import "./MovingFunds.sol";
35
+
36
+ import "../bank/Bank.sol";
37
+
38
+ /// @title Bitcoin Bridge
39
+ /// @notice Bridge manages BTC deposit and redemption flow and is increasing and
20
40
  /// decreasing balances in the Bank as a result of BTC deposit and
21
- /// redemption operations.
41
+ /// redemption operations performed by depositors and redeemers.
22
42
  ///
23
- /// Depositors send BTC funds to the most-recently-created-wallet of the
24
- /// bridge using pay-to-script-hash (P2SH) which contains hashed
25
- /// information about the depositor’s minting Ethereum address. Then,
26
- /// the depositor reveals their desired Ethereum minting address to the
27
- /// Ethereum chain. The Bridge listens for these sorts of messages and
28
- /// when it gets one, it checks the Bitcoin network to make sure the
29
- /// funds line up. If they do, the off-chain wallet may decide to pick
30
- /// this transaction for sweeping, and when the sweep operation is
31
- /// confirmed on the Bitcoin network, the wallet informs the Bridge
32
- /// 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.
33
56
  /// @dev Bridge is an upgradeable component of the Bank.
34
- contract Bridge {
35
- struct DepositInfo {
36
- uint64 amount;
37
- address vault;
38
- uint32 revealedAt;
39
- }
57
+ ///
58
+ // TODO: All wallets-related operations that are currently done directly
59
+ // by the Bridge can be probably delegated to the Wallets library.
60
+ // Examples of such operations are main UTXO or pending redemptions
61
+ // value updates.
62
+ contract Bridge is Ownable, EcdsaWalletOwner {
63
+ using BridgeState for BridgeState.Storage;
64
+ using Deposit for BridgeState.Storage;
65
+ using Sweep for BridgeState.Storage;
66
+ using Redeem for BridgeState.Storage;
67
+ using MovingFunds for BridgeState.Storage;
68
+ using Frauds for Frauds.Data;
69
+ using Wallets for Wallets.Data;
70
+
71
+ using BTCUtils for bytes;
72
+ using BTCUtils for uint256;
73
+ using BytesLib for bytes;
74
+
75
+ BridgeState.Storage internal self;
76
+
77
+ /// @notice Contains parameters related to frauds and the collection of all
78
+ /// submitted fraud challenges.
79
+ Frauds.Data internal frauds;
80
+
81
+ /// @notice State related with wallets.
82
+ Wallets.Data internal wallets;
83
+
84
+ event WalletCreationPeriodUpdated(uint32 newCreationPeriod);
85
+
86
+ event WalletBtcBalanceRangeUpdated(
87
+ uint64 newMinBtcBalance,
88
+ uint64 newMaxBtcBalance
89
+ );
90
+
91
+ event WalletMaxAgeUpdated(uint32 newMaxAge);
92
+
93
+ event NewWalletRequested();
94
+
95
+ event NewWalletRegistered(
96
+ bytes32 indexed ecdsaWalletID,
97
+ bytes20 indexed walletPubKeyHash
98
+ );
99
+
100
+ event WalletMovingFunds(
101
+ bytes32 indexed ecdsaWalletID,
102
+ bytes20 indexed walletPubKeyHash
103
+ );
40
104
 
41
- /// @notice Collection of all unswept deposits indexed by
42
- /// keccak256(fundingTxHash | fundingOutputIndex | depositorAddress).
43
- /// This mapping may contain valid and invalid deposits and the
44
- /// wallet is responsible for validating them before attempting to
45
- /// execute a sweep.
46
- mapping(uint256 => DepositInfo) public unswept;
105
+ event WalletClosed(
106
+ bytes32 indexed ecdsaWalletID,
107
+ bytes20 indexed walletPubKeyHash
108
+ );
109
+
110
+ event WalletTerminated(
111
+ bytes32 indexed ecdsaWalletID,
112
+ bytes20 indexed walletPubKeyHash
113
+ );
114
+
115
+ event VaultStatusUpdated(address indexed vault, bool isTrusted);
116
+
117
+ event FraudSlashingAmountUpdated(uint256 newFraudSlashingAmount);
118
+
119
+ event FraudNotifierRewardMultiplierUpdated(
120
+ uint256 newFraudNotifierRewardMultiplier
121
+ );
122
+
123
+ event FraudChallengeDefeatTimeoutUpdated(
124
+ uint256 newFraudChallengeDefeatTimeout
125
+ );
126
+
127
+ event FraudChallengeDepositAmountUpdated(
128
+ uint256 newFraudChallengeDepositAmount
129
+ );
47
130
 
48
131
  event DepositRevealed(
49
- uint256 depositId,
50
132
  bytes32 fundingTxHash,
51
- uint8 fundingOutputIndex,
133
+ uint32 fundingOutputIndex,
52
134
  address depositor,
53
- uint64 blindingFactor,
54
- bytes refundPubKey,
55
135
  uint64 amount,
136
+ bytes8 blindingFactor,
137
+ bytes20 walletPubKeyHash,
138
+ bytes20 refundPubKeyHash,
139
+ bytes4 refundLocktime,
56
140
  address vault
57
141
  );
58
142
 
59
- /// @notice Used by the depositor to reveal information about their P2SH
143
+ event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
144
+
145
+ event RedemptionRequested(
146
+ bytes20 walletPubKeyHash,
147
+ bytes redeemerOutputScript,
148
+ address redeemer,
149
+ uint64 requestedAmount,
150
+ uint64 treasuryFee,
151
+ uint64 txMaxFee
152
+ );
153
+
154
+ event RedemptionsCompleted(
155
+ bytes20 walletPubKeyHash,
156
+ bytes32 redemptionTxHash
157
+ );
158
+
159
+ event RedemptionTimedOut(
160
+ bytes20 walletPubKeyHash,
161
+ bytes redeemerOutputScript
162
+ );
163
+
164
+ event FraudChallengeSubmitted(
165
+ bytes20 walletPublicKeyHash,
166
+ bytes32 sighash,
167
+ uint8 v,
168
+ bytes32 r,
169
+ bytes32 s
170
+ );
171
+
172
+ event FraudChallengeDefeated(bytes20 walletPublicKeyHash, bytes32 sighash);
173
+
174
+ event FraudChallengeDefeatTimedOut(
175
+ bytes20 walletPublicKeyHash,
176
+ bytes32 sighash
177
+ );
178
+
179
+ event MovingFundsCompleted(
180
+ bytes20 walletPubKeyHash,
181
+ bytes32 movingFundsTxHash
182
+ );
183
+
184
+ constructor(
185
+ address _bank,
186
+ address _relay,
187
+ address _treasury,
188
+ address _ecdsaWalletRegistry,
189
+ uint256 _txProofDifficultyFactor
190
+ ) {
191
+ require(_bank != address(0), "Bank address cannot be zero");
192
+ self.bank = Bank(_bank);
193
+
194
+ require(_relay != address(0), "Relay address cannot be zero");
195
+ self.relay = IRelay(_relay);
196
+
197
+ require(_treasury != address(0), "Treasury address cannot be zero");
198
+ self.treasury = _treasury;
199
+
200
+ self.txProofDifficultyFactor = _txProofDifficultyFactor;
201
+
202
+ // TODO: Revisit initial values.
203
+ self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
204
+ self.depositTxMaxFee = 10000; // 10000 satoshi
205
+ self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
206
+ self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
207
+ self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
208
+ self.redemptionTxMaxFee = 10000; // 10000 satoshi
209
+ self.redemptionTimeout = 172800; // 48 hours
210
+ self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi
211
+
212
+ // TODO: Revisit initial values.
213
+ frauds.setSlashingAmount(10000 * 1e18); // 10000 T
214
+ frauds.setNotifierRewardMultiplier(100); // 100%
215
+ frauds.setChallengeDefeatTimeout(7 days);
216
+ frauds.setChallengeDepositAmount(2 ether);
217
+
218
+ // TODO: Revisit initial values.
219
+ wallets.init(_ecdsaWalletRegistry);
220
+ wallets.setCreationPeriod(1 weeks);
221
+ wallets.setBtcBalanceRange(1 * 1e8, 10 * 1e8); // [1 BTC, 10 BTC]
222
+ wallets.setMaxAge(26 weeks); // ~6 months
223
+ }
224
+
225
+ /// @notice Updates parameters used by the `Wallets` library.
226
+ /// @param creationPeriod New value of the wallet creation period
227
+ /// @param minBtcBalance New value of the minimum BTC balance
228
+ /// @param maxBtcBalance New value of the maximum BTC balance
229
+ /// @param maxAge New value of the wallet maximum age
230
+ /// @dev Requirements:
231
+ /// - Caller must be the contract owner.
232
+ /// - Minimum BTC balance must be greater than zero
233
+ /// - Maximum BTC balance must be greater than minimum BTC balance
234
+ function updateWalletsParameters(
235
+ uint32 creationPeriod,
236
+ uint64 minBtcBalance,
237
+ uint64 maxBtcBalance,
238
+ uint32 maxAge
239
+ ) external onlyOwner {
240
+ wallets.setCreationPeriod(creationPeriod);
241
+ wallets.setBtcBalanceRange(minBtcBalance, maxBtcBalance);
242
+ wallets.setMaxAge(maxAge);
243
+ }
244
+
245
+ /// @return creationPeriod Value of the wallet creation period
246
+ /// @return minBtcBalance Value of the minimum BTC balance
247
+ /// @return maxBtcBalance Value of the maximum BTC balance
248
+ /// @return maxAge Value of the wallet max age
249
+ function getWalletsParameters()
250
+ external
251
+ view
252
+ returns (
253
+ uint32 creationPeriod,
254
+ uint64 minBtcBalance,
255
+ uint64 maxBtcBalance,
256
+ uint32 maxAge
257
+ )
258
+ {
259
+ creationPeriod = wallets.creationPeriod;
260
+ minBtcBalance = wallets.minBtcBalance;
261
+ maxBtcBalance = wallets.maxBtcBalance;
262
+ maxAge = wallets.maxAge;
263
+
264
+ return (creationPeriod, minBtcBalance, maxBtcBalance, maxAge);
265
+ }
266
+
267
+ /// @notice Allows the Governance to mark the given vault address as trusted
268
+ /// or no longer trusted. Vaults are not trusted by default.
269
+ /// Trusted vault must meet the following criteria:
270
+ /// - `IVault.receiveBalanceIncrease` must have a known, low gas
271
+ /// cost.
272
+ /// - `IVault.receiveBalanceIncrease` must never revert.
273
+ /// @dev Without restricting reveal only to trusted vaults, malicious
274
+ /// vaults not meeting the criteria would be able to nuke sweep proof
275
+ /// transactions executed by ECDSA wallet with deposits routed to
276
+ /// them.
277
+ /// @param vault The address of the vault
278
+ /// @param isTrusted flag indicating whether the vault is trusted or not
279
+ /// @dev Can only be called by the Governance.
280
+ function setVaultStatus(address vault, bool isTrusted) external onlyOwner {
281
+ self.isVaultTrusted[vault] = isTrusted;
282
+ emit VaultStatusUpdated(vault, isTrusted);
283
+ }
284
+
285
+ /// @notice Requests creation of a new wallet. This function just
286
+ /// forms a request and the creation process is performed
287
+ /// asynchronously. Once a wallet is created, the ECDSA Wallet
288
+ /// Registry will notify this contract by calling the
289
+ /// `__ecdsaWalletCreatedCallback` function.
290
+ /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as
291
+ /// currently known on the Ethereum chain.
292
+ /// @dev Requirements:
293
+ /// - `activeWalletMainUtxo` components must point to the recent main
294
+ /// UTXO of the given active wallet, as currently known on the
295
+ /// Ethereum chain. If there is no active wallet at the moment, or
296
+ /// the active wallet has no main UTXO, this parameter can be
297
+ /// empty as it is ignored.
298
+ /// - Wallet creation must not be in progress
299
+ /// - If the active wallet is set, one of the following
300
+ /// conditions must be true:
301
+ /// - The active wallet BTC balance is above the minimum threshold
302
+ /// and the active wallet is old enough, i.e. the creation period
303
+ /// was elapsed since its creation time
304
+ /// - The active wallet BTC balance is above the maximum threshold
305
+ function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)
306
+ external
307
+ {
308
+ wallets.requestNewWallet(activeWalletMainUtxo);
309
+ }
310
+
311
+ /// @notice A callback function that is called by the ECDSA Wallet Registry
312
+ /// once a new ECDSA wallet is created.
313
+ /// @param ecdsaWalletID Wallet's unique identifier.
314
+ /// @param publicKeyX Wallet's public key's X coordinate.
315
+ /// @param publicKeyY Wallet's public key's Y coordinate.
316
+ /// @dev Requirements:
317
+ /// - The only caller authorized to call this function is `registry`
318
+ /// - Given wallet data must not belong to an already registered wallet
319
+ function __ecdsaWalletCreatedCallback(
320
+ bytes32 ecdsaWalletID,
321
+ bytes32 publicKeyX,
322
+ bytes32 publicKeyY
323
+ ) external override {
324
+ wallets.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);
325
+ }
326
+
327
+ /// @notice A callback function that is called by the ECDSA Wallet Registry
328
+ /// once a wallet heartbeat failure is detected.
329
+ /// @param publicKeyX Wallet's public key's X coordinate
330
+ /// @param publicKeyY Wallet's public key's Y coordinate
331
+ /// @dev Requirements:
332
+ /// - The only caller authorized to call this function is `registry`
333
+ /// - Wallet must be in Live state
334
+ function __ecdsaWalletHeartbeatFailedCallback(
335
+ bytes32,
336
+ bytes32 publicKeyX,
337
+ bytes32 publicKeyY
338
+ ) external override {
339
+ wallets.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);
340
+ }
341
+
342
+ /// @notice Notifies that the wallet is either old enough or has too few
343
+ /// satoshis left and qualifies to be closed.
344
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
345
+ /// @param walletMainUtxo Data of the wallet's main UTXO, as currently
346
+ /// known on the Ethereum chain.
347
+ /// @dev Requirements:
348
+ /// - Wallet must not be set as the current active wallet
349
+ /// - Wallet must exceed the wallet maximum age OR the wallet BTC
350
+ /// balance must be lesser than the minimum threshold. If the latter
351
+ /// case is true, the `walletMainUtxo` components must point to the
352
+ /// recent main UTXO of the given wallet, as currently known on the
353
+ /// Ethereum chain. If the wallet has no main UTXO, this parameter
354
+ /// can be empty as it is ignored since the wallet balance is
355
+ /// assumed to be zero.
356
+ /// - Wallet must be in Live state
357
+ function notifyCloseableWallet(
358
+ bytes20 walletPubKeyHash,
359
+ BitcoinTx.UTXO calldata walletMainUtxo
360
+ ) external {
361
+ wallets.notifyCloseableWallet(walletPubKeyHash, walletMainUtxo);
362
+ }
363
+
364
+ /// @notice Gets details about a registered wallet.
365
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
366
+ /// using Bitcoin HASH160 over the compressed ECDSA public key)
367
+ /// @return Wallet details.
368
+ function getWallet(bytes20 walletPubKeyHash)
369
+ external
370
+ view
371
+ returns (Wallets.Wallet memory)
372
+ {
373
+ return wallets.registeredWallets[walletPubKeyHash];
374
+ }
375
+
376
+ /// @notice Gets the public key hash of the active wallet.
377
+ /// @return The 20-byte public key hash (computed using Bitcoin HASH160
378
+ /// over the compressed ECDSA public key) of the active wallet.
379
+ /// Returns bytes20(0) if there is no active wallet at the moment.
380
+ function getActiveWalletPubKeyHash() external view returns (bytes20) {
381
+ return wallets.activeWalletPubKeyHash;
382
+ }
383
+
384
+ /// @notice Used by the depositor to reveal information about their P2(W)SH
60
385
  /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain
61
386
  /// wallet listens for revealed deposit events and may decide to
62
387
  /// include the revealed deposit in the next executed sweep.
63
388
  /// Information about the Bitcoin deposit can be revealed before or
64
- /// after the Bitcoin transaction with P2SH deposit is mined on the
65
- /// Bitcoin chain.
66
- /// @param fundingTxHash The BTC transaction hash containing BTC P2SH
67
- /// deposit funding transaction
68
- /// @param fundingOutputIndex The index of the transaction output in the
69
- /// funding TX with P2SH deposit, max 256
70
- /// @param blindingFactor The blinding factor used in the BTC P2SH deposit,
71
- /// max 2^64
72
- /// @param refundPubKey The refund pub key used in the BTC P2SH deposit
73
- /// @param amount The amount locked in the BTC P2SH deposit
74
- /// @param vault Bank vault to which the swept deposit should be routed
389
+ /// after the Bitcoin transaction with P2(W)SH deposit is mined on
390
+ /// the Bitcoin chain. Worth noting, the gas cost of this function
391
+ /// scales with the number of P2(W)SH transaction inputs and
392
+ /// outputs. The deposit may be routed to one of the trusted vaults.
393
+ /// When a deposit is routed to a vault, vault gets notified when
394
+ /// the deposit gets swept and it may execute the appropriate action.
395
+ /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`
396
+ /// @param reveal Deposit reveal data, see `RevealInfo struct
75
397
  /// @dev Requirements:
76
- /// - `msg.sender` must be the Ethereum address used in the P2SH BTC deposit,
77
- /// - `blindingFactor` must be the blinding factor used in the P2SH BTC deposit,
78
- /// - `refundPubKey` must be the refund pub key used in the P2SH BTC deposit,
79
- /// - `amount` must be the same as locked in the P2SH BTC deposit,
398
+ /// - `reveal.walletPubKeyHash` must identify a `Live` wallet
399
+ /// - `reveal.vault` must be 0x0 or point to a trusted vault
400
+ /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH
401
+ /// output of the BTC deposit transaction
402
+ /// - `reveal.depositor` must be the Ethereum address used in the
403
+ /// P2(W)SH BTC deposit transaction,
404
+ /// - `reveal.blindingFactor` must be the blinding factor used in the
405
+ /// P2(W)SH BTC deposit transaction,
406
+ /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in
407
+ /// the P2(W)SH BTC deposit transaction,
408
+ /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in
409
+ /// the P2(W)SH BTC deposit transaction,
410
+ /// - `reveal.refundLocktime` must be the refund locktime used in the
411
+ /// P2(W)SH BTC deposit transaction,
80
412
  /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`
81
- /// can be revealed by `msg.sender` only one time.
413
+ /// can be revealed only one time.
82
414
  ///
83
415
  /// If any of these requirements is not met, the wallet _must_ refuse
84
416
  /// to sweep the deposit and the depositor has to wait until the
85
417
  /// deposit script unlocks to receive their BTC back.
86
418
  function revealDeposit(
87
- bytes32 fundingTxHash,
88
- uint8 fundingOutputIndex,
89
- uint64 blindingFactor,
90
- bytes calldata refundPubKey,
91
- uint64 amount,
92
- address vault
419
+ BitcoinTx.Info calldata fundingTx,
420
+ Deposit.DepositRevealInfo calldata reveal
93
421
  ) external {
94
- uint256 depositId =
95
- uint256(
96
- keccak256(
97
- abi.encode(fundingTxHash, fundingOutputIndex, msg.sender)
98
- )
99
- );
100
-
101
- DepositInfo storage deposit = unswept[depositId];
102
- require(deposit.revealedAt == 0, "Deposit already revealed");
103
-
104
- deposit.amount = amount;
105
- deposit.vault = vault;
106
- /* solhint-disable-next-line not-rely-on-time */
107
- deposit.revealedAt = uint32(block.timestamp);
108
-
109
- emit DepositRevealed(
110
- depositId,
111
- fundingTxHash,
112
- fundingOutputIndex,
113
- msg.sender,
114
- blindingFactor,
115
- refundPubKey,
116
- amount,
117
- vault
118
- );
422
+ self.revealDeposit(wallets, fundingTx, reveal);
119
423
  }
120
424
 
121
425
  /// @notice Used by the wallet to prove the BTC deposit sweep transaction
@@ -125,52 +429,605 @@ contract Bridge {
125
429
  /// The function is performing Bank balance updates by first
126
430
  /// computing the Bitcoin fee for the sweep transaction. The fee is
127
431
  /// divided evenly between all swept deposits. Each depositor
128
- /// receives a balance in the bank equal to the amount they have
129
- /// declared during the reveal transaction, minus their fee share.
432
+ /// receives a balance in the bank equal to the amount inferred
433
+ /// during the reveal transaction, minus their fee share.
130
434
  ///
131
435
  /// It is possible to prove the given sweep only one time.
132
- /// @param txVersion Transaction version number (4-byte LE)
133
- /// @param txInputVector All transaction inputs prepended by the number of
134
- /// inputs encoded as a VarInt, max 0xFC(252) inputs
135
- /// @param txOutput Single sweep transaction output
136
- /// @param txLocktime Final 4 bytes of the transaction
137
- /// @param merkleProof The merkle proof of transaction inclusion in a block
138
- /// @param txIndexInBlock Transaction index in the block (0-indexed)
139
- /// @param bitcoinHeaders Single bytestring of 80-byte bitcoin headers,
140
- /// lowest height first
141
- function sweep(
142
- bytes4 txVersion,
143
- bytes memory txInputVector,
144
- bytes memory txOutput,
145
- bytes4 txLocktime,
146
- bytes memory merkleProof,
147
- uint256 txIndexInBlock,
148
- bytes memory bitcoinHeaders
436
+ /// @param sweepTx Bitcoin sweep transaction data
437
+ /// @param sweepProof Bitcoin sweep proof data
438
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
439
+ /// the Ethereum chain. If no main UTXO exists for the given wallet,
440
+ /// this parameter is ignored
441
+ /// @dev Requirements:
442
+ /// - `sweepTx` components must match the expected structure. See
443
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
444
+ /// correspond to appropriate Bitcoin transaction fields to produce
445
+ /// a provable transaction hash.
446
+ /// - The `sweepTx` should represent a Bitcoin transaction with 1..n
447
+ /// inputs. If the wallet has no main UTXO, all n inputs should
448
+ /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has
449
+ /// an existing main UTXO, one of the n inputs must point to that
450
+ /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH
451
+ /// revealed deposits UTXOs. That transaction must have only
452
+ /// one P2(W)PKH output locking funds on the 20-byte wallet public
453
+ /// key hash.
454
+ /// - `sweepProof` components must match the expected structure. See
455
+ /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
456
+ /// field must contain a valid number of block headers, not less
457
+ /// than the `txProofDifficultyFactor` contract constant.
458
+ /// - `mainUtxo` components must point to the recent main UTXO
459
+ /// of the given wallet, as currently known on the Ethereum chain.
460
+ /// If there is no main UTXO, this parameter is ignored.
461
+ function submitSweepProof(
462
+ BitcoinTx.Info calldata sweepTx,
463
+ BitcoinTx.Proof calldata sweepProof,
464
+ BitcoinTx.UTXO calldata mainUtxo
465
+ ) external {
466
+ self.submitSweepProof(wallets, sweepTx, sweepProof, mainUtxo);
467
+ }
468
+
469
+ /// @notice Submits a fraud challenge indicating that a UTXO being under
470
+ /// wallet control was unlocked by the wallet but was not used
471
+ /// according to the protocol rules. That means the wallet signed
472
+ /// a transaction input pointing to that UTXO and there is a unique
473
+ /// sighash and signature pair associated with that input. This
474
+ /// function uses those parameters to create a fraud accusation that
475
+ /// proves a given transaction input unlocking the given UTXO was
476
+ /// actually signed by the wallet. This function cannot determine
477
+ /// whether the transaction was actually broadcast and the input was
478
+ /// consumed in a fraudulent way so it just opens a challenge period
479
+ /// during which the wallet can defeat the challenge by submitting
480
+ /// proof of a transaction that consumes the given input according
481
+ /// to protocol rules. To prevent spurious allegations, the caller
482
+ /// must deposit ETH that is returned back upon justified fraud
483
+ /// challenge or confiscated otherwise.
484
+ ///@param walletPublicKey The public key of the wallet in the uncompressed
485
+ /// and unprefixed format (64 bytes)
486
+ /// @param sighash The hash that was used to produce the ECDSA signature
487
+ /// that is the subject of the fraud claim. This hash is constructed
488
+ /// by applying double SHA-256 over a serialized subset of the
489
+ /// transaction. The exact subset used as hash preimage depends on
490
+ /// the transaction input the signature is produced for. See BIP-143
491
+ /// for reference
492
+ /// @param signature Bitcoin signature in the R/S/V format
493
+ /// @dev Requirements:
494
+ /// - Wallet behind `walletPubKey` must be in `Live` or `MovingFunds`
495
+ /// state
496
+ /// - The challenger must send appropriate amount of ETH used as
497
+ /// fraud challenge deposit
498
+ /// - The signature (represented by r, s and v) must be generated by
499
+ /// the wallet behind `walletPubKey` during signing of `sighash`
500
+ /// - Wallet can be challenged for the given signature only once
501
+ function submitFraudChallenge(
502
+ bytes calldata walletPublicKey,
503
+ bytes32 sighash,
504
+ BitcoinTx.RSVSignature calldata signature
505
+ ) external payable {
506
+ bytes memory compressedWalletPublicKey = EcdsaLib.compressPublicKey(
507
+ walletPublicKey.slice32(0),
508
+ walletPublicKey.slice32(32)
509
+ );
510
+ bytes20 walletPubKeyHash = compressedWalletPublicKey.hash160View();
511
+
512
+ Wallets.Wallet storage wallet = wallets.registeredWallets[
513
+ walletPubKeyHash
514
+ ];
515
+
516
+ require(
517
+ wallet.state == Wallets.WalletState.Live ||
518
+ wallet.state == Wallets.WalletState.MovingFunds,
519
+ "Wallet is neither in Live nor MovingFunds state"
520
+ );
521
+
522
+ frauds.submitChallenge(
523
+ walletPublicKey,
524
+ walletPubKeyHash,
525
+ sighash,
526
+ signature
527
+ );
528
+ }
529
+
530
+ /// @notice Allows to defeat a pending fraud challenge against a wallet if
531
+ /// the transaction that spends the UTXO follows the protocol rules.
532
+ /// In order to defeat the challenge the same `walletPublicKey` and
533
+ /// signature (represented by `r`, `s` and `v`) must be provided as
534
+ /// were used to calculate the sighash during input signing.
535
+ /// The fraud challenge defeat attempt will only succeed if the
536
+ /// inputs in the preimage are considered honestly spent by the
537
+ /// wallet. Therefore the transaction spending the UTXO must be
538
+ /// proven in the Bridge before a challenge defeat is called.
539
+ /// If successfully defeated, the fraud challenge is marked as
540
+ /// resolved and the amount of ether deposited by the challenger is
541
+ /// sent to the treasury.
542
+ /// @param walletPublicKey The public key of the wallet in the uncompressed
543
+ /// and unprefixed format (64 bytes)
544
+ /// @param preimage The preimage which produces sighash used to generate the
545
+ /// ECDSA signature that is the subject of the fraud claim. It is a
546
+ /// serialized subset of the transaction. The exact subset used as
547
+ /// the preimage depends on the transaction input the signature is
548
+ /// produced for. See BIP-143 for reference
549
+ /// @param witness Flag indicating whether the preimage was produced for a
550
+ /// witness input. True for witness, false for non-witness input
551
+ /// @dev Requirements:
552
+ /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`
553
+ /// must identify an open fraud challenge
554
+ /// - the preimage must be a valid preimage of a transaction generated
555
+ /// according to the protocol rules and already proved in the Bridge
556
+ /// - before a defeat attempt is made the transaction that spends the
557
+ /// given UTXO must be proven in the Bridge
558
+ function defeatFraudChallenge(
559
+ bytes calldata walletPublicKey,
560
+ bytes calldata preimage,
561
+ bool witness
562
+ ) external {
563
+ uint256 utxoKey = frauds.unwrapChallenge(
564
+ walletPublicKey,
565
+ preimage,
566
+ witness
567
+ );
568
+
569
+ // Check that the UTXO key identifies a correctly spent UTXO.
570
+ require(
571
+ self.deposits[utxoKey].sweptAt > 0 || self.spentMainUTXOs[utxoKey],
572
+ "Spent UTXO not found among correctly spent UTXOs"
573
+ );
574
+
575
+ frauds.defeatChallenge(walletPublicKey, preimage, self.treasury);
576
+ }
577
+
578
+ /// @notice Notifies about defeat timeout for the given fraud challenge.
579
+ /// Can be called only if there was a fraud challenge identified by
580
+ /// the provided `walletPublicKey` and `sighash` and it was not
581
+ /// defeated on time. The amount of time that needs to pass after
582
+ /// a fraud challenge is reported is indicated by the
583
+ /// `challengeDefeatTimeout`. After a successful fraud challenge
584
+ /// defeat timeout notification the fraud challenge is marked as
585
+ /// resolved, the stake of each operator is slashed, the ether
586
+ /// deposited is returned to the challenger and the challenger is
587
+ /// rewarded.
588
+ /// @param walletPublicKey The public key of the wallet in the uncompressed
589
+ /// and unprefixed format (64 bytes)
590
+ /// @param sighash The hash that was used to produce the ECDSA signature
591
+ /// that is the subject of the fraud claim. This hash is constructed
592
+ /// by applying double SHA-256 over a serialized subset of the
593
+ /// transaction. The exact subset used as hash preimage depends on
594
+ /// the transaction input the signature is produced for. See BIP-143
595
+ /// for reference
596
+ /// @dev Requirements:
597
+ /// - `walletPublicKey`and `sighash` must identify an open fraud
598
+ /// challenge
599
+ /// - the amount of time indicated by `challengeDefeatTimeout` must
600
+ /// pass after the challenge was reported
601
+ function notifyFraudChallengeDefeatTimeout(
602
+ bytes calldata walletPublicKey,
603
+ bytes32 sighash
604
+ ) external {
605
+ frauds.notifyChallengeDefeatTimeout(walletPublicKey, sighash);
606
+ }
607
+
608
+ /// @notice Returns parameters used by the `Frauds` library.
609
+ /// @return slashingAmount Value of the slashing amount
610
+ /// @return notifierRewardMultiplier Value of the notifier reward multiplier
611
+ /// @return challengeDefeatTimeout Value of the challenge defeat timeout
612
+ /// @return challengeDepositAmount Value of the challenge deposit amount
613
+ function getFraudParameters()
614
+ external
615
+ view
616
+ returns (
617
+ uint256 slashingAmount,
618
+ uint256 notifierRewardMultiplier,
619
+ uint256 challengeDefeatTimeout,
620
+ uint256 challengeDepositAmount
621
+ )
622
+ {
623
+ slashingAmount = frauds.slashingAmount;
624
+ notifierRewardMultiplier = frauds.notifierRewardMultiplier;
625
+ challengeDefeatTimeout = frauds.challengeDefeatTimeout;
626
+ challengeDepositAmount = frauds.challengeDepositAmount;
627
+
628
+ return (
629
+ slashingAmount,
630
+ notifierRewardMultiplier,
631
+ challengeDefeatTimeout,
632
+ challengeDepositAmount
633
+ );
634
+ }
635
+
636
+ /// @notice Returns the fraud challenge identified by the given key built
637
+ /// as keccak256(walletPublicKey|sighash).
638
+ function fraudChallenges(uint256 challengeKey)
639
+ external
640
+ view
641
+ returns (Frauds.FraudChallenge memory)
642
+ {
643
+ return frauds.challenges[challengeKey];
644
+ }
645
+
646
+ /// @notice Requests redemption of the given amount from the specified
647
+ /// wallet to the redeemer Bitcoin output script.
648
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
649
+ /// using Bitcoin HASH160 over the compressed ECDSA public key)
650
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
651
+ /// the Ethereum chain
652
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
653
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
654
+ /// redeemed BTC
655
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
656
+ /// that is taken from redeemer's balance in the Bank upon request.
657
+ /// Once the request is handled, the actual amount of BTC locked
658
+ /// on the redeemer output script will be always lower than this value
659
+ /// since the treasury and Bitcoin transaction fees must be incurred.
660
+ /// The minimal amount satisfying the request can be computed as:
661
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
662
+ /// Fees values are taken at the moment of request creation.
663
+ /// @dev Requirements:
664
+ /// - Wallet behind `walletPubKeyHash` must be live
665
+ /// - `mainUtxo` components must point to the recent main UTXO
666
+ /// of the given wallet, as currently known on the Ethereum chain.
667
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
668
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
669
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
670
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
671
+ /// used for only one pending request at the same time
672
+ /// - Wallet must have enough Bitcoin balance to proceed the request
673
+ /// - Redeemer must make an allowance in the Bank that the Bridge
674
+ /// contract can spend the given `amount`.
675
+ function requestRedemption(
676
+ bytes20 walletPubKeyHash,
677
+ BitcoinTx.UTXO calldata mainUtxo,
678
+ bytes calldata redeemerOutputScript,
679
+ uint64 amount
680
+ ) external {
681
+ self.requestRedemption(
682
+ wallets,
683
+ walletPubKeyHash,
684
+ mainUtxo,
685
+ redeemerOutputScript,
686
+ amount
687
+ );
688
+ }
689
+
690
+ /// @notice Used by the wallet to prove the BTC redemption transaction
691
+ /// and to make the necessary bookkeeping. Redemption is only
692
+ /// accepted if it satisfies SPV proof.
693
+ ///
694
+ /// The function is performing Bank balance updates by burning
695
+ /// the total redeemed Bitcoin amount from Bridge balance and
696
+ /// transferring the treasury fee sum to the treasury address.
697
+ ///
698
+ /// It is possible to prove the given redemption only one time.
699
+ /// @param redemptionTx Bitcoin redemption transaction data
700
+ /// @param redemptionProof Bitcoin redemption proof data
701
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
702
+ /// the Ethereum chain
703
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
704
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
705
+ /// performed the redemption transaction
706
+ /// @dev Requirements:
707
+ /// - `redemptionTx` components must match the expected structure. See
708
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
709
+ /// correspond to appropriate Bitcoin transaction fields to produce
710
+ /// a provable transaction hash.
711
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
712
+ /// exactly 1 input that refers to the wallet's main UTXO. That
713
+ /// transaction should have 1..n outputs handling existing pending
714
+ /// redemption requests or pointing to reported timed out requests.
715
+ /// There can be also 1 optional output representing the
716
+ /// change and pointing back to the 20-byte wallet public key hash.
717
+ /// The change should be always present if the redeemed value sum
718
+ /// is lower than the total wallet's BTC balance.
719
+ /// - `redemptionProof` components must match the expected structure.
720
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
721
+ /// field must contain a valid number of block headers, not less
722
+ /// than the `txProofDifficultyFactor` contract constant.
723
+ /// - `mainUtxo` components must point to the recent main UTXO
724
+ /// of the given wallet, as currently known on the Ethereum chain.
725
+ /// Additionally, the recent main UTXO on Ethereum must be set.
726
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
727
+ /// as transaction single input.
728
+ /// Other remarks:
729
+ /// - Putting the change output as the first transaction output can
730
+ /// save some gas because the output processing loop begins each
731
+ /// iteration by checking whether the given output is the change
732
+ /// thus uses some gas for making the comparison. Once the change
733
+ /// is identified, that check is omitted in further iterations.
734
+ function submitRedemptionProof(
735
+ BitcoinTx.Info calldata redemptionTx,
736
+ BitcoinTx.Proof calldata redemptionProof,
737
+ BitcoinTx.UTXO calldata mainUtxo,
738
+ bytes20 walletPubKeyHash
739
+ ) external {
740
+ self.submitRedemptionProof(
741
+ wallets,
742
+ redemptionTx,
743
+ redemptionProof,
744
+ mainUtxo,
745
+ walletPubKeyHash
746
+ );
747
+ }
748
+
749
+ /// @notice Notifies that there is a pending redemption request associated
750
+ /// with the given wallet, that has timed out. The redemption
751
+ /// request is identified by the key built as
752
+ /// `keccak256(walletPubKeyHash | redeemerOutputScript)`.
753
+ /// The results of calling this function: the pending redemptions
754
+ /// value for the wallet will be decreased by the requested amount
755
+ /// (minus treasury fee), the tokens taken from the redeemer on
756
+ /// redemption request will be returned to the redeemer, the request
757
+ /// will be moved from pending redemptions to timed-out redemptions.
758
+ /// If the state of the wallet is `Live` or `MovingFunds`, the
759
+ /// wallet operators will be slashed.
760
+ /// Additionally, if the state of wallet is `Live`, the wallet will
761
+ /// be closed or marked as `MovingFunds` (depending on the presence
762
+ /// or absence of the wallet's main UTXO) and the wallet will no
763
+ /// longer be marked as the active wallet (if it was marked as such).
764
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet
765
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
766
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH)
767
+ /// @dev Requirements:
768
+ /// - The redemption request identified by `walletPubKeyHash` and
769
+ /// `redeemerOutputScript` must exist
770
+ /// - The amount of time defined by `redemptionTimeout` must have
771
+ /// passed since the redemption was requested (the request must be
772
+ /// timed-out).
773
+ function notifyRedemptionTimeout(
774
+ bytes20 walletPubKeyHash,
775
+ bytes calldata redeemerOutputScript
776
+ ) external {
777
+ self.notifyRedemptionTimeout(
778
+ wallets,
779
+ walletPubKeyHash,
780
+ redeemerOutputScript
781
+ );
782
+ }
783
+
784
+ /// @notice Used by the wallet to prove the BTC moving funds transaction
785
+ /// and to make the necessary state changes. Moving funds is only
786
+ /// accepted if it satisfies SPV proof.
787
+ ///
788
+ /// The function validates the moving funds transaction structure
789
+ /// by checking if it actually spends the main UTXO of the declared
790
+ /// wallet and locks the value on the pre-committed target wallets
791
+ /// using a reasonable transaction fee. If all preconditions are
792
+ /// met, this functions closes the source wallet.
793
+ ///
794
+ /// It is possible to prove the given moving funds transaction only
795
+ /// one time.
796
+ /// @param movingFundsTx Bitcoin moving funds transaction data
797
+ /// @param movingFundsProof Bitcoin moving funds proof data
798
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
799
+ /// the Ethereum chain
800
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
801
+ /// HASH160 over the compressed ECDSA public key) of the wallet
802
+ /// which performed the moving funds transaction
803
+ /// @dev Requirements:
804
+ /// - `movingFundsTx` components must match the expected structure. See
805
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
806
+ /// correspond to appropriate Bitcoin transaction fields to produce
807
+ /// a provable transaction hash.
808
+ /// - The `movingFundsTx` should represent a Bitcoin transaction with
809
+ /// exactly 1 input that refers to the wallet's main UTXO. That
810
+ /// transaction should have 1..n outputs corresponding to the
811
+ /// pre-committed target wallets. Outputs must be ordered in the
812
+ /// same way as their corresponding target wallets are ordered
813
+ /// within the target wallets commitment.
814
+ /// - `movingFundsProof` components must match the expected structure.
815
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
816
+ /// field must contain a valid number of block headers, not less
817
+ /// than the `txProofDifficultyFactor` contract constant.
818
+ /// - `mainUtxo` components must point to the recent main UTXO
819
+ /// of the given wallet, as currently known on the Ethereum chain.
820
+ /// Additionally, the recent main UTXO on Ethereum must be set.
821
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
822
+ /// as transaction single input.
823
+ /// - The wallet that `walletPubKeyHash` points to must be in the
824
+ /// MovingFunds state.
825
+ /// - The target wallets commitment must be submitted by the wallet
826
+ /// that `walletPubKeyHash` points to.
827
+ /// - The total Bitcoin transaction fee must be lesser or equal
828
+ /// to `movingFundsTxMaxTotalFee` governable parameter.
829
+ function submitMovingFundsProof(
830
+ BitcoinTx.Info calldata movingFundsTx,
831
+ BitcoinTx.Proof calldata movingFundsProof,
832
+ BitcoinTx.UTXO calldata mainUtxo,
833
+ bytes20 walletPubKeyHash
149
834
  ) external {
150
- // TODO We need to read `fundingTxHash`, `fundingOutputIndex` and
151
- // P2SH script depositor address from `txInputVector`.
152
- // We then hash them to obtain deposit identifier and read
153
- // DepositInfo. From DepositInfo we know what amount was declared
154
- // by the depositor in their reveal transaction and we use that
155
- // amount to update their Bank balance, minus fee.
156
- //
157
- // TODO We need to validate if the sum in the output minus the
158
- // amount from the previous wallet balance input minus fees is
159
- // equal to the amount by which Bank balances were increased.
160
- //
161
- // TODO We need to validate txOutput to see if the balance was not
162
- // transferred away from the wallet before increasing balances in
163
- // the bank.
164
- //
165
- // TODO Delete deposit from unswept mapping or mark it as swept
166
- // depending on the gas costs. Alternativly, do not allow to
167
- // use the same TX input vector twice. Sweep should be provable
168
- // only one time.
169
- }
170
-
171
- // TODO It is possible a malicious wallet can sweep deposits that can not
172
- // be later proved on Ethereum. For example, a deposit with
173
- // an incorrect amount revealed. We need to provide a function for honest
174
- // depositors, next to sweep, to prove their swept balances on Ethereum
175
- // selectively, based on deposits they have earlier received.
835
+ self.submitMovingFundsProof(
836
+ wallets,
837
+ movingFundsTx,
838
+ movingFundsProof,
839
+ mainUtxo,
840
+ walletPubKeyHash
841
+ );
842
+ }
843
+
844
+ /// @notice Returns the addresses of contracts Bridge is interacting with.
845
+ /// @return bank Address of the Bank the Bridge belongs to.
846
+ /// @return relay Address of the Bitcoin relay providing the current Bitcoin
847
+ /// network difficulty.
848
+ function getContracts() external view returns (Bank bank, IRelay relay) {
849
+ bank = self.bank;
850
+ relay = self.relay;
851
+ }
852
+
853
+ /// @notice Address where the deposit treasury fees will be sent to.
854
+ /// Treasury takes part in the operators rewarding process.
855
+ function treasury() external view returns (address treasury) {
856
+ treasury = self.treasury;
857
+ }
858
+
859
+ /// @notice The number of confirmations on the Bitcoin chain required to
860
+ /// successfully evaluate an SPV proof.
861
+ function txProofDifficultyFactor()
862
+ external
863
+ view
864
+ returns (uint256 txProofDifficultyFactor)
865
+ {
866
+ txProofDifficultyFactor = self.txProofDifficultyFactor;
867
+ }
868
+
869
+ /// @notice Returns the current values of Bridge deposit parameters.
870
+ /// @return depositDustThreshold The minimal amount that can be requested
871
+ /// to deposit. Value of this parameter must take into account the
872
+ /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`
873
+ /// parameters in order to make requests that can incur the
874
+ /// treasury and transaction fee and still satisfy the depositor.
875
+ /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury
876
+ /// fee taken from each deposit and transferred to the treasury upon
877
+ /// sweep proof submission. That fee is computed as follows:
878
+ /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`
879
+ /// For example, if the treasury fee needs to be 2% of each deposit,
880
+ /// the `depositTreasuryFeeDivisor` should be set to `50`
881
+ /// because `1/50 = 0.02 = 2%`.
882
+ /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can
883
+ /// be incurred by each swept deposit being part of the given sweep
884
+ /// transaction. If the maximum BTC transaction fee is exceeded,
885
+ /// such transaction is considered a fraud.
886
+ function depositParameters()
887
+ external
888
+ view
889
+ returns (
890
+ uint64 depositDustThreshold,
891
+ uint64 depositTreasuryFeeDivisor,
892
+ uint64 depositTxMaxFee
893
+ )
894
+ {
895
+ depositDustThreshold = self.depositDustThreshold;
896
+ depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;
897
+ depositTxMaxFee = self.depositTxMaxFee;
898
+ }
899
+
900
+ /// @notice Returns the current values of Bridge redemption parameters.
901
+ /// @return redemptionDustThreshold The minimal amount that can be requested
902
+ /// for redemption. Value of this parameter must take into account
903
+ /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
904
+ /// parameters in order to make requests that can incur the
905
+ /// treasury and transaction fee and still satisfy the redeemer.
906
+ /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury
907
+ /// fee taken from each redemption request and transferred to the
908
+ /// treasury upon successful request finalization. That fee is
909
+ /// computed as follows:
910
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
911
+ /// For example, if the treasury fee needs to be 2% of each
912
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
913
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
914
+ /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that
915
+ /// can be incurred by each redemption request being part of the
916
+ /// given redemption transaction. If the maximum BTC transaction
917
+ /// fee is exceeded, such transaction is considered a fraud.
918
+ /// @return redemptionTimeout Time after which the redemption request can be
919
+ /// reported as timed out. It is counted from the moment when the
920
+ /// redemption request was created via `requestRedemption` call.
921
+ /// Reported timed out requests are cancelled and locked TBTC is
922
+ /// returned to the redeemer in full amount.
923
+ function redemptionParameters()
924
+ external
925
+ view
926
+ returns (
927
+ uint64 redemptionDustThreshold,
928
+ uint64 redemptionTreasuryFeeDivisor,
929
+ uint64 redemptionTxMaxFee,
930
+ uint256 redemptionTimeout,
931
+ address treasury,
932
+ uint256 txProofDifficultyFactor
933
+ )
934
+ {
935
+ redemptionDustThreshold = self.redemptionDustThreshold;
936
+ redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;
937
+ redemptionTxMaxFee = self.redemptionTxMaxFee;
938
+ redemptionTimeout = self.redemptionTimeout;
939
+ }
940
+
941
+ /// @notice Returns the current values of Bridge moving funds between
942
+ /// wallets parameters.
943
+ /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC
944
+ /// transaction fee that is acceptable in a single moving funds
945
+ /// transaction. This is a _total_ max fee for the entire moving
946
+ /// funds transaction.
947
+ function movingFundsParameters()
948
+ external
949
+ view
950
+ returns (uint64 movingFundsTxMaxTotalFee)
951
+ {
952
+ // TODO: we will have more parameters here, for example moving funds timeout
953
+ movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;
954
+ }
955
+
956
+ /// @notice Indicates if the vault with the given address is trusted or not.
957
+ /// Depositors can route their revealed deposits only to trusted
958
+ /// vaults and have trusted vaults notified about new deposits as
959
+ /// soon as these deposits get swept. Vaults not trusted by the
960
+ /// Bridge can still be used by Bank balance owners on their own
961
+ /// responsibility - anyone can approve their Bank balance to any
962
+ /// address.
963
+ function isVaultTrusted(address vault) external view returns (bool) {
964
+ return self.isVaultTrusted[vault];
965
+ }
966
+
967
+ /// @notice Collection of all revealed deposits indexed by
968
+ /// keccak256(fundingTxHash | fundingOutputIndex).
969
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
970
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
971
+ /// and invalid deposits and the wallet is responsible for
972
+ /// validating them before attempting to execute a sweep.
973
+ function deposits(uint256 depositKey)
974
+ external
975
+ view
976
+ returns (Deposit.DepositRequest memory)
977
+ {
978
+ return self.deposits[depositKey];
979
+ }
980
+
981
+ /// @notice Collection of main UTXOs that are honestly spent indexed by
982
+ /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash
983
+ /// is bytes32 (ordered as in Bitcoin internally) and
984
+ /// fundingOutputIndex an uint32. A main UTXO is considered honestly
985
+ /// spent if it was used as an input of a transaction that have been
986
+ /// proven in the Bridge.
987
+ function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {
988
+ return self.spentMainUTXOs[utxoKey];
989
+ }
990
+
991
+ /// @notice Collection of all pending redemption requests indexed by
992
+ /// redemption key built as
993
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
994
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
995
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
996
+ /// public key) and redeemerOutputScript is a Bitcoin script
997
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
998
+ /// redeemed BTC as requested by the redeemer. Requests are added
999
+ /// to this mapping by the `requestRedemption` method (duplicates
1000
+ /// not allowed) and are removed by one of the following methods:
1001
+ /// - `submitRedemptionProof` in case the request was handled
1002
+ /// successfully
1003
+ /// - `notifyRedemptionTimeout` in case the request was reported
1004
+ /// to be timed out
1005
+ function pendingRedemptions(uint256 redemptionKey)
1006
+ external
1007
+ view
1008
+ returns (Redeem.RedemptionRequest memory)
1009
+ {
1010
+ return self.pendingRedemptions[redemptionKey];
1011
+ }
1012
+
1013
+ /// @notice Collection of all timed out redemptions requests indexed by
1014
+ /// redemption key built as
1015
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1016
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1017
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1018
+ /// public key) and redeemerOutputScript is the Bitcoin script
1019
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
1020
+ /// out request. Timed out requests are stored in this mapping to
1021
+ /// avoid slashing the wallets multiple times for the same timeout.
1022
+ /// Only one method can add to this mapping:
1023
+ /// - `notifyRedemptionTimeout` which puts the redemption key
1024
+ /// to this mapping basing on a timed out request stored
1025
+ /// previously in `pendingRedemptions` mapping.
1026
+ function timedOutRedemptions(uint256 redemptionKey)
1027
+ external
1028
+ view
1029
+ returns (Redeem.RedemptionRequest memory)
1030
+ {
1031
+ return self.timedOutRedemptions[redemptionKey];
1032
+ }
176
1033
  }