@keep-network/tbtc-v2 0.1.1-dev.36 → 0.1.1-dev.39

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 (38) hide show
  1. package/artifacts/TBTC.json +3 -3
  2. package/artifacts/TBTCToken.json +3 -3
  3. package/artifacts/VendingMachine.json +10 -10
  4. package/artifacts/solcInputs/{4718d6e944ad9d1fc247efda870cf51a.json → 518efc6faeb6612766a5b3fef24e13ad.json} +10 -4
  5. package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
  6. package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
  7. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
  8. package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.json +3 -89
  9. package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
  10. package/build/contracts/bridge/Bridge.sol/Bridge.json +165 -157
  11. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  12. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +2 -2
  13. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  14. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  15. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  16. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +1 -1
  17. package/build/contracts/bridge/Frauds.sol/Frauds.json +2 -2
  18. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
  19. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +4 -0
  20. package/build/contracts/bridge/MovingFunds.sol/MovingFunds.json +48 -0
  21. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  22. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  23. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  24. package/build/contracts/bridge/Redeem.sol/Redeem.json +110 -0
  25. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +1 -1
  26. package/build/contracts/bridge/Sweep.sol/Sweep.json +4 -22
  27. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  28. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  29. package/build/contracts/bridge/Wallets.sol/Wallets.json +2 -2
  30. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  31. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  32. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  33. package/contracts/bridge/BitcoinTx.sol +3 -3
  34. package/contracts/bridge/Bridge.sol +131 -910
  35. package/contracts/bridge/BridgeState.sol +68 -0
  36. package/contracts/bridge/MovingFunds.sol +280 -0
  37. package/contracts/bridge/Redeem.sol +849 -0
  38. package/package.json +1 -1
@@ -26,10 +26,12 @@ import "./IRelay.sol";
26
26
  import "./BridgeState.sol";
27
27
  import "./Deposit.sol";
28
28
  import "./Sweep.sol";
29
+ import "./Redeem.sol";
29
30
  import "./BitcoinTx.sol";
30
31
  import "./EcdsaLib.sol";
31
32
  import "./Wallets.sol";
32
33
  import "./Frauds.sol";
34
+ import "./MovingFunds.sol";
33
35
 
34
36
  import "../bank/Bank.sol";
35
37
 
@@ -53,14 +55,16 @@ import "../bank/Bank.sol";
53
55
  /// balances in the Bank.
54
56
  /// @dev Bridge is an upgradeable component of the Bank.
55
57
  ///
