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

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