@keep-network/tbtc-v2 0.1.1-dev.13 → 0.1.1-dev.14

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.
@@ -93,7 +93,7 @@ contract Bridge is Ownable {
93
93
  }
94
94
 
95
95
  /// @notice Represents tBTC deposit data.
96
- struct DepositInfo {
96
+ struct DepositRequest {
97
97
  // Ethereum depositor address.
98
98
  address depositor;
99
99
  // Deposit amount in satoshi.
@@ -109,18 +109,113 @@ contract Bridge is Ownable {
109
109
  uint32 sweptAt;
110
110
  }
111
111
 
112
+ /// @notice Represents a redemption request.
113
+ struct RedemptionRequest {
114
+ // ETH address of the redeemer who created the request.
115
+ address redeemer;
116
+ // Requested TBTC amount in satoshi.
117
+ uint64 requestedAmount;
118
+ // Treasury TBTC fee in satoshi at the moment of request creation.
119
+ uint64 treasuryFee;
120
+ // Transaction maximum BTC fee in satoshi at the moment of request
121
+ // creation.
122
+ uint64 txMaxFee;
123
+ // UNIX timestamp the request was created at.
124
+ uint32 requestedAt;
125
+ }
126
+
127
+ /// @notice Represents an outcome of the redemption Bitcoin transaction
128
+ /// outputs processing.
129
+ struct RedemptionTxOutputsInfo {
130
+ // Total TBTC value in satoshi that should be burned by the Bridge.
131
+ // It includes the total amount of all BTC redeemed in the transaction
132
+ // and the fee paid to BTC miners for the redemption transaction.
133
+ uint64 totalBurnableValue;
134
+ // Total TBTC value in satoshi that should be transferred to
135
+ // the treasury. It is a sum of all treasury fees paid by all
136
+ // redeemers included in the redemption transaction.
137
+ uint64 totalTreasuryFee;
138
+ // Index of the change output. The change output becomes
139
+ // the new main wallet's UTXO.
140
+ uint32 changeIndex;
141
+ // Value in satoshi of the change output.
142
+ uint64 changeValue;
143
+ }
144
+
145
+ /// @notice Represents wallet state:
146
+ enum WalletState {
147
+ /// @dev The wallet is unknown to the Bridge.
148
+ Unknown,
149
+ /// @dev The wallet can sweep deposits and accept redemption requests.
150
+ Active,
151
+ /// @dev The wallet was deemed unhealthy and is expected to move their
152
+ /// outstanding funds to another wallet. The wallet can still
153
+ /// fulfill their pending redemption requests although new
154
+ /// redemption requests and new deposit reveals are not accepted.
155
+ MovingFunds,
156
+ /// @dev The wallet moved or redeemed all their funds and cannot
157
+ /// perform any action.
158
+ Closed,
159
+ /// @dev The wallet committed a fraud that was reported. The wallet is
160
+ /// blocked and can not perform any actions in the Bridge.
161
+ /// Off-chain coordination with the wallet operators is needed to
162
+ /// recover funds.
163
+ Terminated
164
+ }
165
+
166
+ /// @notice Holds information about a wallet.
167
+ struct Wallet {
168
+ // Current state of the wallet.
169
+ WalletState state;
170
+ // The total redeemable value of pending redemption requests targeting
171
+ // that wallet.
172
+ uint64 pendingRedemptionsValue;
173
+ }
174
+
112
175
  /// @notice The number of confirmations on the Bitcoin chain required to
113
176
  /// successfully evaluate an SPV proof.
114
177
  uint256 public immutable txProofDifficultyFactor;
115
178
 
116
- // TODO: Revisit whether it should be updatable or not.
179
+ /// TODO: Revisit whether it should be governable or not.
117
180
  /// @notice Address of the Bank this Bridge belongs to.
118
181
  Bank public immutable bank;
119
182
 
120
- /// TODO: Make it updatable.
183
+ /// TODO: Make it governable.
121
184
  /// @notice Handle to the Bitcoin relay.
122
185
  IRelay public immutable relay;
123
186
 
187
+ /// TODO: Revisit whether it should be governable or not.
188
+ /// @notice Address where the redemptions treasury fees will be sent to.
189
+ /// Treasury takes part in the operators rewarding process.
190
+ address public immutable treasury;
191
+
192
+ /// TODO: Make it governable.
193
+ /// @notice The minimal amount that can be requested for redemption.
194
+ /// Value of this parameter should be always bigger than the sum
195
+ /// of `redemptionTreasuryFee` and `redemptionTxMaxFee` to make
196
+ /// redemptions possible.
197
+ uint64 public redemptionDustThreshold;
198
+
199
+ /// TODO: Make it governable.
200
+ /// @notice Amount of TBTC that is taken from each redemption request and
201
+ /// transferred to the treasury upon successful request finalization.
202
+ uint64 public redemptionTreasuryFee;
203
+
204
+ /// TODO: Make it governable.
205
+ /// @notice Maximum amount of BTC transaction fee that can be incurred by
206
+ /// each redemption request being part of the given redemption
207
+ /// transaction. If the maximum BTC transaction fee is exceeded, such
208
+ /// transaction is considered a fraud.
209
+ uint64 public redemptionTxMaxFee;
210
+
211
+ /// TODO: Make it governable.
212
+ /// @notice Time after which the redemption request can be reported as
213
+ /// timed out. It is counted from the moment when the redemption
214
+ /// request was created via `requestRedemption` call. Reported
215
+ /// timed out requests are cancelled and locked TBTC is returned
216
+ /// to the redeemer in full amount.
217
+ uint256 public redemptionTimeout;
218
+
124
219
  /// @notice Indicates if the vault with the given address is trusted or not.
125
220
  /// Depositors can route their revealed deposits only to trusted
126
221
  /// vaults and have trusted vaults notified about new deposits as
@@ -132,18 +227,66 @@ contract Bridge is Ownable {
132
227
 
133
228
  /// @notice Collection of all revealed deposits indexed by
134
229
  /// keccak256(fundingTxHash | fundingOutputIndex).
135
- /// The fundingTxHash is LE bytes32 and fundingOutputIndex an uint32.
136
- /// This mapping may contain valid and invalid deposits and the
137
- /// wallet is responsible for validating them before attempting to
138
- /// execute a sweep.
139
- mapping(uint256 => DepositInfo) public deposits;
140
-
141
- /// @notice Maps the wallet public key hash (computed using HASH160 opcode)
142
- /// to the latest wallet's main UTXO computed as
230
+ /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)
231
+ /// and fundingOutputIndex an uint32. This mapping may contain valid
232
+ /// and invalid deposits and the wallet is responsible for
233
+ /// validating them before attempting to execute a sweep.
234
+ mapping(uint256 => DepositRequest) public deposits;
235
+
236
+ /// @notice Maps the 20-byte wallet public key hash (computed using
237
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to
238
+ /// the latest wallet's main UTXO computed as
143
239
  /// keccak256(txHash | txOutputIndex | txOutputValue). The `tx`
144
240
  /// prefix refers to the transaction which created that main UTXO.
241
+ /// The txHash is bytes32 (ordered as in Bitcoin internally),
242
+ /// txOutputIndex an uint32, and txOutputValue an uint64 value.
145
243
  mapping(bytes20 => bytes32) public mainUtxos;
146
244
 
245
+ /// @notice Collection of all pending redemption requests indexed by
246
+ /// redemption key built as
247
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
248
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
249
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
250
+ /// public key) and redeemerOutputScript is a Bitcoin script
251
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
252
+ /// redeemed BTC as requested by the redeemer. Requests are added
253
+ /// to this mapping by the `requestRedemption` method (duplicates
254
+ /// not allowed) and are removed by one of the following methods:
255
+ /// - `submitRedemptionProof` in case the request was handled
256
+ /// successfully
257
+ /// - `notifyRedemptionTimeout` in case the request was reported
258
+ /// to be timed out
259
+ /// - `submitRedemptionFraudProof` in case the request was handled
260
+ /// in an fraudulent way amount-wise.
261
+ mapping(uint256 => RedemptionRequest) public pendingRedemptions;
262
+
263
+ /// @notice Collection of all timed out redemptions requests indexed by
264
+ /// redemption key built as
265
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
266
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
267
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
268
+ /// public key) and redeemerOutputScript is the Bitcoin script
269
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
270
+ /// out request. Timed out requests are stored in this mapping to
271
+ /// avoid slashing the wallets multiple times for the same timeout.
272
+ /// Only one method can add to this mapping:
273
+ /// - `notifyRedemptionTimeout` which puts the redemption key
274
+ /// to this mapping basing on a timed out request stored
275
+ /// previously in `pendingRedemptions` mapping.
276
+ ///
277
+ // TODO: Remove that Slither disable once this variable is used.
278
+ // slither-disable-next-line uninitialized-state
279
+ mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
280
+
281
+ /// @notice Maps the 20-byte wallet public key hash (computed using
282
+ /// Bitcoin HASH160 over the compressed ECDSA public key) to the
283
+ /// basic wallet information like state and pending
284
+ /// redemptions value.
285
+ ///
286
+ // TODO: Remove that Slither disable once this variable is used.
287
+ // slither-disable-next-line uninitialized-state
288
+ mapping(bytes20 => Wallet) public wallets;
289
+
147
290
  event VaultStatusUpdated(address indexed vault, bool isTrusted);
148
291
 
149
292
  event DepositRevealed(
@@ -160,9 +303,24 @@ contract Bridge is Ownable {
160
303
 
161
304
  event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);
162
305
 
306
+ event RedemptionRequested(
307
+ bytes20 walletPubKeyHash,
308
+ bytes redeemerOutputScript,
309
+ address redeemer,
310
+ uint64 requestedAmount,
311
+ uint64 treasuryFee,
312
+ uint64 txMaxFee
313
+ );
314
+
315
+ event RedemptionsCompleted(
316
+ bytes20 walletPubKeyHash,
317
+ bytes32 redemptionTxHash
318
+ );
319
+
163
320
  constructor(
164
321
  address _bank,
165
322
  address _relay,
323
+ address _treasury,
166
324
  uint256 _txProofDifficultyFactor
167
325
  ) {
168
326
  require(_bank != address(0), "Bank address cannot be zero");
@@ -171,9 +329,21 @@ contract Bridge is Ownable {
171
329
  require(_relay != address(0), "Relay address cannot be zero");
172
330
  relay = IRelay(_relay);
173
331
 
332
+ require(_treasury != address(0), "Treasury address cannot be zero");
333
+ treasury = _treasury;
334
+
174
335
  txProofDifficultyFactor = _txProofDifficultyFactor;
336
+
337
+ // TODO: Revisit initial values.
338
+ redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
339
+ redemptionTreasuryFee = 100000; // 100000 satoshi
340
+ redemptionTxMaxFee = 1000; // 1000 satoshi
341
+ redemptionTimeout = 172800; // 48 hours
175
342
  }
176
343
 
344
+ // TODO: Add function `onNewWalletCreated` according to discussion:
345
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r809885230
346
+
177
347
  /// @notice Allows the Governance to mark the given vault address as trusted
178
348
  /// or no longer trusted. Vaults are not trusted by default.
179
349
  /// Trusted vault must meet the following criteria:
@@ -234,6 +404,9 @@ contract Bridge is Ownable {
234
404
  "Vault is not trusted"
235
405
  );
236
406
 
407
+ // TODO: Validate if `walletPubKeyHash` is a known and active wallet.
408
+ // TODO: Should we enforce a specific locktime at contract level?
409
+
237
410
  bytes memory expectedScript =
238
411
  abi.encodePacked(
239
412
  hex"14", // Byte length of depositor Ethereum address.
@@ -308,7 +481,7 @@ contract Bridge is Ownable {
308
481
  )
309
482
  .hash256View();
310
483
 
311
- DepositInfo storage deposit =
484
+ DepositRequest storage deposit =
312
485
  deposits[
313
486
  uint256(
314
487
  keccak256(
@@ -392,7 +565,7 @@ contract Bridge is Ownable {
392
565
  // can assume the transaction happened on Bitcoin chain and has
393
566
  // a sufficient number of confirmations as determined by
394
567
  // `txProofDifficultyFactor` constant.
395
- bytes32 sweepTxHash = validateSweepTxProof(sweepTx, sweepProof);
568
+ bytes32 sweepTxHash = validateBitcoinTxProof(sweepTx, sweepProof);
396
569
 
397
570
  // Process sweep transaction output and extract its target wallet
398
571
  // public key hash and value.
@@ -462,40 +635,40 @@ contract Bridge is Ownable {
462
635
  // TODO: Handle deposits having `vault` set.
463
636
  }
464
637
 
465
- /// @notice Validates the SPV proof of the Bitcoin sweep transaction.
638
+ /// @notice Validates the SPV proof of the Bitcoin transaction.
466
639
  /// Reverts in case the validation or proof verification fail.
467
- /// @param sweepTx Bitcoin sweep transaction data
468
- /// @param sweepProof Bitcoin sweep proof data
469
- /// @return sweepTxHash Proven 32-byte sweep transaction hash.
470
- function validateSweepTxProof(
471
- BitcoinTx.Info calldata sweepTx,
472
- BitcoinTx.Proof calldata sweepProof
473
- ) internal view returns (bytes32 sweepTxHash) {
640
+ /// @param txInfo Bitcoin transaction data
641
+ /// @param proof Bitcoin proof data
642
+ /// @return txHash Proven 32-byte transaction hash.
643
+ function validateBitcoinTxProof(
644
+ BitcoinTx.Info calldata txInfo,
645
+ BitcoinTx.Proof calldata proof
646
+ ) internal view returns (bytes32 txHash) {
474
647
  require(
475
- sweepTx.inputVector.validateVin(),
648
+ txInfo.inputVector.validateVin(),
476
649
  "Invalid input vector provided"
477
650
  );
478
651
  require(
479
- sweepTx.outputVector.validateVout(),
652
+ txInfo.outputVector.validateVout(),
480
653
  "Invalid output vector provided"
481
654
  );
482
655
 
483
- sweepTxHash = abi
656
+ txHash = abi
484
657
  .encodePacked(
485
- sweepTx
658
+ txInfo
486
659
  .version,
487
- sweepTx
660
+ txInfo
488
661
  .inputVector,
489
- sweepTx
662
+ txInfo
490
663
  .outputVector,
491
- sweepTx
664
+ txInfo
492
665
  .locktime
493
666
  )
494
667
  .hash256View();
495
668
 
496
- checkProofFromTxHash(sweepTxHash, sweepProof);
669
+ checkProofFromTxHash(txHash, proof);
497
670
 
498
- return sweepTxHash;
671
+ return txHash;
499
672
  }
500
673
 
501
674
  /// @notice Checks the given Bitcoin transaction hash against the SPV proof.
@@ -686,18 +859,18 @@ contract Bridge is Ownable {
686
859
 
687
860
  // Inputs processing loop.
688
861
  for (uint256 i = 0; i < inputsCount; i++) {
689
- // Check if we are at the end of the input vector.
690
- if (inputStartingIndex >= sweepTxInputVector.length) {
691
- break;
692
- }
693
-
694
- (bytes32 inputTxHash, uint32 inputTxIndex, uint256 inputLength) =
695
- parseTxInputAt(sweepTxInputVector, inputStartingIndex);
862
+ (
863
+ bytes32 outpointTxHash,
864
+ uint32 outpointIndex,
865
+ uint256 inputLength
866
+ ) = parseTxInputAt(sweepTxInputVector, inputStartingIndex);
696
867
 
697
- DepositInfo storage deposit =
868
+ DepositRequest storage deposit =
698
869
  deposits[
699
870
  uint256(
700
- keccak256(abi.encodePacked(inputTxHash, inputTxIndex))
871
+ keccak256(
872
+ abi.encodePacked(outpointTxHash, outpointIndex)
873
+ )
701
874
  )
702
875
  ];
703
876
 
@@ -726,7 +899,7 @@ contract Bridge is Ownable {
726
899
  processedDepositsCount++;
727
900
  } else if (
728
901
  mainUtxoExpected != mainUtxoFound &&
729
- mainUtxo.txHash == inputTxHash
902
+ mainUtxo.txHash == outpointTxHash
730
903
  ) {
731
904
  // If we entered here, that means the input was identified as
732
905
  // the expected main UTXO.
@@ -763,9 +936,9 @@ contract Bridge is Ownable {
763
936
  /// @notice Parses a Bitcoin transaction input starting at the given index.
764
937
  /// @param inputVector Bitcoin transaction input vector
765
938
  /// @param inputStartingIndex Index the given input starts at
766
- /// @return inputTxHash 32-byte hash of the Bitcoin transaction which is
939
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
767
940
  /// pointed in the given input's outpoint.
768
- /// @return inputTxIndex 4-byte index of the Bitcoin transaction output
941
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
769
942
  /// which is pointed in the given input's outpoint.
770
943
  /// @return inputLength Byte length of the given input.
771
944
  /// @dev This function assumes vector's structure is valid so it must be
@@ -778,26 +951,651 @@ contract Bridge is Ownable {
778
951
  internal
779
952
  pure
780
953
  returns (
781
- bytes32 inputTxHash,
782
- uint32 inputTxIndex,
954
+ bytes32 outpointTxHash,
955
+ uint32 outpointIndex,
783
956
  uint256 inputLength
784
957
  )
785
958
  {
786
- inputTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
959
+ outpointTxHash = inputVector.extractInputTxIdLeAt(inputStartingIndex);
787
960
 
788
- inputTxIndex = BTCUtils.reverseUint32(
961
+ outpointIndex = BTCUtils.reverseUint32(
789
962
  uint32(inputVector.extractTxIndexLeAt(inputStartingIndex))
790
963
  );
791
964
 
792
965
  inputLength = inputVector.determineInputLengthAt(inputStartingIndex);
793
966
 
794
- return (inputTxHash, inputTxIndex, inputLength);
967
+ return (outpointTxHash, outpointIndex, inputLength);
968
+ }
969
+
970
+ /// @notice Requests redemption of the given amount from the specified
971
+ /// wallet to the redeemer Bitcoin output script.
972
+ /// @param walletPubKeyHash The 20-byte wallet public key hash (computed
973
+ // using Bitcoin HASH160 over the compressed ECDSA public key)
974
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
975
+ /// the Ethereum chain
976
+ /// @param redeemerOutputScript The redeemer's length-prefixed output
977
+ /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
978
+ /// redeemed BTC
979
+ /// @param amount Requested amount in satoshi. This is also the TBTC amount
980
+ /// that is taken from redeemer's balance in the Bank upon request.
981
+ /// Once the request is handled, the actual amount of BTC locked
982
+ /// on the redeemer output script will be always lower than this value
983
+ /// since the treasury and Bitcoin transaction fees must be incurred.
984
+ /// The minimal amount satisfying the request can be computed as:
985
+ /// `amount - redemptionTreasuryFee - redemptionTxMaxFee`.
986
+ /// Fees values are taken at the moment of request creation.
987
+ /// @dev Requirements:
988
+ /// - Wallet behind `walletPubKeyHash` must be active
989
+ /// - `mainUtxo` components must point to the recent main UTXO
990
+ /// of the given wallet, as currently known on the Ethereum chain.
991
+ /// - `redeemerOutputScript` must be a proper Bitcoin script
992
+ /// - `redeemerOutputScript` cannot have wallet PKH as payload
993
+ /// - `amount` must be above or equal the `redemptionDustThreshold`
994
+ /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be
995
+ /// used for only one pending request at the same time
996
+ /// - Wallet must have enough Bitcoin balance to proceed the request
997
+ /// - Redeemer must make an allowance in the Bank that the Bridge
998
+ /// contract can spend the given `amount`.
999
+ function requestRedemption(
1000
+ bytes20 walletPubKeyHash,
1001
+ BitcoinTx.UTXO calldata mainUtxo,
1002
+ bytes calldata redeemerOutputScript,
1003
+ uint64 amount
1004
+ ) external {
1005
+ require(
1006
+ wallets[walletPubKeyHash].state == WalletState.Active,
1007
+ "Wallet must be in Active state"
1008
+ );
1009
+
1010
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1011
+ require(
1012
+ mainUtxoHash != bytes32(0),
1013
+ "No main UTXO for the given wallet"
1014
+ );
1015
+ require(
1016
+ keccak256(
1017
+ abi.encodePacked(
1018
+ mainUtxo.txHash,
1019
+ mainUtxo.txOutputIndex,
1020
+ mainUtxo.txOutputValue
1021
+ )
1022
+ ) == mainUtxoHash,
1023
+ "Invalid main UTXO data"
1024
+ );
1025
+
1026
+ // TODO: Confirm if `walletPubKeyHash` should be validated by checking
1027
+ // if it is the oldest one who can handle the request. This will
1028
+ // be suggested by the dApp but may not be respected by users who
1029
+ // interact directly with the contract. Do we need to enforce it
1030
+ // here? One option is not to enforce it, to save on gas, but if
1031
+ // we see this rule is not respected, upgrade Bridge contract to
1032
+ // require it.
1033
+
1034
+ // Validate if redeemer output script is a correct standard type
1035
+ // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
1036
+ // output with 0 as value and using `BTCUtils.extractHash` on it. Such
1037
+ // a function extracts the payload properly only from standard outputs
1038
+ // so if it succeeds, we have a guarantee the redeemer output script
1039
+ // is proper. Worth to note `extractHash` ignores the value at all
1040
+ // so this is why we can use 0 safely. This way of validation is the
1041
+ // same as in tBTC v1.
1042
+ bytes memory redeemerOutputScriptPayload =
1043
+ abi.encodePacked(bytes8(0), redeemerOutputScript).extractHash();
1044
+ require(
1045
+ redeemerOutputScriptPayload.length > 0,
1046
+ "Redeemer output script must be a standard type"
1047
+ );
1048
+ // Check if the redeemer output script payload does not point to the
1049
+ // wallet public key hash.
1050
+ require(
1051
+ keccak256(abi.encodePacked(walletPubKeyHash)) !=
1052
+ keccak256(redeemerOutputScriptPayload),
1053
+ "Redeemer output script must not point to the wallet PKH"
1054
+ );
1055
+
1056
+ require(
1057
+ amount >= redemptionDustThreshold,
1058
+ "Redemption amount too small"
1059
+ );
1060
+
1061
+ // The redemption key is built on top of the wallet public key hash
1062
+ // and redeemer output script pair. That means there can be only one
1063
+ // request asking for redemption from the given wallet to the given
1064
+ // BTC script at the same time.
1065
+ uint256 redemptionKey =
1066
+ uint256(
1067
+ keccak256(
1068
+ abi.encodePacked(walletPubKeyHash, redeemerOutputScript)
1069
+ )
1070
+ );
1071
+
1072
+ // Check if given redemption key is not used by a pending redemption.
1073
+ // There is no need to check for existence in `timedOutRedemptions`
1074
+ // since the wallet's state is changed to other than Active after
1075
+ // first time out is reported so making new requests is not possible.
1076
+ // slither-disable-next-line incorrect-equality
1077
+ require(
1078
+ pendingRedemptions[redemptionKey].requestedAt == 0,
1079
+ "There is a pending redemption request from this wallet to the same address"
1080
+ );
1081
+
1082
+ uint64 treasuryFee = redemptionTreasuryFee;
1083
+ uint64 txMaxFee = redemptionTxMaxFee;
1084
+
1085
+ // The main wallet UTXO's value doesn't include all pending redemptions.
1086
+ // To determine if the requested redemption can be performed by the
1087
+ // wallet we need to subtract the total value of all pending redemptions
1088
+ // from that wallet's main UTXO value. Given that the treasury fee is
1089
+ // not redeemed from the wallet, we are subtracting it.
1090
+ wallets[walletPubKeyHash].pendingRedemptionsValue +=
1091
+ amount -
1092
+ treasuryFee;
1093
+ require(
1094
+ mainUtxo.txOutputValue >=
1095
+ wallets[walletPubKeyHash].pendingRedemptionsValue,
1096
+ "Insufficient wallet funds"
1097
+ );
1098
+
1099
+ pendingRedemptions[redemptionKey] = RedemptionRequest(
1100
+ msg.sender,
1101
+ amount,
1102
+ treasuryFee,
1103
+ txMaxFee,
1104
+ /* solhint-disable-next-line not-rely-on-time */
1105
+ uint32(block.timestamp)
1106
+ );
1107
+
1108
+ emit RedemptionRequested(
1109
+ walletPubKeyHash,
1110
+ redeemerOutputScript,
1111
+ msg.sender,
1112
+ amount,
1113
+ treasuryFee,
1114
+ txMaxFee
1115
+ );
1116
+
1117
+ bank.transferBalanceFrom(msg.sender, address(this), amount);
1118
+ }
1119
+
1120
+ /// @notice Used by the wallet to prove the BTC redemption transaction
1121
+ /// and to make the necessary bookkeeping. Redemption is only
1122
+ /// accepted if it satisfies SPV proof.
1123
+ ///
1124
+ /// The function is performing Bank balance updates by burning
1125
+ /// the total redeemed Bitcoin amount from Bridge balance and
1126
+ /// transferring the treasury fee sum to the treasury address.
1127
+ ///
1128
+ /// It is possible to prove the given redemption only one time.
1129
+ /// @param redemptionTx Bitcoin redemption transaction data
1130
+ /// @param redemptionProof Bitcoin redemption proof data
1131
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1132
+ /// the Ethereum chain
1133
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1134
+ /// HASH160 over the compressed ECDSA public key) of the wallet which
1135
+ /// performed the redemption transaction
1136
+ /// @dev Requirements:
1137
+ /// - `redemptionTx` components must match the expected structure. See
1138
+ /// `BitcoinTx.Info` docs for reference. Their values must exactly
1139
+ /// correspond to appropriate Bitcoin transaction fields to produce
1140
+ /// a provable transaction hash.
1141
+ /// - The `redemptionTx` should represent a Bitcoin transaction with
1142
+ /// exactly 1 input that refers to the wallet's main UTXO. That
1143
+ /// transaction should have 1..n outputs handling existing pending
1144
+ /// redemption requests or pointing to reported timed out requests.
1145
+ /// There can be also 1 optional output representing the
1146
+ /// change and pointing back to the 20-byte wallet public key hash.
1147
+ /// The change should be always present if the redeemed value sum
1148
+ /// is lower than the total wallet's BTC balance.
1149
+ /// - `redemptionProof` components must match the expected structure.
1150
+ /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`
1151
+ /// field must contain a valid number of block headers, not less
1152
+ /// than the `txProofDifficultyFactor` contract constant.
1153
+ /// - `mainUtxo` components must point to the recent main UTXO
1154
+ /// of the given wallet, as currently known on the Ethereum chain.
1155
+ /// Additionally, the recent main UTXO on Ethereum must be set.
1156
+ /// - `walletPubKeyHash` must be connected with the main UTXO used
1157
+ /// as transaction single input.
1158
+ /// Other remarks:
1159
+ /// - Putting the change output as the first transaction output can
1160
+ /// save some gas because the output processing loop begins each
1161
+ /// iteration by checking whether the given output is the change
1162
+ /// thus uses some gas for making the comparison. Once the change
1163
+ /// is identified, that check is omitted in further iterations.
1164
+ function submitRedemptionProof(
1165
+ BitcoinTx.Info calldata redemptionTx,
1166
+ BitcoinTx.Proof calldata redemptionProof,
1167
+ BitcoinTx.UTXO calldata mainUtxo,
1168
+ bytes20 walletPubKeyHash
1169
+ ) external {
1170
+ // TODO: Just as for `submitSweepProof`, fail early if the function
1171
+ // call gets frontrunned. See discussion:
1172
+ // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
1173
+
1174
+ // The actual transaction proof is performed here. After that point, we
1175
+ // can assume the transaction happened on Bitcoin chain and has
1176
+ // a sufficient number of confirmations as determined by
1177
+ // `txProofDifficultyFactor` constant.
1178
+ bytes32 redemptionTxHash =
1179
+ validateBitcoinTxProof(redemptionTx, redemptionProof);
1180
+
1181
+ // Perform validation of the redemption transaction input. Specifically,
1182
+ // check if it refers to the expected wallet's main UTXO.
1183
+ validateRedemptionTxInput(
1184
+ redemptionTx.inputVector,
1185
+ mainUtxo,
1186
+ walletPubKeyHash
1187
+ );
1188
+
1189
+ WalletState walletState = wallets[walletPubKeyHash].state;
1190
+ require(
1191
+ walletState == WalletState.Active ||
1192
+ walletState == WalletState.MovingFunds,
1193
+ "Wallet must be in Active or MovingFuds state"
1194
+ );
1195
+
1196
+ // Process redemption transaction outputs to extract some info required
1197
+ // for further processing.
1198
+ RedemptionTxOutputsInfo memory outputsInfo =
1199
+ processRedemptionTxOutputs(
1200
+ redemptionTx.outputVector,
1201
+ walletPubKeyHash
1202
+ );
1203
+
1204
+ if (outputsInfo.changeValue > 0) {
1205
+ // If the change value is grater than zero, it means the change
1206
+ // output exists and can be used as new wallet's main UTXO.
1207
+ mainUtxos[walletPubKeyHash] = keccak256(
1208
+ abi.encodePacked(
1209
+ redemptionTxHash,
1210
+ outputsInfo.changeIndex,
1211
+ outputsInfo.changeValue
1212
+ )
1213
+ );
1214
+ } else {
1215
+ // If the change value is zero, it means the change output doesn't
1216
+ // exists and no funds left on the wallet. Delete the main UTXO
1217
+ // for that wallet to represent that state in a proper way.
1218
+ delete mainUtxos[walletPubKeyHash];
1219
+ }
1220
+
1221
+ wallets[walletPubKeyHash].pendingRedemptionsValue -= outputsInfo
1222
+ .totalBurnableValue;
1223
+
1224
+ emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1225
+
1226
+ bank.decreaseBalance(outputsInfo.totalBurnableValue);
1227
+ bank.transferBalance(treasury, outputsInfo.totalTreasuryFee);
1228
+ }
1229
+
1230
+ /// @notice Validates whether the redemption Bitcoin transaction input
1231
+ /// vector contains a single input referring to the wallet's main
1232
+ /// UTXO. Reverts in case the validation fails.
1233
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1234
+ /// vector. This function assumes vector's structure is valid so it
1235
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1236
+ /// before it is passed here
1237
+ /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1238
+ /// the Ethereum chain.
1239
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1240
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1241
+ /// performed the redemption transaction.
1242
+ function validateRedemptionTxInput(
1243
+ bytes memory redemptionTxInputVector,
1244
+ BitcoinTx.UTXO calldata mainUtxo,
1245
+ bytes20 walletPubKeyHash
1246
+ ) internal view {
1247
+ // Assert that main UTXO for passed wallet exists in storage.
1248
+ bytes32 mainUtxoHash = mainUtxos[walletPubKeyHash];
1249
+ require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1250
+
1251
+ // Assert that passed main UTXO parameter is the same as in storage and
1252
+ // can be used for further processing.
1253
+ require(
1254
+ keccak256(
1255
+ abi.encodePacked(
1256
+ mainUtxo.txHash,
1257
+ mainUtxo.txOutputIndex,
1258
+ mainUtxo.txOutputValue
1259
+ )
1260
+ ) == mainUtxoHash,
1261
+ "Invalid main UTXO data"
1262
+ );
1263
+
1264
+ // Assert that the single redemption transaction input actually
1265
+ // refers to the wallet's main UTXO.
1266
+ (bytes32 redemptionTxOutpointTxHash, uint32 redemptionTxOutpointIndex) =
1267
+ processRedemptionTxInput(redemptionTxInputVector);
1268
+ require(
1269
+ mainUtxo.txHash == redemptionTxOutpointTxHash &&
1270
+ mainUtxo.txOutputIndex == redemptionTxOutpointIndex,
1271
+ "Redemption transaction input must point to the wallet's main UTXO"
1272
+ );
1273
+ }
1274
+
1275
+ /// @notice Processes the Bitcoin redemption transaction input vector. It
1276
+ /// extracts the single input then the transaction hash and output
1277
+ /// index from its outpoint.
1278
+ /// @param redemptionTxInputVector Bitcoin redemption transaction input
1279
+ /// vector. This function assumes vector's structure is valid so it
1280
+ /// must be validated using e.g. `BTCUtils.validateVin` function
1281
+ /// before it is passed here
1282
+ /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1283
+ /// pointed in the input's outpoint.
1284
+ /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1285
+ /// which is pointed in the input's outpoint.
1286
+ function processRedemptionTxInput(bytes memory redemptionTxInputVector)
1287
+ internal
1288
+ pure
1289
+ returns (bytes32 outpointTxHash, uint32 outpointIndex)
1290
+ {
1291
+ // To determine the total number of redemption transaction inputs,
1292
+ // we need to parse the compactSize uint (VarInt) the input vector is
1293
+ // prepended by. That compactSize uint encodes the number of vector
1294
+ // elements using the format presented in:
1295
+ // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1296
+ // We don't need asserting the compactSize uint is parseable since it
1297
+ // was already checked during `validateVin` validation.
1298
+ // See `BitcoinTx.inputVector` docs for more details.
1299
+ (, uint256 inputsCount) = redemptionTxInputVector.parseVarInt();
1300
+ require(
1301
+ inputsCount == 1,
1302
+ "Redemption transaction must have a single input"
1303
+ );
1304
+
1305
+ bytes memory input = redemptionTxInputVector.extractInputAtIndex(0);
1306
+
1307
+ outpointTxHash = input.extractInputTxIdLE();
1308
+
1309
+ outpointIndex = BTCUtils.reverseUint32(
1310
+ uint32(input.extractTxIndexLE())
1311
+ );
1312
+
1313
+ // There is only one input in the transaction. Input has an outpoint
1314
+ // field that is a reference to the transaction being spent (see
1315
+ // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1316
+ // to spend (`outpointTxHash`) and the index of the specific output
1317
+ // from that transaction (`outpointIndex`).
1318
+ return (outpointTxHash, outpointIndex);
1319
+ }
1320
+
1321
+ /// @notice Processes the Bitcoin redemption transaction output vector.
1322
+ /// It extracts each output and tries to identify it as a pending
1323
+ /// redemption request, reported timed out request, or change.
1324
+ /// Reverts if one of the outputs cannot be recognized properly.
1325
+ /// This function also marks each request as processed by removing
1326
+ /// them from `pendingRedemptions` mapping.
1327
+ /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1328
+ /// vector. This function assumes vector's structure is valid so it
1329
+ /// must be validated using e.g. `BTCUtils.validateVout` function
1330
+ /// before it is passed here
1331
+ /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1332
+ // HASH160 over the compressed ECDSA public key) of the wallet which
1333
+ /// performed the redemption transaction.
1334
+ /// @return info Outcomes of the processing.
1335
+ function processRedemptionTxOutputs(
1336
+ bytes memory redemptionTxOutputVector,
1337
+ bytes20 walletPubKeyHash
1338
+ ) internal returns (RedemptionTxOutputsInfo memory info) {
1339
+ // Determining the total number of redemption transaction outputs in
1340
+ // the same way as for number of inputs. See `BitcoinTx.outputVector`
1341
+ // docs for more details.
1342
+ (uint256 outputsCompactSizeUintLength, uint256 outputsCount) =
1343
+ redemptionTxOutputVector.parseVarInt();
1344
+
1345
+ // To determine the first output starting index, we must jump over
1346
+ // the compactSize uint which prepends the output vector. One byte
1347
+ // must be added because `BtcUtils.parseVarInt` does not include
1348
+ // compactSize uint tag in the returned length.
1349
+ //
1350
+ // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1351
+ // returns `0`, so we jump over one byte of compactSize uint.
1352
+ //
1353
+ // For >= 253 && <= 0xffff there is `0xfd` tag,
1354
+ // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1355
+ // tag byte included) so we need to jump over 1+2 bytes of
1356
+ // compactSize uint.
1357
+ //
1358
+ // Please refer `BTCUtils` library and compactSize uint
1359
+ // docs in `BitcoinTx` library for more details.
1360
+ uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1361
+
1362
+ // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1363
+ // scripts that can be used to lock the change. This is done upfront to
1364
+ // save on gas. Both scripts have a strict format defined by Bitcoin.
1365
+ //
1366
+ // The P2PKH script has format <0x1976a914> <20-byte PKH> <0x88ac>.
1367
+ bytes32 walletP2PKHScriptKeccak =
1368
+ keccak256(
1369
+ abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1370
+ );
1371
+ // The P2WPKH script has format <0x160014> <20-byte PKH>.
1372
+ bytes32 walletP2WPKHScriptKeccak =
1373
+ keccak256(abi.encodePacked(hex"160014", walletPubKeyHash));
1374
+
1375
+ // Helper variable that counts the number of processed redemption
1376
+ // outputs. Redemptions can be either pending or reported as timed out.
1377
+ // TODO: Revisit the approach with redemptions count according to
1378
+ // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1379
+ uint256 processedRedemptionsCount = 0;
1380
+
1381
+ // Outputs processing loop.
1382
+ for (uint256 i = 0; i < outputsCount; i++) {
1383
+ // TODO: Check if we can optimize gas costs by adding
1384
+ // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1385
+ // in order to avoid allocating bytes in memory.
1386
+ uint256 outputLength =
1387
+ redemptionTxOutputVector.determineOutputLengthAt(
1388
+ outputStartingIndex
1389
+ );
1390
+ bytes memory output =
1391
+ redemptionTxOutputVector.slice(
1392
+ outputStartingIndex,
1393
+ outputLength
1394
+ );
1395
+
1396
+ // Extract the value from given output.
1397
+ uint64 outputValue = output.extractValue();
1398
+ // The output consists of an 8-byte value and a variable length
1399
+ // script. To extract that script we slice the output staring from
1400
+ // 9th byte until the end.
1401
+ bytes memory outputScript = output.slice(8, output.length - 8);
1402
+
1403
+ if (
1404
+ info.changeValue == 0 &&
1405
+ (keccak256(outputScript) == walletP2PKHScriptKeccak ||
1406
+ keccak256(outputScript) == walletP2WPKHScriptKeccak) &&
1407
+ outputValue > 0
1408
+ ) {
1409
+ // If we entered here, that means the change output with a
1410
+ // proper non-zero value was found.
1411
+ info.changeIndex = uint32(i);
1412
+ info.changeValue = outputValue;
1413
+ } else {
1414
+ // If we entered here, that the means the given output is
1415
+ // supposed to represent a redemption. Build the redemption key
1416
+ // to perform that check.
1417
+ uint256 redemptionKey =
1418
+ uint256(
1419
+ keccak256(
1420
+ abi.encodePacked(walletPubKeyHash, outputScript)
1421
+ )
1422
+ );
1423
+
1424
+ if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1425
+ // If we entered here, that means the output was identified
1426
+ // as a pending redemption request.
1427
+ RedemptionRequest storage request =
1428
+ pendingRedemptions[redemptionKey];
1429
+ // Compute the request's redeemable amount as the requested
1430
+ // amount reduced by the treasury fee. The request's
1431
+ // minimal amount is then the redeemable amount reduced by
1432
+ // the maximum transaction fee.
1433
+ uint64 redeemableAmount =
1434
+ request.requestedAmount - request.treasuryFee;
1435
+ // Output value must fit between the request's redeemable
1436
+ // and minimal amounts to be deemed valid.
1437
+ require(
1438
+ redeemableAmount - request.txMaxFee <= outputValue &&
1439
+ outputValue <= redeemableAmount,
1440
+ "Output value is not within the acceptable range of the pending request"
1441
+ );
1442
+ // Add the redeemable amount to the total burnable value
1443
+ // the Bridge will use to decrease its balance in the Bank.
1444
+ info.totalBurnableValue += redeemableAmount;
1445
+ // Add the request's treasury fee to the total treasury fee
1446
+ // value the Bridge will transfer to the treasury.
1447
+ info.totalTreasuryFee += request.treasuryFee;
1448
+ // Request was properly handled so remove its redemption
1449
+ // key from the mapping to make it reusable for further
1450
+ // requests.
1451
+ delete pendingRedemptions[redemptionKey];
1452
+
1453
+ processedRedemptionsCount++;
1454
+ } else {
1455
+ // If we entered here, the output is not a redemption
1456
+ // request but there is still a chance the given output is
1457
+ // related to a reported timed out redemption request.
1458
+ // If so, check if the output value matches the request
1459
+ // amount to confirm this is an overdue request fulfillment
1460
+ // then bypass this output and process the subsequent
1461
+ // ones. That also means the wallet was already punished
1462
+ // for the inactivity. Otherwise, just revert.
1463
+ RedemptionRequest storage request =
1464
+ timedOutRedemptions[redemptionKey];
1465
+
1466
+ require(
1467
+ request.requestedAt != 0,
1468
+ "Output is a non-requested redemption"
1469
+ );
1470
+
1471
+ uint64 redeemableAmount =
1472
+ request.requestedAmount - request.treasuryFee;
1473
+
1474
+ require(
1475
+ redeemableAmount - request.txMaxFee <= outputValue &&
1476
+ outputValue <= redeemableAmount,
1477
+ "Output value is not within the acceptable range of the timed out request"
1478
+ );
1479
+
1480
+ processedRedemptionsCount++;
1481
+ }
1482
+ }
1483
+
1484
+ // Make the `outputStartingIndex` pointing to the next output by
1485
+ // increasing it by current output's length.
1486
+ outputStartingIndex += outputLength;
1487
+ }
1488
+
1489
+ // Protect against the cases when there is only a single change output
1490
+ // referring back to the wallet PKH and just burning main UTXO value
1491
+ // for transaction fees.
1492
+ require(
1493
+ processedRedemptionsCount > 0,
1494
+ "Redemption transaction must process at least one redemption"
1495
+ );
1496
+
1497
+ return info;
795
1498
  }
796
1499
 
797
- // TODO It is possible a malicious wallet can sweep deposits that can not
798
- // be later proved on Ethereum. For example, a deposit with
799
- // an incorrect amount revealed. We need to provide a function for honest
800
- // depositors, next to sweep, to prove their swept balances on Ethereum
801
- // selectively, based on deposits they have earlier received.
802
- // (UPDATE PR #90: Is it still the case since amounts are inferred?)
1500
+ // TODO: Function `notifyRedemptionTimeout. That function must:
1501
+ // 1. Take a the `walletPubKey` and `redeemerOutputScript` as params.
1502
+ // 2. Build the redemption key using those params.
1503
+ // 3. Use the redemption key and take the request from
1504
+ // `pendingRedemptions` mapping.
1505
+ // 4. If request doesn't exist in mapping - revert.
1506
+ // 5. If request exits, and is timed out - remove the redemption key
1507
+ // from `pendingRedemptions` and put it to `timedOutRedemptions`
1508
+ // by copying the entire `RedemptionRequest` struct there. No need
1509
+ // to check if `timedOutRedemptions` mapping already contains
1510
+ // that key because `requestRedemption` blocks requests targeting
1511
+ // non-active wallets. Because `notifyRedemptionTimeout` changes
1512
+ // wallet state after first call (point 9), there is no possibility
1513
+ // that the given redemption key could be reported as timed out
1514
+ // multiple times. At the same time, if the given redemption key
1515
+ // was already marked as fraudulent due to an amount-related fraud,
1516
+ // it will not be possible to report a time out on it since it
1517
+ // won't be present in `pendingRedemptions` mapping.
1518
+ // 6. Return the `requestedAmount` to the `redeemer`.
1519
+ // 7. Reduce the `pendingRedemptionsValue` (`wallets` mapping) for
1520
+ // given wallet by request's redeemable amount computed as
1521
+ // `requestedAmount - treasuryFee`.
1522
+ // 8. Punish the wallet, probably by slashing its operators.
1523
+ // 9. Change wallet's state in `wallets` mapping to `MovingFunds` in
1524
+ // order to prevent against new redemption requests hitting
1525
+ // that wallet.
1526
+ // 10. Expect the wallet to transfer its funds to another healthy
1527
+ // wallet (just as in case of failed heartbeat). The wallet is
1528
+ // expected to finish the already queued redemption requests
1529
+ // before moving funds but we are not going to enforce it on-chain.
1530
+
1531
+ // TODO: Function `submitRedemptionFraudProof`
1532
+ //
1533
+ // Deposit and redemption fraud proofs are challenging to implement
1534
+ // and it may happen we will have to rely on the coverage pool
1535
+ // (https://github.com/keep-network/coverage-pools) and DAO to
1536
+ // reimburse unlucky depositors and bring back the balance to the
1537
+ // system in case of a wallet fraud by liquidating a part of the
1538
+ // coverage pool manually.
1539
+ //
1540
+ // The probability of 51-of-100 wallet being fraudulent is negligible:
1541
+ // https://github.com/keep-network/tbtc-v2/blob/main/docs/rfc/rfc-2.adoc#111-group-size-and-threshold
1542
+ // and the coverage pool would be there to bring the balance back in
1543
+ // case we are unlucky and malicious wallet emerges.
1544
+ //
1545
+ // We do not want to slash for a misbehavior that is not provable
1546
+ // on-chain and it is possible to construct such a Bitcoin transaction
1547
+ // that is not provable on Ethereum, see
1548
+ // https://consensys.net/diligence/blog/2020/05/tbtc-navigating-the-cross-chain-conundrum
1549
+ //
1550
+ // The algorithm described below assumes we will be able to prove the
1551
+ // TX on Ethereum which may not always be the case. Consider the steps
1552
+ // below as an idea, and not necessarily how this function will be
1553
+ // implemented because it may happen this function will never be
1554
+ // implemented, given the Bitcoin transaction size problems.
1555
+ //
1556
+ // The algorithm:
1557
+ // 1. Take a `BitcoinTx.Info` and `BitcoinTx.Proof` of the
1558
+ // fraudulent transaction. It should also accept `walletPubKeyHash`
1559
+ // and index of fraudulent output. Probably index of fraudulent
1560
+ // input will be also required if the transaction is supposed
1561
+ // to have a bad input vector.
1562
+ // 2. Perform SPV proof to make sure it occurred on Bitcoin chain.
1563
+ // If not - revert.
1564
+ // 3. Check if wallet state is Active or MovingFunds. If not, revert.
1565
+ // 4. Validate the number of inputs. If there is one input and it
1566
+ // points to the wallet's main UTXO - move to point 5. If there
1567
+ // are multiple inputs and there is wallet's main UTXO in the set,
1568
+ // check if this is a sweep transaction. If it's not a sweep,
1569
+ // consider it as fraudulent and move to point 6.
1570
+ // In all other cases revert the call.
1571
+ // 5. Extract the output and analyze its type. The output is not
1572
+ // a fraud and the call should be reverted ONLY IF one of the
1573
+ // following conditions is true:
1574
+ // - Output is a requested redemption held by `pendingRedemptions`
1575
+ // and output value fulfills the request range. There is an
1576
+ // open question if a misfunded request should be removed
1577
+ // from `pendingRedemptions` (probably yes) and whether the
1578
+ // redeemer should be reimbursed in case of an underfund.
1579
+ // - Output is a timed out redemption held by `timedOutRedemptions`
1580
+ // and output value fulfills the request range.
1581
+ // - Output is a proper change i.e. a single output targeting
1582
+ // the wallet PKH back and having a non-zero value.
1583
+ // - Wallet is in MovingFunds state, the output points to the
1584
+ // expected target wallet, have non-zero value, and is a single
1585
+ // output in the vector.
1586
+ // In all other cases consider the transaction as fraud and
1587
+ // proceed to point 6.
1588
+ // 6. Punish the wallet, probably by severely slashing its operators.
1589
+ // 7. Change wallet's state in `wallets` mapping to `Terminated` in
1590
+ // order to prevent against new redemption requests hitting
1591
+ // that wallet. This also prevents against reporting a fraud
1592
+ // multiple times for one transaction (see point 3) and blocks
1593
+ // submission of sweep and redemption proofs. `Terminated` wallet
1594
+ // is blocked in the Bridge forever. If the fraud was a mistake
1595
+ // done by the wallet and the wallet is still honest deep in its
1596
+ // heart, the wallet can coordinate off-chain to recover the BTC
1597
+ // and donate it to another wallet. If they recover all of the
1598
+ // remaining BTC, DAO might decide to reward them with tokens so
1599
+ // that they can have at least some portion of their slashed
1600
+ // tokens back.
803
1601
  }