56
- /// TODO: All wallets-related operations that are currently done directly
57
- /// by the Bridge can be probably delegated to the Wallets library.
58
- /// Examples of such operations are main UTXO or pending redemptions
59
- /// value updates.
58
+ // TODO: All wallets-related operations that are currently done directly
59
+ // by the Bridge can be probably delegated to the Wallets library.
60
+ // Examples of such operations are main UTXO or pending redemptions
61
+ // value updates.
60
62
  contract Bridge is Ownable, EcdsaWalletOwner {
61
63
  using BridgeState for BridgeState.Storage;
62
64
  using Deposit for BridgeState.Storage;
63
65
  using Sweep for BridgeState.Storage;
66
+ using Redeem for BridgeState.Storage;
67
+ using MovingFunds for BridgeState.Storage;
64
68
  using Frauds for Frauds.Data;
65
69
  using Wallets for Wallets.Data;
66
70
 
@@ -68,131 +72,8 @@ contract Bridge is Ownable, EcdsaWalletOwner {
68
72
  using BTCUtils for uint256;
69
73
  using BytesLib for bytes;
70
74
 
71
- /// @notice Represents a redemption request.
72
- struct RedemptionRequest {
73
- // ETH address of the redeemer who created the request.
74
- address redeemer;
75
- // Requested TBTC amount in satoshi.
76
- uint64 requestedAmount;
77
- // Treasury TBTC fee in satoshi at the moment of request creation.
78
- uint64 treasuryFee;
79
- // Transaction maximum BTC fee in satoshi at the moment of request
80
- // creation.
81
- uint64 txMaxFee;
82
- // UNIX timestamp the request was created at.
83
- uint32 requestedAt;
84
- }
85
-
86
- /// @notice Represents an outcome of the redemption Bitcoin transaction
87
- /// outputs processing.
88
- struct RedemptionTxOutputsInfo {
89
- // Total TBTC value in satoshi that should be burned by the Bridge.
90
- // It includes the total amount of all BTC redeemed in the transaction
91
- // and the fee paid to BTC miners for the redemption transaction.
92
- uint64 totalBurnableValue;
93
- // Total TBTC value in satoshi that should be transferred to
94
- // the treasury. It is a sum of all treasury fees paid by all
95
- // redeemers included in the redemption transaction.
96
- uint64 totalTreasuryFee;
97
- // Index of the change output. The change output becomes
98
- // the new main wallet's UTXO.
99
- uint32 changeIndex;
100
- // Value in satoshi of the change output.
101
- uint64 changeValue;
102
- }
103
-
104
- /// @notice Represents temporary information needed during the processing of
105
- /// the redemption Bitcoin transaction outputs. This structure is an
106
- /// internal one and should not be exported outside of the redemption
107
- /// transaction processing code.
108
- /// @dev Allows to mitigate "stack too deep" errors on EVM.
109
- struct RedemptionTxOutputsProcessingInfo {
110
- // The first output starting index in the transaction.
111
- uint256 outputStartingIndex;
112
- // The number of outputs in the transaction.
113
- uint256 outputsCount;
114
- // P2PKH script for the wallet. Needed to determine the change output.
115
- bytes32 walletP2PKHScriptKeccak;
116
- // P2WPKH script for the wallet. Needed to determine the change output.
117
- bytes32 walletP2WPKHScriptKeccak;
118
- }
119
-
120
75
  BridgeState.Storage internal self;
121
76
 
122
- /// TODO: Make it governable.
123
- /// @notice The minimal amount that can be requested for redemption.
124
- /// Value of this parameter must take into account the value of
125
- /// `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
126
- /// parameters in order to make requests that can incur the
127
- /// treasury and transaction fee and still satisfy the redeemer.
128
- uint64 public redemptionDustThreshold;
129
-
130
- /// TODO: Make it governable.
131
- /// @notice Divisor used to compute the treasury fee taken from each
132
- /// redemption request and transferred to the treasury upon
133
- /// successful request finalization. That fee is computed as follows:
134
- /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
135
- /// For example, if the treasury fee needs to be 2% of each
136
- /// redemption request, the `redemptionTreasuryFeeDivisor` should
137
- /// be set to `50` because `1/50 = 0.02 = 2%`.
138
- uint64 public redemptionTreasuryFeeDivisor;
139
-
140
- /// TODO: Make it governable.
141
- /// @notice Maximum amount of BTC transaction fee that can be incurred by
142
- /// each redemption request being part of the given redemption
143
- /// transaction. If the maximum BTC transaction fee is exceeded, such
144
- /// transaction is considered a fraud.
145
- /// @dev This is a per-redemption output max fee for the redemption transaction.
146
- uint64 public redemptionTxMaxFee;
147
-
148
- /// TODO: Make it governable.
149
- /// @notice Time after which the redemption request can be reported as
150
- /// timed out. It is counted from the moment when the redemption
151
- /// request was created via `requestRedemption` call. Reported
152
- /// timed out requests are cancelled and locked TBTC is returned
153
- /// to the redeemer in full amount.
154
- uint256 public redemptionTimeout;
155
-
156
- /// TODO: Make it governable.
157
- /// @notice Maximum amount of the total BTC transaction fee that is
158
- /// acceptable in a single moving funds transaction.
159
- /// @dev This is a TOTAL max fee for the moving funds transaction. Note that
160
- /// `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`
161
- /// if per single redemption. `movingFundsTxMaxTotalFee` is a total fee
162
- /// for the entire transaction.
163
- uint64 public movingFundsTxMaxTotalFee;
164
-
165
- /// @notice Collection of all pending redemption requests indexed by
166
- /// redemption key built as
167
- /// keccak256(walletPubKeyHash | redeemerOutputScript). The
168
- /// walletPubKeyHash is the 20-byte wallet's public key hash
169
- /// (computed using Bitcoin HASH160 over the compressed ECDSA
170
- /// public key) and redeemerOutputScript is a Bitcoin script
171
- /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
172
- /// redeemed BTC as requested by the redeemer. Requests are added
173
- /// to this mapping by the `requestRedemption` method (duplicates
174
- /// not allowed) and are removed by one of the following methods:
175
- /// - `submitRedemptionProof` in case the request was handled
176
- /// successfully
177
- /// - `notifyRedemptionTimeout` in case the request was reported
178
- /// to be timed out
179
- mapping(uint256 => RedemptionRequest) public pendingRedemptions;
180
-
181
- /// @notice Collection of all timed out redemptions requests indexed by
182
- /// redemption key built as
183
- /// keccak256(walletPubKeyHash | redeemerOutputScript). The
184
- /// walletPubKeyHash is the 20-byte wallet's public key hash
185
- /// (computed using Bitcoin HASH160 over the compressed ECDSA
186
- /// public key) and redeemerOutputScript is the Bitcoin script
187
- /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
188
- /// out request. Timed out requests are stored in this mapping to
189
- /// avoid slashing the wallets multiple times for the same timeout.
190
- /// Only one method can add to this mapping:
191
- /// - `notifyRedemptionTimeout` which puts the redemption key
192
- /// to this mapping basing on a timed out request stored
193
- /// previously in `pendingRedemptions` mapping.
194
- mapping(uint256 => RedemptionRequest) public timedOutRedemptions;
195
-
196
77
  /// @notice Contains parameters related to frauds and the collection of all
197
78
  /// submitted fraud challenges.
198
79
  Frauds.Data internal frauds;
@@ -322,11 +203,11 @@ contract Bridge is Ownable, EcdsaWalletOwner {
322
203
  self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
323
204
  self.depositTxMaxFee = 10000; // 10000 satoshi
324
205
  self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
325
- redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
326
- redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
327
- redemptionTxMaxFee = 10000; // 10000 satoshi
328
- redemptionTimeout = 172800; // 48 hours
329
- movingFundsTxMaxTotalFee = 10000; // 10000 satoshi
206
+ self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
207
+ self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
208
+ self.redemptionTxMaxFee = 10000; // 10000 satoshi
209
+ self.redemptionTimeout = 172800; // 48 hours
210
+ self.movingFundsTxMaxTotalFee = 10000; // 10000 satoshi
330
211
 
331
212
  // TODO: Revisit initial values.
332
213
  frauds.setSlashingAmount(10000 * 1e18); // 10000 T
@@ -797,123 +678,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
797
678
  bytes calldata redeemerOutputScript,
798
679
  uint64 amount
799
680
  ) external {
800
- Wallets.Wallet storage wallet = wallets.registeredWallets[
801
- walletPubKeyHash
802
- ];
803
-
804
- require(
805
- wallet.state == Wallets.WalletState.Live,
806
- "Wallet must be in Live state"
807
- );
808
-
809
- bytes32 mainUtxoHash = wallet.mainUtxoHash;
810
- require(
811
- mainUtxoHash != bytes32(0),
812
- "No main UTXO for the given wallet"
813
- );
814
- require(
815
- keccak256(
816
- abi.encodePacked(
817
- mainUtxo.txHash,
818
- mainUtxo.txOutputIndex,
819
- mainUtxo.txOutputValue
820
- )
821
- ) == mainUtxoHash,
822
- "Invalid main UTXO data"
823
- );
824
-
825
- // TODO: Confirm if `walletPubKeyHash` should be validated by checking
826
- // if it is the oldest one who can handle the request. This will
827
- // be suggested by the dApp but may not be respected by users who
828
- // interact directly with the contract. Do we need to enforce it
829
- // here? One option is not to enforce it, to save on gas, but if
830
- // we see this rule is not respected, upgrade Bridge contract to
831
- // require it.
832
-
833
- // Validate if redeemer output script is a correct standard type
834
- // (P2PKH, P2WPKH, P2SH or P2WSH). This is done by building a stub
835
- // output with 0 as value and using `BTCUtils.extractHash` on it. Such
836
- // a function extracts the payload properly only from standard outputs
837
- // so if it succeeds, we have a guarantee the redeemer output script
838
- // is proper. Worth to note `extractHash` ignores the value at all
839
- // so this is why we can use 0 safely. This way of validation is the
840
- // same as in tBTC v1.
841
- bytes memory redeemerOutputScriptPayload = abi
842
- .encodePacked(bytes8(0), redeemerOutputScript)
843
- .extractHash();
844
- require(
845
- redeemerOutputScriptPayload.length > 0,
846
- "Redeemer output script must be a standard type"
847
- );
848
- // Check if the redeemer output script payload does not point to the
849
- // wallet public key hash.
850
- require(
851
- keccak256(abi.encodePacked(walletPubKeyHash)) !=
852
- keccak256(redeemerOutputScriptPayload),
853
- "Redeemer output script must not point to the wallet PKH"
854
- );
855
-
856
- require(
857
- amount >= redemptionDustThreshold,
858
- "Redemption amount too small"
859
- );
860
-
861
- // The redemption key is built on top of the wallet public key hash
862
- // and redeemer output script pair. That means there can be only one
863
- // request asking for redemption from the given wallet to the given
864
- // BTC script at the same time.
865
- uint256 redemptionKey = uint256(
866
- keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
867
- );
868
-
869
- // Check if given redemption key is not used by a pending redemption.
870
- // There is no need to check for existence in `timedOutRedemptions`
871
- // since the wallet's state is changed to other than Live after
872
- // first time out is reported so making new requests is not possible.
873
- // slither-disable-next-line incorrect-equality
874
- require(
875
- pendingRedemptions[redemptionKey].requestedAt == 0,
876
- "There is a pending redemption request from this wallet to the same address"
877
- );
878
-
879
- // No need to check whether `amount - treasuryFee - txMaxFee > 0`
880
- // since the `redemptionDustThreshold` should force that condition
881
- // to be always true.
882
- uint64 treasuryFee = redemptionTreasuryFeeDivisor > 0
883
- ? amount / redemptionTreasuryFeeDivisor
884
- : 0;
885
- uint64 txMaxFee = redemptionTxMaxFee;
886
-
887
- // The main wallet UTXO's value doesn't include all pending redemptions.
888
- // To determine if the requested redemption can be performed by the
889
- // wallet we need to subtract the total value of all pending redemptions
890
- // from that wallet's main UTXO value. Given that the treasury fee is
891
- // not redeemed from the wallet, we are subtracting it.
892
- wallet.pendingRedemptionsValue += amount - treasuryFee;
893
- require(
894
- mainUtxo.txOutputValue >= wallet.pendingRedemptionsValue,
895
- "Insufficient wallet funds"
896
- );
897
-
898
- pendingRedemptions[redemptionKey] = RedemptionRequest(
899
- msg.sender,
900
- amount,
901
- treasuryFee,
902
- txMaxFee,
903
- /* solhint-disable-next-line not-rely-on-time */
904
- uint32(block.timestamp)
905
- );
906
-
907
- emit RedemptionRequested(
681
+ self.requestRedemption(
682
+ wallets,
908
683
  walletPubKeyHash,
684
+ mainUtxo,
909
685
  redeemerOutputScript,
910
- msg.sender,
911
- amount,
912
- treasuryFee,
913
- txMaxFee
686
+ amount
914
687
  );
915
-
916
- self.bank.transferBalanceFrom(msg.sender, address(this), amount);
917
688
  }
918
689
 
919
690
  /// @notice Used by the wallet to prove the BTC redemption transaction
@@ -966,443 +737,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
966
737
  BitcoinTx.UTXO calldata mainUtxo,
967
738
  bytes20 walletPubKeyHash
968
739
  ) external {
969
- // TODO: Just as for `submitSweepProof`, fail early if the function
970
- // call gets frontrunned. See discussion:
971
- // https://github.com/keep-network/tbtc-v2/pull/106#discussion_r801745204
972
-
973
- // The actual transaction proof is performed here. After that point, we
974
- // can assume the transaction happened on Bitcoin chain and has
975
- // a sufficient number of confirmations as determined by
976
- // `txProofDifficultyFactor` constant.
977
- bytes32 redemptionTxHash = BitcoinTx.validateProof(
740
+ self.submitRedemptionProof(
741
+ wallets,
978
742
  redemptionTx,
979
743
  redemptionProof,
980
- self.proofDifficultyContext()
981
- );
982
-
983
- // Process the redemption transaction input. Specifically, check if it
984
- // refers to the expected wallet's main UTXO.
985
- processWalletOutboundTxInput(
986
- redemptionTx.inputVector,
987
744
  mainUtxo,
988
745
  walletPubKeyHash
989
746
  );
990
-
991
- Wallets.Wallet storage wallet = wallets.registeredWallets[
992
- walletPubKeyHash
993
- ];
994
-
995
- Wallets.WalletState walletState = wallet.state;
996
- require(
997
- walletState == Wallets.WalletState.Live ||
998
- walletState == Wallets.WalletState.MovingFunds,
999
- "Wallet must be in Live or MovingFuds state"
1000
- );
1001
-
1002
- // Process redemption transaction outputs to extract some info required
1003
- // for further processing.
1004
- RedemptionTxOutputsInfo memory outputsInfo = processRedemptionTxOutputs(
1005
- redemptionTx.outputVector,
1006
- walletPubKeyHash
1007
- );
1008
-
1009
- if (outputsInfo.changeValue > 0) {
1010
- // If the change value is grater than zero, it means the change
1011
- // output exists and can be used as new wallet's main UTXO.
1012
- wallet.mainUtxoHash = keccak256(
1013
- abi.encodePacked(
1014
- redemptionTxHash,
1015
- outputsInfo.changeIndex,
1016
- outputsInfo.changeValue
1017
- )
1018
- );
1019
- } else {
1020
- // If the change value is zero, it means the change output doesn't
1021
- // exists and no funds left on the wallet. Delete the main UTXO
1022
- // for that wallet to represent that state in a proper way.
1023
- delete wallet.mainUtxoHash;
1024
- }
1025
-
1026
- wallet.pendingRedemptionsValue -= outputsInfo.totalBurnableValue;
1027
-
1028
- emit RedemptionsCompleted(walletPubKeyHash, redemptionTxHash);
1029
-
1030
- self.bank.decreaseBalance(outputsInfo.totalBurnableValue);
1031
- self.bank.transferBalance(self.treasury, outputsInfo.totalTreasuryFee);
1032
- }
1033
-
1034
- /// @notice Checks whether an outbound Bitcoin transaction performed from
1035
- /// the given wallet has an input vector that contains a single
1036
- /// input referring to the wallet's main UTXO. Marks that main UTXO
1037
- /// as correctly spent if the validation succeeds. Reverts otherwise.
1038
- /// There are two outbound transactions from a wallet possible: a
1039
- /// redemption transaction or a moving funds to another wallet
1040
- /// transaction.
1041
- /// @param walletOutboundTxInputVector Bitcoin outbound transaction's input
1042
- /// vector. This function assumes vector's structure is valid so it
1043
- /// must be validated using e.g. `BTCUtils.validateVin` function
1044
- /// before it is passed here
1045
- /// @param mainUtxo Data of the wallet's main UTXO, as currently known on
1046
- /// the Ethereum chain.
1047
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1048
- // HASH160 over the compressed ECDSA public key) of the wallet which
1049
- /// performed the outbound transaction.
1050
- function processWalletOutboundTxInput(
1051
- bytes memory walletOutboundTxInputVector,
1052
- BitcoinTx.UTXO calldata mainUtxo,
1053
- bytes20 walletPubKeyHash
1054
- ) internal {
1055
- // Assert that main UTXO for passed wallet exists in storage.
1056
- bytes32 mainUtxoHash = wallets
1057
- .registeredWallets[walletPubKeyHash]
1058
- .mainUtxoHash;
1059
- require(mainUtxoHash != bytes32(0), "No main UTXO for given wallet");
1060
-
1061
- // Assert that passed main UTXO parameter is the same as in storage and
1062
- // can be used for further processing.
1063
- require(
1064
- keccak256(
1065
- abi.encodePacked(
1066
- mainUtxo.txHash,
1067
- mainUtxo.txOutputIndex,
1068
- mainUtxo.txOutputValue
1069
- )
1070
- ) == mainUtxoHash,
1071
- "Invalid main UTXO data"
1072
- );
1073
-
1074
- // Assert that the single outbound transaction input actually
1075
- // refers to the wallet's main UTXO.
1076
- (
1077
- bytes32 outpointTxHash,
1078
- uint32 outpointIndex
1079
- ) = parseWalletOutboundTxInput(walletOutboundTxInputVector);
1080
- require(
1081
- mainUtxo.txHash == outpointTxHash &&
1082
- mainUtxo.txOutputIndex == outpointIndex,
1083
- "Outbound transaction input must point to the wallet's main UTXO"
1084
- );
1085
-
1086
- // Main UTXO used as an input, mark it as spent.
1087
- self.spentMainUTXOs[
1088
- uint256(
1089
- keccak256(
1090
- abi.encodePacked(mainUtxo.txHash, mainUtxo.txOutputIndex)
1091
- )
1092
- )
1093
- ] = true;
1094
- }
1095
-
1096
- /// @notice Parses the input vector of an outbound Bitcoin transaction
1097
- /// performed from the given wallet. It extracts the single input
1098
- /// then the transaction hash and output index from its outpoint.
1099
- /// There are two outbound transactions from a wallet possible: a
1100
- /// redemption transaction or a moving funds to another wallet
1101
- /// transaction.
1102
- /// @param walletOutboundTxInputVector Bitcoin outbound transaction input
1103
- /// vector. This function assumes vector's structure is valid so it
1104
- /// must be validated using e.g. `BTCUtils.validateVin` function
1105
- /// before it is passed here
1106
- /// @return outpointTxHash 32-byte hash of the Bitcoin transaction which is
1107
- /// pointed in the input's outpoint.
1108
- /// @return outpointIndex 4-byte index of the Bitcoin transaction output
1109
- /// which is pointed in the input's outpoint.
1110
- function parseWalletOutboundTxInput(
1111
- bytes memory walletOutboundTxInputVector
1112
- ) internal pure returns (bytes32 outpointTxHash, uint32 outpointIndex) {
1113
- // To determine the total number of Bitcoin transaction inputs,
1114
- // we need to parse the compactSize uint (VarInt) the input vector is
1115
- // prepended by. That compactSize uint encodes the number of vector
1116
- // elements using the format presented in:
1117
- // https://developer.bitcoin.org/reference/transactions.html#compactsize-unsigned-integers
1118
- // We don't need asserting the compactSize uint is parseable since it
1119
- // was already checked during `validateVin` validation.
1120
- // See `BitcoinTx.inputVector` docs for more details.
1121
- (, uint256 inputsCount) = walletOutboundTxInputVector.parseVarInt();
1122
- require(
1123
- inputsCount == 1,
1124
- "Outbound transaction must have a single input"
1125
- );
1126
-
1127
- bytes memory input = walletOutboundTxInputVector.extractInputAtIndex(0);
1128
-
1129
- outpointTxHash = input.extractInputTxIdLE();
1130
-
1131
- outpointIndex = BTCUtils.reverseUint32(
1132
- uint32(input.extractTxIndexLE())
1133
- );
1134
-
1135
- // There is only one input in the transaction. Input has an outpoint
1136
- // field that is a reference to the transaction being spent (see
1137
- // `BitcoinTx` docs). The outpoint contains the hash of the transaction
1138
- // to spend (`outpointTxHash`) and the index of the specific output
1139
- // from that transaction (`outpointIndex`).
1140
- return (outpointTxHash, outpointIndex);
1141
- }
1142
-
1143
- /// @notice Processes the Bitcoin redemption transaction output vector.
1144
- /// It extracts each output and tries to identify it as a pending
1145
- /// redemption request, reported timed out request, or change.
1146
- /// Reverts if one of the outputs cannot be recognized properly.
1147
- /// This function also marks each request as processed by removing
1148
- /// them from `pendingRedemptions` mapping.
1149
- /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1150
- /// vector. This function assumes vector's structure is valid so it
1151
- /// must be validated using e.g. `BTCUtils.validateVout` function
1152
- /// before it is passed here
1153
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1154
- // HASH160 over the compressed ECDSA public key) of the wallet which
1155
- /// performed the redemption transaction.
1156
- /// @return info Outcomes of the processing.
1157
- function processRedemptionTxOutputs(
1158
- bytes memory redemptionTxOutputVector,
1159
- bytes20 walletPubKeyHash
1160
- ) internal returns (RedemptionTxOutputsInfo memory info) {
1161
- // Determining the total number of redemption transaction outputs in
1162
- // the same way as for number of inputs. See `BitcoinTx.outputVector`
1163
- // docs for more details.
1164
- (
1165
- uint256 outputsCompactSizeUintLength,
1166
- uint256 outputsCount
1167
- ) = redemptionTxOutputVector.parseVarInt();
1168
-
1169
- // To determine the first output starting index, we must jump over
1170
- // the compactSize uint which prepends the output vector. One byte
1171
- // must be added because `BtcUtils.parseVarInt` does not include
1172
- // compactSize uint tag in the returned length.
1173
- //
1174
- // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1175
- // returns `0`, so we jump over one byte of compactSize uint.
1176
- //
1177
- // For >= 253 && <= 0xffff there is `0xfd` tag,
1178
- // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1179
- // tag byte included) so we need to jump over 1+2 bytes of
1180
- // compactSize uint.
1181
- //
1182
- // Please refer `BTCUtils` library and compactSize uint
1183
- // docs in `BitcoinTx` library for more details.
1184
- uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1185
-
1186
- // Calculate the keccak256 for two possible wallet's P2PKH or P2WPKH
1187
- // scripts that can be used to lock the change. This is done upfront to
1188
- // save on gas. Both scripts have a strict format defined by Bitcoin.
1189
- //
1190
- // The P2PKH script has the byte format: <0x1976a914> <20-byte PKH> <0x88ac>.
1191
- // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1192
- // - 0x19: Byte length of the entire script
1193
- // - 0x76: OP_DUP
1194
- // - 0xa9: OP_HASH160
1195
- // - 0x14: Byte length of the public key hash
1196
- // - 0x88: OP_EQUALVERIFY
1197
- // - 0xac: OP_CHECKSIG
1198
- // which matches the P2PKH structure as per:
1199
- // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
1200
- bytes32 walletP2PKHScriptKeccak = keccak256(
1201
- abi.encodePacked(hex"1976a914", walletPubKeyHash, hex"88ac")
1202
- );
1203
- // The P2WPKH script has the byte format: <0x160014> <20-byte PKH>.
1204
- // According to https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1205
- // - 0x16: Byte length of the entire script
1206
- // - 0x00: OP_0
1207
- // - 0x14: Byte length of the public key hash
1208
- // which matches the P2WPKH structure as per:
1209
- // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
1210
- bytes32 walletP2WPKHScriptKeccak = keccak256(
1211
- abi.encodePacked(hex"160014", walletPubKeyHash)
1212
- );
1213
-
1214
- return
1215
- processRedemptionTxOutputs(
1216
- redemptionTxOutputVector,
1217
- walletPubKeyHash,
1218
- RedemptionTxOutputsProcessingInfo(
1219
- outputStartingIndex,
1220
- outputsCount,
1221
- walletP2PKHScriptKeccak,
1222
- walletP2WPKHScriptKeccak
1223
- )
1224
- );
1225
- }
1226
-
1227
- /// @notice Processes all outputs from the redemption transaction. Tries to
1228
- /// identify output as a change output, pending redemption request
1229
- // or reported redemption. Reverts if one of the outputs cannot be
1230
- /// recognized properly. Marks each request as processed by removing
1231
- /// them from `pendingRedemptions` mapping.
1232
- /// @param redemptionTxOutputVector Bitcoin redemption transaction output
1233
- /// vector. This function assumes vector's structure is valid so it
1234
- /// must be validated using e.g. `BTCUtils.validateVout` function
1235
- /// before it is passed here
1236
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1237
- // HASH160 over the compressed ECDSA public key) of the wallet which
1238
- /// performed the redemption transaction.
1239
- /// @param processInfo RedemptionTxOutputsProcessingInfo identifying output
1240
- /// starting index, the number of outputs and possible wallet change
1241
- /// P2PKH and P2WPKH scripts.
1242
- function processRedemptionTxOutputs(
1243
- bytes memory redemptionTxOutputVector,
1244
- bytes20 walletPubKeyHash,
1245
- RedemptionTxOutputsProcessingInfo memory processInfo
1246
- ) internal returns (RedemptionTxOutputsInfo memory resultInfo) {
1247
- // Helper variable that counts the number of processed redemption
1248
- // outputs. Redemptions can be either pending or reported as timed out.
1249
- // TODO: Revisit the approach with redemptions count according to
1250
- // https://github.com/keep-network/tbtc-v2/pull/128#discussion_r808237765
1251
- uint256 processedRedemptionsCount = 0;
1252
-
1253
- // Outputs processing loop.
1254
- for (uint256 i = 0; i < processInfo.outputsCount; i++) {
1255
- // TODO: Check if we can optimize gas costs by adding
1256
- // `extractValueAt` and `extractHashAt` in `bitcoin-spv-sol`
1257
- // in order to avoid allocating bytes in memory.
1258
- uint256 outputLength = redemptionTxOutputVector
1259
- .determineOutputLengthAt(processInfo.outputStartingIndex);
1260
- bytes memory output = redemptionTxOutputVector.slice(
1261
- processInfo.outputStartingIndex,
1262
- outputLength
1263
- );
1264
-
1265
- // Extract the value from given output.
1266
- uint64 outputValue = output.extractValue();
1267
- // The output consists of an 8-byte value and a variable length
1268
- // script. To extract that script we slice the output starting from
1269
- // 9th byte until the end.
1270
- bytes memory outputScript = output.slice(8, output.length - 8);
1271
-
1272
- if (
1273
- resultInfo.changeValue == 0 &&
1274
- (keccak256(outputScript) ==
1275
- processInfo.walletP2PKHScriptKeccak ||
1276
- keccak256(outputScript) ==
1277
- processInfo.walletP2WPKHScriptKeccak) &&
1278
- outputValue > 0
1279
- ) {
1280
- // If we entered here, that means the change output with a
1281
- // proper non-zero value was found.
1282
- resultInfo.changeIndex = uint32(i);
1283
- resultInfo.changeValue = outputValue;
1284
- } else {
1285
- // If we entered here, that the means the given output is
1286
- // supposed to represent a redemption.
1287
- (
1288
- uint64 burnableValue,
1289
- uint64 treasuryFee
1290
- ) = processNonChangeRedemptionTxOutput(
1291
- walletPubKeyHash,
1292
- outputScript,
1293
- outputValue
1294
- );
1295
- resultInfo.totalBurnableValue += burnableValue;
1296
- resultInfo.totalTreasuryFee += treasuryFee;
1297
- processedRedemptionsCount++;
1298
- }
1299
-
1300
- // Make the `outputStartingIndex` pointing to the next output by
1301
- // increasing it by current output's length.
1302
- processInfo.outputStartingIndex += outputLength;
1303
- }
1304
-
1305
- // Protect against the cases when there is only a single change output
1306
- // referring back to the wallet PKH and just burning main UTXO value
1307
- // for transaction fees.
1308
- require(
1309
- processedRedemptionsCount > 0,
1310
- "Redemption transaction must process at least one redemption"
1311
- );
1312
- }
1313
-
1314
- /// @notice Processes a single redemption transaction output. Tries to
1315
- /// identify output as a pending redemption request or reported
1316
- /// redemption timeout. Output script passed to this function must
1317
- /// not be the change output. Such output needs to be identified
1318
- /// separately before calling this function.
1319
- /// Reverts if output is neither requested pending redemption nor
1320
- /// requested and reported timed-out redemption.
1321
- /// This function also marks each pending request as processed by
1322
- /// removing it from `pendingRedemptions` mapping.
1323
- /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin
1324
- // HASH160 over the compressed ECDSA public key) of the wallet which
1325
- /// performed the redemption transaction.
1326
- /// @param outputScript Non-change output script to be processed
1327
- /// @param outputValue Value of the output being processed
1328
- /// @return burnableValue The value burnable as a result of processing this
1329
- /// single redemption output. This value needs to be summed up with
1330
- /// burnable values of all other outputs to evaluate total burnable
1331
- /// value for the entire redemption transaction. This value is 0
1332
- /// for a timed-out redemption request.
1333
- /// @return treasuryFee The treasury fee from this single redemption output.
1334
- /// This value needs to be summed up with treasury fees of all other
1335
- /// outputs to evaluate the total treasury fee for the entire
1336
- /// redemption transaction. This value is 0 for a timed-out
1337
- /// redemption request.
1338
- function processNonChangeRedemptionTxOutput(
1339
- bytes20 walletPubKeyHash,
1340
- bytes memory outputScript,
1341
- uint64 outputValue
1342
- ) internal returns (uint64 burnableValue, uint64 treasuryFee) {
1343
- // This function should be called only if the given output is
1344
- // supposed to represent a redemption. Build the redemption key
1345
- // to perform that check.
1346
- uint256 redemptionKey = uint256(
1347
- keccak256(abi.encodePacked(walletPubKeyHash, outputScript))
1348
- );
1349
-
1350
- if (pendingRedemptions[redemptionKey].requestedAt != 0) {
1351
- // If we entered here, that means the output was identified
1352
- // as a pending redemption request.
1353
- RedemptionRequest storage request = pendingRedemptions[
1354
- redemptionKey
1355
- ];
1356
- // Compute the request's redeemable amount as the requested
1357
- // amount reduced by the treasury fee. The request's
1358
- // minimal amount is then the redeemable amount reduced by
1359
- // the maximum transaction fee.
1360
- uint64 redeemableAmount = request.requestedAmount -
1361
- request.treasuryFee;
1362
- // Output value must fit between the request's redeemable
1363
- // and minimal amounts to be deemed valid.
1364
- require(
1365
- redeemableAmount - request.txMaxFee <= outputValue &&
1366
- outputValue <= redeemableAmount,
1367
- "Output value is not within the acceptable range of the pending request"
1368
- );
1369
- // Add the redeemable amount to the total burnable value
1370
- // the Bridge will use to decrease its balance in the Bank.
1371
- burnableValue = redeemableAmount;
1372
- // Add the request's treasury fee to the total treasury fee
1373
- // value the Bridge will transfer to the treasury.
1374
- treasuryFee = request.treasuryFee;
1375
- // Request was properly handled so remove its redemption
1376
- // key from the mapping to make it reusable for further
1377
- // requests.
1378
- delete pendingRedemptions[redemptionKey];
1379
- } else {
1380
- // If we entered here, the output is not a redemption
1381
- // request but there is still a chance the given output is
1382
- // related to a reported timed out redemption request.
1383
- // If so, check if the output value matches the request
1384
- // amount to confirm this is an overdue request fulfillment
1385
- // then bypass this output and process the subsequent
1386
- // ones. That also means the wallet was already punished
1387
- // for the inactivity. Otherwise, just revert.
1388
- RedemptionRequest storage request = timedOutRedemptions[
1389
- redemptionKey
1390
- ];
1391
-
1392
- require(
1393
- request.requestedAt != 0,
1394
- "Output is a non-requested redemption"
1395
- );
1396
-
1397
- uint64 redeemableAmount = request.requestedAmount -
1398
- request.treasuryFee;
1399
-
1400
- require(
1401
- redeemableAmount - request.txMaxFee <= outputValue &&
1402
- outputValue <= redeemableAmount,
1403
- "Output value is not within the acceptable range of the timed out request"
1404
- );
1405
- }
1406
747
  }
1407
748
 
1408
749
  /// @notice Notifies that there is a pending redemption request associated
@@ -1433,56 +774,11 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1433
774
  bytes20 walletPubKeyHash,
1434
775
  bytes calldata redeemerOutputScript
1435
776
  ) external {
1436
- uint256 redemptionKey = uint256(
1437
- keccak256(abi.encodePacked(walletPubKeyHash, redeemerOutputScript))
1438
- );
1439
- RedemptionRequest memory request = pendingRedemptions[redemptionKey];
1440
-
1441
- require(request.requestedAt > 0, "Redemption request does not exist");
1442
- require(
1443
- /* solhint-disable-next-line not-rely-on-time */
1444
- request.requestedAt + redemptionTimeout < block.timestamp,
1445
- "Redemption request has not timed out"
1446
- );
1447
-
1448
- // Update the wallet's pending redemptions value
1449
- Wallets.Wallet storage wallet = wallets.registeredWallets[
1450
- walletPubKeyHash
1451
- ];
1452
- wallet.pendingRedemptionsValue -=
1453
- request.requestedAmount -
1454
- request.treasuryFee;
1455
-
1456
- require(
1457
- // TODO: Allow the wallets in `Closing` state when the state is added
1458
- wallet.state == Wallets.WalletState.Live ||
1459
- wallet.state == Wallets.WalletState.MovingFunds ||
1460
- wallet.state == Wallets.WalletState.Terminated,
1461
- "The wallet must be in Live, MovingFunds or Terminated state"
777
+ self.notifyRedemptionTimeout(
778
+ wallets,
779
+ walletPubKeyHash,
780
+ redeemerOutputScript
1462
781
  );
1463
-
1464
- // It is worth noting that there is no need to check if
1465
- // `timedOutRedemption` mapping already contains the given redemption
1466
- // key. There is no possibility to re-use a key of a reported timed-out
1467
- // redemption because the wallet responsible for causing the timeout is
1468
- // moved to a state that prevents it to receive new redemption requests.
1469
-
1470
- // Move the redemption from pending redemptions to timed-out redemptions
1471
- timedOutRedemptions[redemptionKey] = request;
1472
- delete pendingRedemptions[redemptionKey];
1473
-
1474
- if (
1475
- wallet.state == Wallets.WalletState.Live ||
1476
- wallet.state == Wallets.WalletState.MovingFunds
1477
- ) {
1478
- // Propagate timeout consequences to the wallet
1479
- wallets.notifyRedemptionTimedOut(walletPubKeyHash);
1480
- }
1481
-
1482
- emit RedemptionTimedOut(walletPubKeyHash, redeemerOutputScript);
1483
-
1484
- // Return the requested amount of tokens to the redeemer
1485
- self.bank.transferBalance(request.redeemer, request.requestedAmount);
1486
782
  }
1487
783
 
1488
784
  /// @notice Used by the wallet to prove the BTC moving funds transaction
@@ -1536,195 +832,16 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1536
832
  BitcoinTx.UTXO calldata mainUtxo,
1537
833
  bytes20 walletPubKeyHash
1538
834
  ) external {
1539
- // The actual transaction proof is performed here. After that point, we
1540
- // can assume the transaction happened on Bitcoin chain and has
1541
- // a sufficient number of confirmations as determined by
1542
- // `txProofDifficultyFactor` constant.
1543
- bytes32 movingFundsTxHash = BitcoinTx.validateProof(
835
+ self.submitMovingFundsProof(
836
+ wallets,
1544
837
  movingFundsTx,
1545
838
  movingFundsProof,
1546
- self.proofDifficultyContext()
1547
- );
1548
-
1549
- // Process the moving funds transaction input. Specifically, check if
1550
- // it refers to the expected wallet's main UTXO.
1551
- processWalletOutboundTxInput(
1552
- movingFundsTx.inputVector,
1553
839
  mainUtxo,
1554
840
  walletPubKeyHash
1555
841
  );
1556
-
1557
- (
1558
- bytes32 targetWalletsHash,
1559
- uint256 outputsTotalValue
1560
- ) = processMovingFundsTxOutputs(movingFundsTx.outputVector);
1561
-
1562
- require(
1563
- mainUtxo.txOutputValue - outputsTotalValue <=
1564
- movingFundsTxMaxTotalFee,
1565
- "Transaction fee is too high"
1566
- );
1567
-
1568
- wallets.notifyFundsMoved(walletPubKeyHash, targetWalletsHash);
1569
-
1570
- emit MovingFundsCompleted(walletPubKeyHash, movingFundsTxHash);
1571
- }
1572
-
1573
- /// @notice Processes the moving funds Bitcoin transaction output vector
1574
- /// and extracts information required for further processing.
1575
- /// @param movingFundsTxOutputVector Bitcoin moving funds transaction output
1576
- /// vector. This function assumes vector's structure is valid so it
1577
- /// must be validated using e.g. `BTCUtils.validateVout` function
1578
- /// before it is passed here
1579
- /// @return targetWalletsHash keccak256 hash over the list of actual
1580
- /// target wallets used in the transaction.
1581
- /// @return outputsTotalValue Sum of all outputs values.
1582
- /// @dev Requirements:
1583
- /// - The `movingFundsTxOutputVector` must be parseable, i.e. must
1584
- /// be validated by the caller as stated in their parameter doc.
1585
- /// - Each output must refer to a 20-byte public key hash.
1586
- /// - The total outputs value must be evenly divided over all outputs.
1587
- function processMovingFundsTxOutputs(bytes memory movingFundsTxOutputVector)
1588
- internal
1589
- view
1590
- returns (bytes32 targetWalletsHash, uint256 outputsTotalValue)
1591
- {
1592
- // Determining the total number of Bitcoin transaction outputs in
1593
- // the same way as for number of inputs. See `BitcoinTx.outputVector`
1594
- // docs for more details.
1595
- (
1596
- uint256 outputsCompactSizeUintLength,
1597
- uint256 outputsCount
1598
- ) = movingFundsTxOutputVector.parseVarInt();
1599
-
1600
- // To determine the first output starting index, we must jump over
1601
- // the compactSize uint which prepends the output vector. One byte
1602
- // must be added because `BtcUtils.parseVarInt` does not include
1603
- // compactSize uint tag in the returned length.
1604
- //
1605
- // For >= 0 && <= 252, `BTCUtils.determineVarIntDataLengthAt`
1606
- // returns `0`, so we jump over one byte of compactSize uint.
1607
- //
1608
- // For >= 253 && <= 0xffff there is `0xfd` tag,
1609
- // `BTCUtils.determineVarIntDataLengthAt` returns `2` (no
1610
- // tag byte included) so we need to jump over 1+2 bytes of
1611
- // compactSize uint.
1612
- //
1613
- // Please refer `BTCUtils` library and compactSize uint
1614
- // docs in `BitcoinTx` library for more details.
1615
- uint256 outputStartingIndex = 1 + outputsCompactSizeUintLength;
1616
-
1617
- bytes20[] memory targetWallets = new bytes20[](outputsCount);
1618
- uint64[] memory outputsValues = new uint64[](outputsCount);
1619
-
1620
- // Outputs processing loop.
1621
- for (uint256 i = 0; i < outputsCount; i++) {
1622
- uint256 outputLength = movingFundsTxOutputVector
1623
- .determineOutputLengthAt(outputStartingIndex);
1624
-
1625
- bytes memory output = movingFundsTxOutputVector.slice(
1626
- outputStartingIndex,
1627
- outputLength
1628
- );
1629
-
1630
- // Extract the output script payload.
1631
- bytes memory targetWalletPubKeyHashBytes = output.extractHash();
1632
- // Output script payload must refer to a known wallet public key
1633
- // hash which is always 20-byte.
1634
- require(
1635
- targetWalletPubKeyHashBytes.length == 20,
1636
- "Target wallet public key hash must have 20 bytes"
1637
- );
1638
-
1639
- bytes20 targetWalletPubKeyHash = targetWalletPubKeyHashBytes
1640
- .slice20(0);
1641
-
1642
- // The next step is making sure that the 20-byte public key hash
1643
- // is actually used in the right context of a P2PKH or P2WPKH
1644
- // output. To do so, we must extract the full script from the output
1645
- // and compare with the expected P2PKH and P2WPKH scripts
1646
- // referring to that 20-byte public key hash. The output consists
1647
- // of an 8-byte value and a variable length script. To extract the
1648
- // script we slice the output starting from 9th byte until the end.
1649
- bytes32 outputScriptKeccak = keccak256(
1650
- output.slice(8, output.length - 8)
1651
- );
1652
- // Build the expected P2PKH script which has the following byte
1653
- // format: <0x1976a914> <20-byte PKH> <0x88ac>. According to
1654
- // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1655
- // - 0x19: Byte length of the entire script
1656
- // - 0x76: OP_DUP
1657
- // - 0xa9: OP_HASH160
1658
- // - 0x14: Byte length of the public key hash
1659
- // - 0x88: OP_EQUALVERIFY
1660
- // - 0xac: OP_CHECKSIG
1661
- // which matches the P2PKH structure as per:
1662
- // https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash
1663
- bytes32 targetWalletP2PKHScriptKeccak = keccak256(
1664
- abi.encodePacked(
1665
- hex"1976a914",
1666
- targetWalletPubKeyHash,
1667
- hex"88ac"
1668
- )
1669
- );
1670
- // Build the expected P2WPKH script which has the following format:
1671
- // <0x160014> <20-byte PKH>. According to
1672
- // https://en.bitcoin.it/wiki/Script#Opcodes this translates to:
1673
- // - 0x16: Byte length of the entire script
1674
- // - 0x00: OP_0
1675
- // - 0x14: Byte length of the public key hash
1676
- // which matches the P2WPKH structure as per:
1677
- // https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH
1678
- bytes32 targetWalletP2WPKHScriptKeccak = keccak256(
1679
- abi.encodePacked(hex"160014", targetWalletPubKeyHash)
1680
- );
1681
- // Make sure the actual output script matches either the P2PKH
1682
- // or P2WPKH format.
1683
- require(
1684
- outputScriptKeccak == targetWalletP2PKHScriptKeccak ||
1685
- outputScriptKeccak == targetWalletP2WPKHScriptKeccak,
1686
- "Output must be P2PKH or P2WPKH"
1687
- );
1688
-
1689
- // Add the wallet public key hash to the list that will be used
1690
- // to build the result list hash. There is no need to check if
1691
- // given output is a change here because the actual target wallet
1692
- // list must be exactly the same as the pre-committed target wallet
1693
- // list which is guaranteed to be valid.
1694
- targetWallets[i] = targetWalletPubKeyHash;
1695
-
1696
- // Extract the value from given output.
1697
- outputsValues[i] = output.extractValue();
1698
- outputsTotalValue += outputsValues[i];
1699
-
1700
- // Make the `outputStartingIndex` pointing to the next output by
1701
- // increasing it by current output's length.
1702
- outputStartingIndex += outputLength;
1703
- }
1704
-
1705
- // Compute the indivisible remainder that remains after dividing the
1706
- // outputs total value over all outputs evenly.
1707
- uint256 outputsTotalValueRemainder = outputsTotalValue % outputsCount;
1708
- // Compute the minimum allowed output value by dividing the outputs
1709
- // total value (reduced by the remainder) by the number of outputs.
1710
- uint256 minOutputValue = (outputsTotalValue -
1711
- outputsTotalValueRemainder) / outputsCount;
1712
- // Maximum possible value is the minimum value with the remainder included.
1713
- uint256 maxOutputValue = minOutputValue + outputsTotalValueRemainder;
1714
-
1715
- for (uint256 i = 0; i < outputsCount; i++) {
1716
- require(
1717
- minOutputValue <= outputsValues[i] &&
1718
- outputsValues[i] <= maxOutputValue,
1719
- "Transaction amount is not distributed evenly"
1720
- );
1721
- }
1722
-
1723
- targetWalletsHash = keccak256(abi.encodePacked(targetWallets));
1724
-
1725
- return (targetWalletsHash, outputsTotalValue);
1726
842
  }
1727
843
 
844
+ /// @notice Returns the addresses of contracts Bridge is interacting with.
1728
845
  /// @return bank Address of the Bank the Bridge belongs to.
1729
846
  /// @return relay Address of the Bitcoin relay providing the current Bitcoin
1730
847
  /// network difficulty.
@@ -1772,6 +889,68 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1772
889
  txProofDifficultyFactor = self.txProofDifficultyFactor;
1773
890
  }
1774
891
 
892
+ /// @notice Returns the current values of Bridge redemption parameters.
893
+ /// @return redemptionDustThreshold The minimal amount that can be requested
894
+ /// for redemption. Value of this parameter must take into account
895
+ /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
896
+ /// parameters in order to make requests that can incur the
897
+ /// treasury and transaction fee and still satisfy the redeemer.
898
+ /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury
899
+ /// fee taken from each redemption request and transferred to the
900
+ /// treasury upon successful request finalization. That fee is
901
+ /// computed as follows:
902
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
903
+ /// For example, if the treasury fee needs to be 2% of each
904
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
905
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
906
+ /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that
907
+ /// can be incurred by each redemption request being part of the
908
+ /// given redemption transaction. If the maximum BTC transaction
909
+ /// fee is exceeded, such transaction is considered a fraud.
910
+ /// @return redemptionTimeout Time after which the redemption request can be
911
+ /// reported as timed out. It is counted from the moment when the
912
+ /// redemption request was created via `requestRedemption` call.
913
+ /// Reported timed out requests are cancelled and locked TBTC is
914
+ /// returned to the redeemer in full amount.
915
+ /// @return treasury Address where the redemption treasury fees will be
916
+ /// sent to. Treasury takes part in the operators rewarding process.
917
+ /// @return txProofDifficultyFactor The number of confirmations on the
918
+ /// Bitcoin chain required to successfully evaluate an SPV proof.
919
+ function redemptionParameters()
920
+ external
921
+ view
922
+ returns (
923
+ uint64 redemptionDustThreshold,
924
+ uint64 redemptionTreasuryFeeDivisor,
925
+ uint64 redemptionTxMaxFee,
926
+ uint256 redemptionTimeout,
927
+ address treasury,
928
+ uint256 txProofDifficultyFactor
929
+ )
930
+ {
931
+ redemptionDustThreshold = self.redemptionDustThreshold;
932
+ redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;
933
+ redemptionTxMaxFee = self.redemptionTxMaxFee;
934
+ redemptionTimeout = self.redemptionTimeout;
935
+ treasury = self.treasury;
936
+ txProofDifficultyFactor = self.txProofDifficultyFactor;
937
+ }
938
+
939
+ /// @notice Returns the current values of Bridge moving funds between
940
+ /// wallets parameters.
941
+ /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC
942
+ /// transaction fee that is acceptable in a single moving funds
943
+ /// transaction. This is a _total_ max fee for the entire moving
944
+ /// funds transaction.
945
+ function movingFundsParameters()
946
+ external
947
+ view
948
+ returns (uint64 movingFundsTxMaxTotalFee)
949
+ {
950
+ // TODO: we will have more parameters here, for example moving funds timeout
951
+ movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;
952
+ }
953
+
1775
954
  /// @notice Indicates if the vault with the given address is trusted or not.
1776
955
  /// Depositors can route their revealed deposits only to trusted
1777
956
  /// vaults and have trusted vaults notified about new deposits as
@@ -1794,7 +973,6 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1794
973
  view
1795
974
  returns (Deposit.Request memory)
1796
975
  {
1797
- // TODO: rename to getDeposit?
1798
976
  return self.deposits[depositKey];
1799
977
  }
1800
978
 
@@ -1807,4 +985,47 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1807
985
  function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {
1808
986
  return self.spentMainUTXOs[utxoKey];
1809
987
  }
988
+
989
+ /// @notice Collection of all pending redemption requests indexed by
990
+ /// redemption key built as
991
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
992
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
993
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
994
+ /// public key) and redeemerOutputScript is a Bitcoin script
995
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
996
+ /// redeemed BTC as requested by the redeemer. Requests are added
997
+ /// to this mapping by the `requestRedemption` method (duplicates
998
+ /// not allowed) and are removed by one of the following methods:
999
+ /// - `submitRedemptionProof` in case the request was handled
1000
+ /// successfully
1001
+ /// - `notifyRedemptionTimeout` in case the request was reported
1002
+ /// to be timed out
1003
+ function pendingRedemptions(uint256 redemptionKey)
1004
+ external
1005
+ view
1006
+ returns (Redeem.RedemptionRequest memory)
1007
+ {
1008
+ return self.pendingRedemptions[redemptionKey];
1009
+ }
1010
+
1011
+ /// @notice Collection of all timed out redemptions requests indexed by
1012
+ /// redemption key built as
1013
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1014
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1015
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1016
+ /// public key) and redeemerOutputScript is the Bitcoin script
1017
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
1018
+ /// out request. Timed out requests are stored in this mapping to
1019
+ /// avoid slashing the wallets multiple times for the same timeout.
1020
+ /// Only one method can add to this mapping:
1021
+ /// - `notifyRedemptionTimeout` which puts the redemption key
1022
+ /// to this mapping basing on a timed out request stored
1023
+ /// previously in `pendingRedemptions` mapping.
1024
+ function timedOutRedemptions(uint256 redemptionKey)
1025
+ external
1026
+ view
1027
+ returns (Redeem.RedemptionRequest memory)
1028
+ {
1029
+ return self.timedOutRedemptions[redemptionKey];
1030
+ }
1810
1031
  }