@keep-network/tbtc-v2 0.1.1-dev.10 → 0.1.1-dev.100

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 (115) hide show
  1. package/README.adoc +12 -0
  2. package/artifacts/Bank.json +807 -0
  3. package/artifacts/Bridge.json +2300 -0
  4. package/artifacts/Deposit.json +117 -0
  5. package/artifacts/DepositSweep.json +77 -0
  6. package/artifacts/EcdsaDkgValidator.json +532 -0
  7. package/artifacts/EcdsaInactivity.json +156 -0
  8. package/artifacts/EcdsaSortitionPool.json +1004 -0
  9. package/artifacts/Fraud.json +164 -0
  10. package/artifacts/KeepRegistry.json +99 -0
  11. package/artifacts/KeepStake.json +286 -0
  12. package/artifacts/KeepToken.json +711 -0
  13. package/artifacts/KeepTokenStaking.json +483 -0
  14. package/artifacts/MovingFunds.json +249 -0
  15. package/artifacts/NuCypherStakingEscrow.json +256 -0
  16. package/artifacts/NuCypherToken.json +711 -0
  17. package/artifacts/RandomBeaconStub.json +141 -0
  18. package/artifacts/Redemption.json +174 -0
  19. package/artifacts/ReimbursementPool.json +509 -0
  20. package/artifacts/Relay.json +123 -0
  21. package/artifacts/T.json +1148 -0
  22. package/artifacts/TBTC.json +27 -26
  23. package/artifacts/TBTCToken.json +27 -26
  24. package/artifacts/TBTCVault.json +691 -0
  25. package/artifacts/TokenStaking.json +2288 -0
  26. package/artifacts/TokenholderGovernor.json +1795 -0
  27. package/artifacts/TokenholderTimelock.json +1058 -0
  28. package/artifacts/VendingMachine.json +31 -30
  29. package/artifacts/VendingMachineKeep.json +400 -0
  30. package/artifacts/VendingMachineNuCypher.json +400 -0
  31. package/artifacts/WalletRegistry.json +1843 -0
  32. package/artifacts/WalletRegistryGovernance.json +2754 -0
  33. package/artifacts/Wallets.json +186 -0
  34. package/artifacts/solcInputs/8b65103759482b36742c6820fa66b63b.json +314 -0
  35. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  36. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.json +2 -2
  37. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  38. package/build/contracts/bank/Bank.sol/Bank.json +10 -5
  39. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +4 -0
  40. package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.json +34 -0
  41. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  42. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +2 -2
  43. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  44. package/build/contracts/bridge/Bridge.sol/Bridge.json +2549 -198
  45. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +4 -0
  46. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +226 -0
  47. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +4 -0
  48. package/build/contracts/bridge/Deposit.sol/Deposit.json +72 -0
  49. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +4 -0
  50. package/build/contracts/bridge/DepositSweep.sol/DepositSweep.json +30 -0
  51. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +4 -0
  52. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.json +10 -0
  53. package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +4 -0
  54. package/build/contracts/bridge/Fraud.sol/Fraud.json +86 -0
  55. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +4 -0
  56. package/build/contracts/bridge/Heartbeat.sol/Heartbeat.json +10 -0
  57. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +4 -0
  58. package/build/contracts/bridge/IRelay.sol/IRelay.json +37 -0
  59. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  60. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +138 -0
  61. package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +4 -0
  62. package/build/contracts/bridge/Redemption.sol/OutboundTx.json +10 -0
  63. package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +4 -0
  64. package/build/contracts/bridge/Redemption.sol/Redemption.json +92 -0
  65. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  66. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.json +2 -2
  67. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +4 -0
  68. package/build/contracts/bridge/Wallets.sol/Wallets.json +112 -0
  69. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  70. package/build/contracts/token/TBTC.sol/TBTC.json +2 -2
  71. package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +4 -0
  72. package/build/contracts/vault/DonationVault.sol/DonationVault.json +108 -0
  73. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  74. package/build/contracts/vault/IVault.sol/IVault.json +5 -0
  75. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  76. package/build/contracts/vault/TBTCVault.sol/TBTCVault.json +273 -5
  77. package/contracts/GovernanceUtils.sol +4 -4
  78. package/contracts/bank/Bank.sol +113 -66
  79. package/contracts/bank/IReceiveBalanceApproval.sol +45 -0
  80. package/contracts/bridge/BitcoinTx.sol +267 -10
  81. package/contracts/bridge/Bridge.sol +1698 -245
  82. package/contracts/bridge/BridgeState.sol +768 -0
  83. package/contracts/bridge/Deposit.sol +269 -0
  84. package/contracts/bridge/DepositSweep.sol +574 -0
  85. package/contracts/bridge/EcdsaLib.sol +45 -0
  86. package/contracts/bridge/Fraud.sol +579 -0
  87. package/contracts/bridge/Heartbeat.sol +112 -0
  88. package/contracts/bridge/IRelay.sol +28 -0
  89. package/contracts/bridge/MovingFunds.sol +1077 -0
  90. package/contracts/bridge/Redemption.sol +1058 -0
  91. package/contracts/bridge/VendingMachine.sol +2 -2
  92. package/contracts/bridge/Wallets.sol +719 -0
  93. package/contracts/hardhat-dependency-compiler/.hardhat-dependency-compiler +1 -0
  94. package/contracts/hardhat-dependency-compiler/@keep-network/ecdsa/contracts/WalletRegistry.sol +3 -0
  95. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol +3 -0
  96. package/contracts/hardhat-dependency-compiler/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol +3 -0
  97. package/contracts/token/TBTC.sol +1 -1
  98. package/contracts/vault/DonationVault.sol +125 -0
  99. package/contracts/vault/IVault.sol +6 -22
  100. package/contracts/vault/TBTCVault.sol +188 -29
  101. package/deploy/00_resolve_relay.ts +28 -0
  102. package/deploy/{03_transfer_roles.ts → 03_transfer_vending_machine_roles.ts} +1 -1
  103. package/deploy/04_deploy_bank.ts +27 -0
  104. package/deploy/05_deploy_bridge.ts +80 -0
  105. package/deploy/06_deploy_tbtc_vault.ts +30 -0
  106. package/deploy/07_bank_update_bridge.ts +19 -0
  107. package/deploy/08_transfer_bank_ownership.ts +15 -0
  108. package/deploy/09_transfer_tbtc_vault_ownership.ts +15 -0
  109. package/deploy/10_transfer_bridge_governance.ts +20 -0
  110. package/deploy/11_initialize_wallet_owner.ts +18 -0
  111. package/deploy/11_transfer_proxy_admin_ownership.ts +30 -0
  112. package/deploy/12_deploy_proxy_admin_with_deputy.ts +33 -0
  113. package/export.json +15771 -443
  114. package/package.json +34 -26
  115. package/artifacts/solcInputs/524094faac10a04084fcc411e06dab84.json +0 -128
@@ -0,0 +1,1058 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ // ██████████████ ▐████▌ ██████████████
4
+ // ██████████████ ▐████▌ ██████████████
5
+ // ▐████▌ ▐████▌
6
+ // ▐████▌ ▐████▌
7
+ // ██████████████ ▐████▌ ██████████████
8
+ // ██████████████ ▐████▌ ██████████████
9
+ // ▐████▌ ▐████▌
10
+ // ▐████▌ ▐████▌
11
+ // ▐████▌ ▐████▌
12
+ // ▐████▌ ▐████▌
13
+ // ▐████▌ ▐████▌
14
+ // ▐████▌ ▐████▌
15
+
16
+ pragma solidity ^0.8.9;
17
+
18
+ import {BTCUtils} from "@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol";
19
+ import {BytesLib} from "@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol";
20
+
21
+ import "./BitcoinTx.sol";
22
+ import "./BridgeState.sol";
23
+ import "./Wallets.sol";
24
+
25
+ import "../bank/Bank.sol";
26
+
27
+ /// @notice Aggregates functions common to the redemption transaction proof
28
+ /// validation and to the moving funds transaction proof validation.
29
+ library OutboundTx {
30
+ using BTCUtils for bytes;
31
+
32
+ /// @notice Checks whether an outbound Bitcoin transaction performed from
33
+ /// the given wallet has an input vector that contains a single
34
+ /// input referring to the wallet's main UTXO. Marks that main UTXO
35
+ /// as correctly spent if the validation succeeds. Reverts otherwise.
36
+ /// There are two outbound transactions from a wallet possible: a
37
+ /// redemption transaction or a moving funds to another wallet
38
+ /// transaction.
39
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input
40
+ /// vector. This function assumes vector's structure is valid so it
41
+ /// must be validated using e.g. `BTCUtils.validateVin` function
42
+ /// before it is passed here.
43
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
44
+ /// the Ethereum chain.
45
+ function processWalletOutboundTxInput(
46
+ BridgeState.Storage storage self,
47
+ bytes memory walletOutboundTxInputVector,
48
+ BitcoinTx.UTXO calldata mainUtxo
49
+ ) internal {
50
+ // Assert that the single outbound transaction input actually
51
+ // refers to the wallet's main UTXO.
52
+ (
53
+ bytes32 outpointTxHash,
54
+ uint32 outpointIndex
55
+ ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);
56
+ require(
57
+ mainUtxo.txHash == outpointTxHash &&
58
+ mainUtxo.txOutputIndex == outpointIndex,
59
+ "Outbound transaction input must point to the wallet's main UTXO"
60
+ );
61
+
62
+ // Main UTXO used as an input, mark it as spent.
63
+ self.spentMainUTXOs[
64
+ uint256(
65
+ keccak256(
66
+ abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
67
+ )
68
+ )
69
+ ] = true;
70
+ }
71
+
72
+ /// @notice Parses the input vector of an outbound Bitcoin transaction
73
+ /// performed from the given wallet. It extracts the single input
74
+ /// then the transaction hash and output index from its outpoint.
75
+ /// There are two outbound transactions from a wallet possible: a
76
+ /// redemption transaction or a moving funds to another wallet
77
+ /// transaction.
78
+ /// @param walletOutboundTxInputVector Bitcoin outbound transaction input
79
+ /// vector. This function assumes vector's structure is valid so it
80
+ /// must be validated using e.g. `BTCUtils.validateVin` function
81
+ /// before it is passed here.
82
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
83
+ /// pointed in the input's outpoint.
84
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
85
+ /// which is pointed in the input's outpoint.
86
+ function parseWalletOutboundTxInput(
87
+ bytes memory walletOutboundTxInputVector
88
+ ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {
89
+ // To determine the total number of Bitcoin transaction inputs,
90
+ // we need to parse the compactSize uint (VarInt) the input vector is
91
+ // prepended by. That compactSize uint encodes the number of vector
92
+ // elements using the format presented in:
93
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
94
+ // We don't need asserting the compactSize uint is parseable since it
95
+ // was already checked during `validateVin` validation.
96
+ // See `BitcoinTx.inputVector` docs for more details.
97
+ (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();
98
+ require(
99
+ inputsCount == 1,
100
+ "Outbound transaction must have a single input"
101
+ );
102
+
103
+ bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);
104
+
105
+ outpointTxHash = input.extractInputTxIdLE();
106
+
107
+ outpointIndex = BTCUtils.reverseUint32(
108
+ uint32(input.extractTxIndexLE())
109
+ );
110
+
111
+ // There is only one input in the transaction. Input has an outpoint
112
+ // field that is a reference to the transaction being spent (see
113
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
114
+ // to spend (`outpointTxHash`) and the index of the specific output
115
+ // from that transaction (`outpointIndex`).
116
+ return (outpointTxHash, outpointIndex);
117
+ }
118
+ }
119
+
120
+ /// @title Bridge redemption
121
+ /// @notice The library handles the logic for redeeming Bitcoin balances from
122
+ /// the Bridge.
123
+ /// @dev To initiate a redemption, a user with a Bank balance supplies
124
+ /// a Bitcoin address. Then, the system calculates the redemption fee, and
125
+ /// releases balance to the provided Bitcoin address. Just like in case of
126
+ /// sweeps of revealed deposits, redemption requests are processed in
127
+ /// batches and require SPV proof to be submitted to the Bridge.
128
+ library Redemption {
129
+ using BridgeState for BridgeState.Storage;
130
+ using Wallets for BridgeState.Storage;
131
+ using BitcoinTx for BridgeState.Storage;
132
+
133
+ using BTCUtils for bytes;
134
+ using BytesLib for bytes;
135
+
136
+ /// @notice Represents a redemption request.
137
+ struct RedemptionRequest {
138
+ // ETH address of the redeemer who created the request.
139
+ address redeemer;
140
+ // Requested TBTC amount in satoshi.
141
+ uint64 requestedAmount;
142
+ // Treasury TBTC fee in satoshi at the moment of request creation.
143
+ uint64 treasuryFee;
144
+ // Transaction maximum BTC fee in satoshi at the moment of request
145
+ // creation.
146
+ uint64 txMaxFee;
147
+ // UNIX timestamp the request was created at.
148
+ uint32 requestedAt;
149
+ // This struct doesn't contain `__gap` property as the structure is stored
150
+ // in a mapping, mappings store values in different slots and they are
151
+ // not contiguous with other values.
152
+ }
153
+
154
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
155
+ /// outputs processing.
156
+ struct RedemptionTxOutputsInfo {
157
+ // Total TBTC value in satoshi that should be burned by the Bridge.
158
+ // It includes the total amount of all BTC redeemed in the transaction
159
+ // and the fee paid to BTC miners for the redemption transaction.
160
+ uint64 totalBurnableValue;
161
+ // Total TBTC value in satoshi that should be transferred to
162
+ // the treasury. It is a sum of all treasury fees paid by all
163
+ // redeemers included in the redemption transaction.
164
+ uint64 totalTreasuryFee;
165
+ // Index of the change output. The change output becomes
166
+ // the new main wallet's UTXO.
167
+ uint32 changeIndex;
168
+ // Value in satoshi of the change output.
169
+ uint64 changeValue;
170
+ // This struct doesn't contain `__gap` property as the structure is not
171
+ // stored, it is used as a function's memory argument.
172
+ }
173
+
174
+ /// @notice Represents temporary information needed during the processing of
175
+ /// the redemption Bitcoin transaction outputs. This structure is an
176
+ /// internal one and should not be exported outside of the redemption
177
+ /// transaction processing code.
178
+ /// @dev Allows to mitigate "stack too deep" errors on EVM.
179
+ struct RedemptionTxOutputsProcessingInfo {
180
+ // The first output starting index in the transaction.
181
+ uint256 outputStartingIndex;
182
+ // The number of outputs in the transaction.
183
+ uint256 outputsCount;
184
+ // P2PKH script for the wallet. Needed to determine the change output.
185
+ bytes32 walletP2PKHScriptKeccak;
186
+ // P2WPKH script for the wallet. Needed to determine the change output.
187
+ bytes32 walletP2WPKHScriptKeccak;
188
+ // This struct doesn't contain `__gap` property as the structure is not
189
+ // stored, it is used as a function's memory argument.
190
+ }
191
+
192
+ event RedemptionRequested(
193
+ bytes20 indexed walletPubKeyHash,
194
+ bytes redeemerOutputScript,
195
+ address indexed redeemer,
196
+ uint64 requestedAmount,
197
+ uint64 treasuryFee,
198
+ uint64 txMaxFee
199
+ );
200
+
201
+ event RedemptionsCompleted(
202
+ bytes20 indexed walletPubKeyHash,
203
+ bytes32 redemptionTxHash
204
+ );
205
+
206
+ event RedemptionTimedOut(
207
+ bytes20 indexed walletPubKeyHash,
208
+ bytes redeemerOutputScript
209
+ );
210
+
211
+ /// @notice Requests redemption of the given amount from the specified
212
+ /// wallet to the redeemer Bitcoin output script.
213
+ /// This function handles the simplest case, where balance owner is
214
+ /// the redeemer.
215
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
216
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
217
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
218
+ /// the Ethereum chain.
219
+ /// @param balanceOwner The address of the Bank balance owner whose balance
220
+ /// is getting redeemed. Balance owner address is stored as
221
+ /// a redemeer address who will be able co claim back the Bank
222
+ /// balance if anything goes wrong during the redemption.
223
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
224
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
225
+ /// redeemed BTC.
226
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
227
+ /// that is taken from the `balanceOwner` upon request.
228
+ /// Once the request is handled, the actual amount of BTC locked
229
+ /// on the redeemer output script will be always lower than this value
230
+ /// since the treasury and Bitcoin transaction fees must be incurred.
231
+ /// The minimal amount satisfying the request can be computed as:
232
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
233
+ /// Fees values are taken at the moment of request creation.
234
+ /// @dev Requirements:
235
+ /// - Wallet behind `walletPubKeyHash` must be live,
236
+ /// - `mainUtxo` components must point to the recent main UTXO
237
+ /// of the given wallet, as currently known on the Ethereum chain,
238
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
239
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
240
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
241
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
242
+ /// used for only one pending request at the same time,
243
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
244
+ /// - Balance owner must make an allowance in the Bank that the Bridge
245
+ /// contract can spend the given `amount`.
246
+ function requestRedemption(
247
+ BridgeState.Storage storage self,
248
+ bytes20 walletPubKeyHash,
249
+ BitcoinTx.UTXO calldata mainUtxo,
250
+ address balanceOwner,
251
+ bytes calldata redeemerOutputScript,
252
+ uint64 amount
253
+ ) external {
254
+ requestRedemption(
255
+ self,
256
+ walletPubKeyHash,
257
+ mainUtxo,
258
+ balanceOwner,
259
+ balanceOwner,
260
+ redeemerOutputScript,
261
+ amount
262
+ );
263
+ }
264
+
265
+ /// @notice Requests redemption of the given amount from the specified
266
+ /// wallet to the redeemer Bitcoin output script. Used by
267
+ /// `Bridge.receiveBalanceApproval`. Can handle more complex cases
268
+ /// where balance owner may be someone else than the redeemer.
269
+ /// @param balanceOwner The address of the Bank balance owner whose balance
270
+ /// is getting redeemed.
271
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
272
+ /// that is taken from the `balanceOwner` upon request.
273
+ /// Once the request is handled, the actual amount of BTC locked
274
+ /// on the redeemer output script will be always lower than this value
275
+ /// since the treasury and Bitcoin transaction fees must be incurred.
276
+ /// The minimal amount satisfying the request can be computed as:
277
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
278
+ /// Fees values are taken at the moment of request creation.
279
+ /// @param redemptionData ABI-encoded redemption data:
280
+ /// [
281
+ /// address redeemer,
282
+ /// bytes20 walletPubKeyHash,
283
+ /// bytes32 mainUtxoTxHash,
284
+ /// uint32 mainUtxoTxOutputIndex,
285
+ /// uint64 mainUtxoTxOutputValue,
286
+ /// bytes redeemerOutputScript
287
+ /// ]
288
+ ///
289
+ /// - redeemer: The Ethereum address of the redeemer who will be able
290
+ /// to claim Bank balance if anything goes wrong during the redemption.
291
+ /// In the most basic case, when someone redeems their Bitcoin
292
+ /// balance from the Bank, `balanceOwner` is the same as `redemeer`.
293
+ /// However, when a Vault is redeeming part of its balance for some
294
+ /// redeemer address (for example, someone who has earlier deposited
295
+ /// into that Vault), `balanceOwner` is the Vault, and `redemeer` is
296
+ /// the address for which the vault is redeeming its balance to,
297
+ /// - walletPubKeyHash: The 20-byte wallet public key hash (computed
298
+ /// using Bitcoin HASH160 over the compressed ECDSA public key),
299
+ /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as
300
+ /// currently known on the Ethereum chain,
301
+ /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output
302
+ /// index, as currently known on Ethereum chain,
303
+ /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output
304
+ /// value, as currently known on Ethereum chain,
305
+ /// - redeemerOutputScript The redeemer's length-prefixed output
306
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
307
+ /// redeemed BTC.
308
+ /// @dev Requirements:
309
+ /// - Wallet behind `walletPubKeyHash` must be live,
310
+ /// - `mainUtxo*` components must point to the recent main UTXO
311
+ /// of the given wallet, as currently known on the Ethereum chain,
312
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
313
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
314
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
315
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
316
+ /// used for only one pending request at the same time,
317
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
318
+ /// - Balance owner must make an allowance in the Bank that the Bridge
319
+ /// contract can spend the given `amount`.
320
+ function requestRedemption(
321
+ BridgeState.Storage storage self,
322
+ address balanceOwner,
323
+ uint64 amount,
324
+ bytes calldata redemptionData
325
+ ) external {
326
+ (
327
+ address redeemer,
328
+ bytes20 walletPubKeyHash,
329
+ bytes32 mainUtxoTxHash,
330
+ uint32 mainUtxoTxOutputIndex,
331
+ uint64 mainUtxoTxOutputValue,
332
+ bytes memory redeemerOutputScript
333
+ ) = abi.decode(
334
+ redemptionData,
335
+ (address, bytes20, bytes32, uint32, uint64, bytes)
336
+ );
337
+
338
+ requestRedemption(
339
+ self,
340
+ walletPubKeyHash,
341
+ BitcoinTx.UTXO(
342
+ mainUtxoTxHash,
343
+ mainUtxoTxOutputIndex,
344
+ mainUtxoTxOutputValue
345
+ ),
346
+ balanceOwner,
347
+ redeemer,
348
+ redeemerOutputScript,
349
+ amount
350
+ );
351
+ }
352
+
353
+ /// @notice Requests redemption of the given amount from the specified
354
+ /// wallet to the redeemer Bitcoin output script.
355
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
356
+ /// using Bitcoin HASH160 over the compressed ECDSA public key).
357
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
358
+ /// the Ethereum chain.
359
+ /// @param balanceOwner The address of the Bank balance owner whose balance
360
+ /// is getting redeemed.
361
+ /// @param redeemer The Ethereum address of the redeemer who will be able to
362
+ /// claim Bank balance if anything goes wrong during the redemption.
363
+ /// In the most basic case, when someone redeems their Bitcoin
364
+ /// balance from the Bank, `balanceOwner` is the same as `redeemer`.
365
+ /// However, when a Vault is redeeming part of its balance for some
366
+ /// redeemer address (for example, someone who has earlier deposited
367
+ /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is
368
+ /// the address for which the vault is redeeming its balance to.
369
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
370
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
371
+ /// redeemed BTC.
372
+ /// @param amount Requested amount in satoshi. This is also the Bank balance
373
+ /// that is taken from the `balanceOwner` upon request.
374
+ /// Once the request is handled, the actual amount of BTC locked
375
+ /// on the redeemer output script will be always lower than this value
376
+ /// since the treasury and Bitcoin transaction fees must be incurred.
377
+ /// The minimal amount satisfying the request can be computed as:
378
+ /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.
379
+ /// Fees values are taken at the moment of request creation.
380
+ /// @dev Requirements:
381
+ /// - Wallet behind `walletPubKeyHash` must be live,
382
+ /// - `mainUtxo` components must point to the recent main UTXO
383
+ /// of the given wallet, as currently known on the Ethereum chain,
384
+ /// - `redeemerOutputScript` must be a proper Bitcoin script,
385
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload,
386
+ /// - `amount` must be above or equal the `redemptionDustThreshold`,
387
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
388
+ /// used for only one pending request at the same time,
389
+ /// - Wallet must have enough Bitcoin balance to proceed the request,
390
+ /// - Balance owner must make an allowance in the Bank that the Bridge
391
+ /// contract can spend the given `amount`.
392
+ function requestRedemption(
393
+ BridgeState.Storage storage self,
394
+ bytes20 walletPubKeyHash,
395
+ BitcoinTx.UTXO memory mainUtxo,
396
+ address balanceOwner,
397
+ address redeemer,
398
+ bytes memory redeemerOutputScript,
399
+ uint64 amount
400
+ ) internal {
401
+ Wallets.Wallet storage wallet = self.registeredWallets[
402
+ walletPubKeyHash
403
+ ];
404
+
405
+ require(
406
+ wallet.state == Wallets.WalletState.Live,
407
+ "Wallet must be in Live state"
408
+ );
409
+
410
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
411
+ require(
412
+ mainUtxoHash != bytes32(0),
413
+ "No main UTXO for the given wallet"
414
+ );
415
+ require(
416
+ keccak256(
417
+ abi.encodePacked(
418
+ mainUtxo.txHash,
419
+ mainUtxo.txOutputIndex,
420
+ mainUtxo.txOutputValue
421
+ )
422
+ ) == mainUtxoHash,
423
+ "Invalid main UTXO data"
424
+ );
425
+
426
+ // Validate if redeemer output script is a correct standard type
427
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by using
428
+ // `BTCUtils.extractHashAt` on it. Such a function extracts the payload
429
+ // properly only from standard outputs so if it succeeds, we have a
430
+ // guarantee the redeemer output script is proper. The underlying way
431
+ // of validation is the same as in tBTC v1.
432
+ bytes memory redeemerOutputScriptPayload = redeemerOutputScript
433
+ .extractHashAt(0, redeemerOutputScript.length);
434
+
435
+ require(
436
+ redeemerOutputScriptPayload.length > 0,
437
+ "Redeemer output script must be a standard type"
438
+ );
439
+ // Check if the redeemer output script payload does not point to the
440
+ // wallet public key hash.
441
+ require(
442
+ redeemerOutputScriptPayload.length != 20 ||
443
+ walletPubKeyHash != redeemerOutputScriptPayload.slice20(0),
444
+ "Redeemer output script must not point to the wallet PKH"
445
+ );
446
+
447
+ require(
448
+ amount >= self.redemptionDustThreshold,
449
+ "Redemption amount too small"
450
+ );
451
+
452
+ // The redemption key is built on top of the wallet public key hash
453
+ // and redeemer output script pair. That means there can be only one
454
+ // request asking for redemption from the given wallet to the given
455
+ // BTC script at the same time.
456
+ uint256 redemptionKey = getRedemptionKey(
457
+ walletPubKeyHash,
458
+ redeemerOutputScript
459
+ );
460
+
461
+ // Check if given redemption key is not used by a pending redemption.
462
+ // There is no need to check for existence in `timedOutRedemptions`
463
+ // since the wallet's state is changed to other than Live after
464
+ // first time out is reported so making new requests is not possible.
465
+ // slither-disable-next-line incorrect-equality
466
+ require(
467
+ self.pendingRedemptions[redemptionKey].requestedAt == 0,
468
+ "There is a pending redemption request from this wallet to the same address"
469
+ );
470
+
471
+ // No need to check whether `amount - treasuryFee - txMaxFee > 0`
472
+ // since the `redemptionDustThreshold` should force that condition
473
+ // to be always true.
474
+ uint64 treasuryFee = self.redemptionTreasuryFeeDivisor > 0
475
+ ? amount / self.redemptionTreasuryFeeDivisor
476
+ : 0;
477
+ uint64 txMaxFee = self.redemptionTxMaxFee;
478
+
479
+ // The main wallet UTXO's value doesn't include all pending redemptions.
480
+ // To determine if the requested redemption can be performed by the
481
+ // wallet we need to subtract the total value of all pending redemptions
482
+ // from that wallet's main UTXO value. Given that the treasury fee is
483
+ // not redeemed from the wallet, we are subtracting it.
484
+ wallet.pendingRedemptionsValue += amount - treasuryFee;
485
+ require(
486
+ mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
487
+ "Insufficient wallet funds"
488
+ );
489
+
490
+ self.pendingRedemptions[redemptionKey] = RedemptionRequest(
491
+ redeemer,
492
+ amount,
493
+ treasuryFee,
494
+ txMaxFee,
495
+ /* solhint-disable-next-line not-rely-on-time */
496
+ uint32(block.timestamp)
497
+ );
498
+
499
+ // slither-disable-next-line reentrancy-events
500
+ emit RedemptionRequested(
501
+ walletPubKeyHash,
502
+ redeemerOutputScript,
503
+ redeemer,
504
+ amount,
505
+ treasuryFee,
506
+ txMaxFee
507
+ );
508
+
509
+ self.bank.transferBalanceFrom(balanceOwner, address(this), amount);
510
+ }
511
+
512
+ /// @notice Used by the wallet to prove the BTC redemption transaction
513
+ /// and to make the necessary bookkeeping. Redemption is only
514
+ /// accepted if it satisfies SPV proof.
515
+ ///
516
+ /// The function is performing Bank balance updates by burning
517
+ /// the total redeemed Bitcoin amount from Bridge balance and
518
+ /// transferring the treasury fee sum to the treasury address.
519
+ ///
520
+ /// It is possible to prove the given redemption only one time.
521
+ /// @param redemptionTx Bitcoin redemption transaction data.
522
+ /// @param redemptionProof Bitcoin redemption proof data.
523
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
524
+ /// the Ethereum chain.
525
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
526
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
527
+ /// performed the redemption transaction.
528
+ /// @dev Requirements:
529
+ /// - `redemptionTx` components must match the expected structure. See
530
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
531
+ /// correspond to appropriate Bitcoin transaction fields to produce
532
+ /// a provable transaction hash,
533
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
534
+ /// exactly 1 input that refers to the wallet's main UTXO. That
535
+ /// transaction should have 1..n outputs handling existing pending
536
+ /// redemption requests or pointing to reported timed out requests.
537
+ /// There can be also 1 optional output representing the
538
+ /// change and pointing back to the 20-byte wallet public key hash.
539
+ /// The change should be always present if the redeemed value sum
540
+ /// is lower than the total wallet's BTC balance,
541
+ /// - `redemptionProof` components must match the expected structure.
542
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
543
+ /// field must contain a valid number of block headers, not less
544
+ /// than the `txProofDifficultyFactor` contract constant,
545
+ /// - `mainUtxo` components must point to the recent main UTXO
546
+ /// of the given wallet, as currently known on the Ethereum chain.
547
+ /// Additionally, the recent main UTXO on Ethereum must be set,
548
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
549
+ /// as transaction single input.
550
+ /// Other remarks:
551
+ /// - Putting the change output as the first transaction output can
552
+ /// save some gas because the output processing loop begins each
553
+ /// iteration by checking whether the given output is the change
554
+ /// thus uses some gas for making the comparison. Once the change
555
+ /// is identified, that check is omitted in further iterations.
556
+ function submitRedemptionProof(
557
+ BridgeState.Storage storage self,
558
+ BitcoinTx.Info calldata redemptionTx,
559
+ BitcoinTx.Proof calldata redemptionProof,
560
+ BitcoinTx.UTXO calldata mainUtxo,
561
+ bytes20 walletPubKeyHash
562
+ ) external {
563
+ // Wallet state validation is performed in the `resolveRedeemingWallet`
564
+ // function.
565
+
566
+ // The actual transaction proof is performed here. After that point, we
567
+ // can assume the transaction happened on Bitcoin chain and has
568
+ // a sufficient number of confirmations as determined by
569
+ // `txProofDifficultyFactor` constant.
570
+ bytes32 redemptionTxHash = self.validateProof(
571
+ redemptionTx,
572
+ redemptionProof
573
+ );
574
+
575
+ Wallets.Wallet storage wallet = resolveRedeemingWallet(
576
+ self,
577
+ walletPubKeyHash,
578
+ mainUtxo
579
+ );
580
+
581
+ // Process the redemption transaction input. Specifically, check if it
582
+ // refers to the expected wallet's main UTXO.
583
+ OutboundTx.processWalletOutboundTxInput(
584
+ self,
585
+ redemptionTx.inputVector,
586
+ mainUtxo
587
+ );
588
+
589
+ // Process redemption transaction outputs to extract some info required
590
+ // for further processing.
591
+ RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
592
+ self,
593
+ redemptionTx.outputVector,
594
+ walletPubKeyHash
595
+ );
596
+
597
+ if (outputsInfo.changeValue > 0) {
598
+ // If the change value is grater than zero, it means the change
599
+ // output exists and can be used as new wallet's main UTXO.
600
+ wallet.mainUtxoHash = keccak256(
601
+ abi.encodePacked(
602
+ redemptionTxHash,
603
+ outputsInfo.changeIndex,
604
+ outputsInfo.changeValue
605
+ )
606
+ );
607
+ } else {
608
+ // If the change value is zero, it means the change output doesn't
609
+ // exists and no funds left on the wallet. Delete the main UTXO
610
+ // for that wallet to represent that state in a proper way.
611
+ delete wallet.mainUtxoHash;
612
+ }
613
+
614
+ wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
615
+
616
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
617
+
618
+ self.bank.decreaseBalance(outputsInfo.totalBurnableValue);
619
+ self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);
620
+ }
621
+
622
+ /// @notice Resolves redeeming wallet based on the provided wallet public
623
+ /// key hash. Validates the wallet state and current main UTXO, as
624
+ /// currently known on the Ethereum chain.
625
+ /// @param walletPubKeyHash public key hash of the wallet proving the sweep
626
+ /// Bitcoin transaction.
627
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
628
+ /// the Ethereum chain.
629
+ /// @return wallet Data of the sweeping wallet.
630
+ /// @dev Requirements:
631
+ /// - Sweeping wallet must be either in Live or MovingFunds state,
632
+ /// - Main UTXO of the redeeming wallet must exists in the storage,
633
+ /// - The passed `mainUTXO` parameter must be equal to the stored one.
634
+ function resolveRedeemingWallet(
635
+ BridgeState.Storage storage self,
636
+ bytes20 walletPubKeyHash,
637
+ BitcoinTx.UTXO calldata mainUtxo
638
+ ) internal view returns (Wallets.Wallet storage wallet) {
639
+ wallet = self.registeredWallets[walletPubKeyHash];
640
+
641
+ // Assert that main UTXO for passed wallet exists in storage.
642
+ bytes32 mainUtxoHash = wallet.mainUtxoHash;
643
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
644
+
645
+ // Assert that passed main UTXO parameter is the same as in storage and
646
+ // can be used for further processing.
647
+ require(
648
+ keccak256(
649
+ abi.encodePacked(
650
+ mainUtxo.txHash,
651
+ mainUtxo.txOutputIndex,
652
+ mainUtxo.txOutputValue
653
+ )
654
+ ) == mainUtxoHash,
655
+ "Invalid main UTXO data"
656
+ );
657
+
658
+ Wallets.WalletState walletState = wallet.state;
659
+ require(
660
+ walletState == Wallets.WalletState.Live ||
661
+ walletState == Wallets.WalletState.MovingFunds,
662
+ "Wallet must be in Live or MovingFunds state"
663
+ );
664
+ }
665
+
666
+ /// @notice Processes the Bitcoin redemption transaction output vector.
667
+ /// It extracts each output and tries to identify it as a pending
668
+ /// redemption request, reported timed out request, or change.
669
+ /// Reverts if one of the outputs cannot be recognized properly.
670
+ /// This function also marks each request as processed by removing
671
+ /// them from `pendingRedemptions` mapping.
672
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
673
+ /// vector. This function assumes vector's structure is valid so it
674
+ /// must be validated using e.g. `BTCUtils.validateVout` function
675
+ /// before it is passed here.
676
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
677
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
678
+ /// performed the redemption transaction.
679
+ /// @return info Outcomes of the processing.
680
+ function processRedemptionTxOutputs(
681
+ BridgeState.Storage storage self,
682
+ bytes memory redemptionTxOutputVector,
683
+ bytes20 walletPubKeyHash
684
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
685
+ // Determining the total number of redemption transaction outputs in
686
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
687
+ // docs for more details.
688
+ (
689
+ uint256 outputsCompactSizeUintLength,
690
+ uint256 outputsCount
691
+ ) = redemptionTxOutputVector.parseVarInt();
692
+
693
+ // To determine the first output starting index, we must jump over
694
+ // the compactSize uint which prepends the output vector. One byte
695
+ // must be added because `BtcUtils.parseVarInt` does not include
696
+ // compactSize uint tag in the returned length.
697
+ //
698
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
699
+ // returns `0`, so we jump over one byte of compactSize uint.
700
+ //
701
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
702
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
703
+ // tag byte included) so we need to jump over 1+2 bytes of
704
+ // compactSize uint.
705
+ //
706
+ // Please refer `BTCUtils` library and compactSize uint
707
+ // docs in `BitcoinTx` library for more details.
708
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
709
+
710
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
711
+ // scripts that can be used to lock the change. This is done upfront to
712
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
713
+ //
714
+ // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
715
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
716
+ // - 0x19: Byte length of the entire script
717
+ // - 0x76: OP_DUP
718
+ // - 0xa9: OP_HASH160
719
+ // - 0x14: Byte length of the public key hash
720
+ // - 0x88: OP_EQUALVERIFY
721
+ // - 0xac: OP_CHECKSIG
722
+ // which matches the P2PKH structure as per:
723
+ // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
724
+ bytes32 walletP2PKHScriptKeccak = keccak256(
725
+ abi.encodePacked(BitcoinTx.makeP2PKHScript(walletPubKeyHash))
726
+ );
727
+ // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
728
+ // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
729
+ // - 0x16: Byte length of the entire script
730
+ // - 0x00: OP_0
731
+ // - 0x14: Byte length of the public key hash
732
+ // which matches the P2WPKH structure as per:
733
+ // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
734
+ bytes32 walletP2WPKHScriptKeccak = keccak256(
735
+ abi.encodePacked(BitcoinTx.makeP2WPKHScript(walletPubKeyHash))
736
+ );
737
+
738
+ return
739
+ processRedemptionTxOutputs(
740
+ self,
741
+ redemptionTxOutputVector,
742
+ walletPubKeyHash,
743
+ RedemptionTxOutputsProcessingInfo(
744
+ outputStartingIndex,
745
+ outputsCount,
746
+ walletP2PKHScriptKeccak,
747
+ walletP2WPKHScriptKeccak
748
+ )
749
+ );
750
+ }
751
+
752
+ /// @notice Processes all outputs from the redemption transaction. Tries to
753
+ /// identify output as a change output, pending redemption request
754
+ /// or reported redemption. Reverts if one of the outputs cannot be
755
+ /// recognized properly. Marks each request as processed by removing
756
+ /// them from `pendingRedemptions` mapping.
757
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
758
+ /// vector. This function assumes vector's structure is valid so it
759
+ /// must be validated using e.g. `BTCUtils.validateVout` function
760
+ /// before it is passed here.
761
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
762
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
763
+ /// performed the redemption transaction.
764
+ /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output
765
+ /// starting index, the number of outputs and possible wallet change
766
+ /// P2PKH and P2WPKH scripts.
767
+ function processRedemptionTxOutputs(
768
+ BridgeState.Storage storage self,
769
+ bytes memory redemptionTxOutputVector,
770
+ bytes20 walletPubKeyHash,
771
+ RedemptionTxOutputsProcessingInfo memory processInfo
772
+ ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {
773
+ // Helper flag indicating whether there was at least one redemption
774
+ // output present (redemption must be either pending or reported as
775
+ // timed out).
776
+ bool redemptionPresent = false;
777
+
778
+ // Outputs processing loop.
779
+ for (uint256 i = 0; i < processInfo.outputsCount; i++) {
780
+ uint256 outputLength = redemptionTxOutputVector
781
+ .determineOutputLengthAt(processInfo.outputStartingIndex);
782
+
783
+ // Extract the value from given output.
784
+ uint64 outputValue = redemptionTxOutputVector.extractValueAt(
785
+ processInfo.outputStartingIndex
786
+ );
787
+
788
+ // The output consists of an 8-byte value and a variable length
789
+ // script. To hash that script we slice the output starting from
790
+ // 9th byte until the end.
791
+ uint256 scriptLength = outputLength - 8;
792
+ uint256 outputScriptStart = processInfo.outputStartingIndex + 8;
793
+
794
+ bytes32 outputScriptHash;
795
+ /* solhint-disable-next-line no-inline-assembly */
796
+ assembly {
797
+ // The first argument to assembly keccak256 is the pointer.
798
+ // We point to `redemptionTxOutputVector` but at the position
799
+ // indicated by `outputScriptStart`. To load that position, we
800
+ // need to call `add(outputScriptStart, 32)` because
801
+ // `outputScriptStart` has 32 bytes.
802
+ outputScriptHash := keccak256(
803
+ add(redemptionTxOutputVector, add(outputScriptStart, 32)),
804
+ scriptLength
805
+ )
806
+ }
807
+
808
+ if (
809
+ resultInfo.changeValue == 0 &&
810
+ (outputScriptHash == processInfo.walletP2PKHScriptKeccak ||
811
+ outputScriptHash == processInfo.walletP2WPKHScriptKeccak) &&
812
+ outputValue > 0
813
+ ) {
814
+ // If we entered here, that means the change output with a
815
+ // proper non-zero value was found.
816
+ resultInfo.changeIndex = uint32(i);
817
+ resultInfo.changeValue = outputValue;
818
+ } else {
819
+ // If we entered here, that the means the given output is
820
+ // supposed to represent a redemption.
821
+ (
822
+ uint64 burnableValue,
823
+ uint64 treasuryFee
824
+ ) = processNonChangeRedemptionTxOutput(
825
+ self,
826
+ _getRedemptionKey(walletPubKeyHash, outputScriptHash),
827
+ outputValue
828
+ );
829
+ resultInfo.totalBurnableValue += burnableValue;
830
+ resultInfo.totalTreasuryFee += treasuryFee;
831
+ redemptionPresent = true;
832
+ }
833
+
834
+ // Make the `outputStartingIndex` pointing to the next output by
835
+ // increasing it by current output's length.
836
+ processInfo.outputStartingIndex += outputLength;
837
+ }
838
+
839
+ // Protect against the cases when there is only a single change output
840
+ // referring back to the wallet PKH and just burning main UTXO value
841
+ // for transaction fees.
842
+ require(
843
+ redemptionPresent,
844
+ "Redemption transaction must process at least one redemption"
845
+ );
846
+ }
847
+
848
+ /// @notice Processes a single redemption transaction output. Tries to
849
+ /// identify output as a pending redemption request or reported
850
+ /// redemption timeout. Output script passed to this function must
851
+ /// not be the change output. Such output needs to be identified
852
+ /// separately before calling this function.
853
+ /// Reverts if output is neither requested pending redemption nor
854
+ /// requested and reported timed-out redemption.
855
+ /// This function also marks each pending request as processed by
856
+ /// removing them from `pendingRedemptions` mapping.
857
+ /// @param redemptionKey Redemption key of the output being processed.
858
+ /// @param outputValue Value of the output being processed.
859
+ /// @return burnableValue The value burnable as a result of processing this
860
+ /// single redemption output. This value needs to be summed up with
861
+ /// burnable values of all other outputs to evaluate total burnable
862
+ /// value for the entire redemption transaction. This value is 0
863
+ /// for a timed-out redemption request.
864
+ /// @return treasuryFee The treasury fee from this single redemption output.
865
+ /// This value needs to be summed up with treasury fees of all other
866
+ /// outputs to evaluate the total treasury fee for the entire
867
+ /// redemption transaction. This value is 0 for a timed-out
868
+ /// redemption request.
869
+ /// @dev Requirements:
870
+ /// - This function should be called only if the given output
871
+ /// represents redemption. It must not be the change output.
872
+ function processNonChangeRedemptionTxOutput(
873
+ BridgeState.Storage storage self,
874
+ uint256 redemptionKey,
875
+ uint64 outputValue
876
+ ) internal returns (uint64 burnableValue, uint64 treasuryFee) {
877
+ if (self.pendingRedemptions[redemptionKey].requestedAt != 0) {
878
+ // If we entered here, that means the output was identified
879
+ // as a pending redemption request.
880
+ RedemptionRequest storage request = self.pendingRedemptions[
881
+ redemptionKey
882
+ ];
883
+ // Compute the request's redeemable amount as the requested
884
+ // amount reduced by the treasury fee. The request's
885
+ // minimal amount is then the redeemable amount reduced by
886
+ // the maximum transaction fee.
887
+ uint64 redeemableAmount = request.requestedAmount -
888
+ request.treasuryFee;
889
+ // Output value must fit between the request's redeemable
890
+ // and minimal amounts to be deemed valid.
891
+ require(
892
+ redeemableAmount - request.txMaxFee <= outputValue &&
893
+ outputValue <= redeemableAmount,
894
+ "Output value is not within the acceptable range of the pending request"
895
+ );
896
+ // Add the redeemable amount to the total burnable value
897
+ // the Bridge will use to decrease its balance in the Bank.
898
+ burnableValue = redeemableAmount;
899
+ // Add the request's treasury fee to the total treasury fee
900
+ // value the Bridge will transfer to the treasury.
901
+ treasuryFee = request.treasuryFee;
902
+ // Request was properly handled so remove its redemption
903
+ // key from the mapping to make it reusable for further
904
+ // requests.
905
+ delete self.pendingRedemptions[redemptionKey];
906
+ } else {
907
+ // If we entered here, the output is not a redemption
908
+ // request but there is still a chance the given output is
909
+ // related to a reported timed out redemption request.
910
+ // If so, check if the output value matches the request
911
+ // amount to confirm this is an overdue request fulfillment
912
+ // then bypass this output and process the subsequent
913
+ // ones. That also means the wallet was already punished
914
+ // for the inactivity. Otherwise, just revert.
915
+ RedemptionRequest storage request = self.timedOutRedemptions[
916
+ redemptionKey
917
+ ];
918
+
919
+ require(
920
+ request.requestedAt != 0,
921
+ "Output is a non-requested redemption"
922
+ );
923
+
924
+ uint64 redeemableAmount = request.requestedAmount -
925
+ request.treasuryFee;
926
+
927
+ require(
928
+ redeemableAmount - request.txMaxFee <= outputValue &&
929
+ outputValue <= redeemableAmount,
930
+ "Output value is not within the acceptable range of the timed out request"
931
+ );
932
+ }
933
+ }
934
+
935
+ /// @notice Notifies that there is a pending redemption request associated
936
+ /// with the given wallet, that has timed out. The redemption
937
+ /// request is identified by the key built as
938
+ /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.
939
+ /// The results of calling this function:
940
+ /// - the pending redemptions value for the wallet will be decreased
941
+ /// by the requested amount (minus treasury fee),
942
+ /// - the tokens taken from the redeemer on redemption request will
943
+ /// be returned to the redeemer,
944
+ /// - the request will be moved from pending redemptions to
945
+ /// timed-out redemptions,
946
+ /// - if the state of the wallet is `Live` or `MovingFunds`, the
947
+ /// wallet operators will be slashed and the notifier will be
948
+ /// rewarded,
949
+ /// - if the state of wallet is `Live`, the wallet will be closed or
950
+ /// marked as `MovingFunds` (depending on the presence or absence
951
+ /// of the wallet's main UTXO) and the wallet will no longer be
952
+ /// marked as the active wallet (if it was marked as such).
953
+ /// @param walletPubKeyHash 20-byte public key hash of the wallet.
954
+ /// @param walletMembersIDs Identifiers of the wallet signing group members.
955
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
956
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH).
957
+ /// @dev Requirements:
958
+ /// - The wallet must be in the Live or MovingFunds or Terminated state,
959
+ /// - The redemption request identified by `walletPubKeyHash` and
960
+ /// `redeemerOutputScript` must exist,
961
+ /// - The expression `keccak256(abi.encode(walletMembersIDs))` must
962
+ /// be exactly the same as the hash stored under `membersIdsHash`
963
+ /// for the given `walletID`. Those IDs are not directly stored
964
+ /// in the contract for gas efficiency purposes but they can be
965
+ /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`
966
+ /// events of the `WalletRegistry` contract,
967
+ /// - The amount of time defined by `redemptionTimeout` must have
968
+ /// passed since the redemption was requested (the request must be
969
+ /// timed-out).
970
+ function notifyRedemptionTimeout(
971
+ BridgeState.Storage storage self,
972
+ bytes20 walletPubKeyHash,
973
+ uint32[] calldata walletMembersIDs,
974
+ bytes calldata redeemerOutputScript
975
+ ) external {
976
+ // Wallet state is validated in `notifyWalletRedemptionTimeout`.
977
+ uint256 redemptionKey = getRedemptionKey(
978
+ walletPubKeyHash,
979
+ redeemerOutputScript
980
+ );
981
+ Redemption.RedemptionRequest memory request = self.pendingRedemptions[
982
+ redemptionKey
983
+ ];
984
+
985
+ require(request.requestedAt > 0, "Redemption request does not exist");
986
+ require(
987
+ /* solhint-disable-next-line not-rely-on-time */
988
+ request.requestedAt + self.redemptionTimeout < block.timestamp,
989
+ "Redemption request has not timed out"
990
+ );
991
+
992
+ // Update the wallet's pending redemptions value
993
+ Wallets.Wallet storage wallet = self.registeredWallets[
994
+ walletPubKeyHash
995
+ ];
996
+ wallet.pendingRedemptionsValue -=
997
+ request.requestedAmount -
998
+ request.treasuryFee;
999
+
1000
+ // It is worth noting that there is no need to check if
1001
+ // `timedOutRedemption` mapping already contains the given redemption
1002
+ // key. There is no possibility to re-use a key of a reported timed-out
1003
+ // redemption because the wallet responsible for causing the timeout is
1004
+ // moved to a state that prevents it to receive new redemption requests.
1005
+
1006
+ // Propagate timeout consequences to the wallet
1007
+ self.notifyWalletRedemptionTimeout(walletPubKeyHash, walletMembersIDs);
1008
+
1009
+ // Move the redemption from pending redemptions to timed-out redemptions
1010
+ self.timedOutRedemptions[redemptionKey] = request;
1011
+ delete self.pendingRedemptions[redemptionKey];
1012
+
1013
+ // slither-disable-next-line reentrancy-events
1014
+ emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
1015
+
1016
+ // Return the requested amount of tokens to the redeemer
1017
+ self.bank.transferBalance(request.redeemer, request.requestedAmount);
1018
+ }
1019
+
1020
+ /// @notice Calculate redemption key without allocations.
1021
+ /// @param walletPubKeyHash the pubkey hash of the wallet.
1022
+ /// @param script the output script of the redemption.
1023
+ /// @return The key = keccak256(keccak256(script) | walletPubKeyHash).
1024
+ function getRedemptionKey(bytes20 walletPubKeyHash, bytes memory script)
1025
+ internal
1026
+ pure
1027
+ returns (uint256)
1028
+ {
1029
+ bytes32 scriptHash = keccak256(script);
1030
+ uint256 key;
1031
+ /* solhint-disable-next-line no-inline-assembly */
1032
+ assembly {
1033
+ mstore(0, scriptHash)
1034
+ mstore(32, walletPubKeyHash)
1035
+ key := keccak256(0, 52)
1036
+ }
1037
+ return key;
1038
+ }
1039
+
1040
+ /// @notice Finish calculating redemption key without allocations.
1041
+ /// @param walletPubKeyHash the pubkey hash of the wallet.
1042
+ /// @param scriptHash the output script hash of the redemption.
1043
+ /// @return The key = keccak256(scriptHash | walletPubKeyHash).
1044
+ function _getRedemptionKey(bytes20 walletPubKeyHash, bytes32 scriptHash)
1045
+ internal
1046
+ pure
1047
+ returns (uint256)
1048
+ {
1049
+ uint256 key;
1050
+ /* solhint-disable-next-line no-inline-assembly */
1051
+ assembly {
1052
+ mstore(0, scriptHash)
1053
+ mstore(32, walletPubKeyHash)
1054
+ key := keccak256(0, 52)
1055
+ }
1056
+ return key;
1057
+ }
1058
+ }