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

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 (32) 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 → e22260bedca047fea8676977de0ef137.json} +6 -3
  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/Bridge.sol/Bridge.dbg.json +1 -1
  9. package/build/contracts/bridge/Bridge.sol/Bridge.json +147 -131
  10. package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
  11. package/build/contracts/bridge/BridgeState.sol/BridgeState.json +2 -2
  12. package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
  13. package/build/contracts/bridge/Deposit.sol/Deposit.json +2 -2
  14. package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
  15. package/build/contracts/bridge/Frauds.sol/Frauds.dbg.json +1 -1
  16. package/build/contracts/bridge/Frauds.sol/Frauds.json +2 -2
  17. package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
  18. package/build/contracts/bridge/Redeem.sol/OutboundTx.dbg.json +4 -0
  19. package/build/contracts/bridge/Redeem.sol/OutboundTx.json +10 -0
  20. package/build/contracts/bridge/Redeem.sol/Redeem.dbg.json +4 -0
  21. package/build/contracts/bridge/Redeem.sol/Redeem.json +126 -0
  22. package/build/contracts/bridge/Sweep.sol/Sweep.dbg.json +1 -1
  23. package/build/contracts/bridge/Sweep.sol/Sweep.json +2 -2
  24. package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
  25. package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
  26. package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
  27. package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
  28. package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
  29. package/contracts/bridge/Bridge.sol +114 -719
  30. package/contracts/bridge/BridgeState.sol +60 -0
  31. package/contracts/bridge/Redeem.sol +849 -0
  32. package/package.json +1 -1
@@ -26,6 +26,7 @@ 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";
@@ -53,14 +54,15 @@ import "../bank/Bank.sol";
53
54
  /// balances in the Bank.
54
55
  /// @dev Bridge is an upgradeable component of the Bank.
55
56
  ///
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.
57
+ // TODO: All wallets-related operations that are currently done directly
58
+ // by the Bridge can be probably delegated to the Wallets library.
59
+ // Examples of such operations are main UTXO or pending redemptions
60
+ // value updates.
60
61
  contract Bridge is Ownable, EcdsaWalletOwner {
61
62
  using BridgeState for BridgeState.Storage;
62
63
  using Deposit for BridgeState.Storage;
63
64
  using Sweep for BridgeState.Storage;
65
+ using Redeem for BridgeState.Storage;
64
66
  using Frauds for Frauds.Data;
65
67
  using Wallets for Wallets.Data;
66
68
 
@@ -68,91 +70,8 @@ contract Bridge is Ownable, EcdsaWalletOwner {
68
70
  using BTCUtils for uint256;
69
71
  using BytesLib for bytes;
70
72
 
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
73
  BridgeState.Storage internal self;
121
74
 
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
75
  /// TODO: Make it governable.
157
76
  /// @notice Maximum amount of the total BTC transaction fee that is
158
77
  /// acceptable in a single moving funds transaction.
@@ -162,37 +81,6 @@ contract Bridge is Ownable, EcdsaWalletOwner {
162
81
  /// for the entire transaction.
163
82
  uint64 public movingFundsTxMaxTotalFee;
164
83
 
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
84
  /// @notice Contains parameters related to frauds and the collection of all
197
85
  /// submitted fraud challenges.
198
86
  Frauds.Data internal frauds;
@@ -322,10 +210,10 @@ contract Bridge is Ownable, EcdsaWalletOwner {
322
210
  self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
323
211
  self.depositTxMaxFee = 10000; // 10000 satoshi
324
212
  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
213
+ self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC
214
+ self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
215
+ self.redemptionTxMaxFee = 10000; // 10000 satoshi
216
+ self.redemptionTimeout = 172800; // 48 hours
329
217
  movingFundsTxMaxTotalFee = 10000; // 10000 satoshi
330
218
 
331
219
  // TODO: Revisit initial values.
@@ -797,123 +685,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
797
685
  bytes calldata redeemerOutputScript,
798
686
  uint64 amount
799
687
  ) 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(
688
+ self.requestRedemption(
689
+ wallets,
908
690
  walletPubKeyHash,
691
+ mainUtxo,
909
692
  redeemerOutputScript,
910
- msg.sender,
911
- amount,
912
- treasuryFee,
913
- txMaxFee
693
+ amount
914
694
  );
915
-
916
- self.bank.transferBalanceFrom(msg.sender, address(this), amount);
917
695
  }
918
696
 
919
697
  /// @notice Used by the wallet to prove the BTC redemption transaction
@@ -966,443 +744,13 @@ contract Bridge is Ownable, EcdsaWalletOwner {
966
744
  BitcoinTx.UTXO calldata mainUtxo,
967
745
  bytes20 walletPubKeyHash
968
746
  ) 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(
747
+ self.submitRedemptionProof(
748
+ wallets,
978
749
  redemptionTx,
979
750
  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
751
  mainUtxo,
988
752
  walletPubKeyHash
989
753
  );
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
754
  }
1407
755
 
1408
756
  /// @notice Notifies that there is a pending redemption request associated
@@ -1433,56 +781,11 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1433
781
  bytes20 walletPubKeyHash,
1434
782
  bytes calldata redeemerOutputScript
1435
783
  ) 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"
784
+ self.notifyRedemptionTimeout(
785
+ wallets,
786
+ walletPubKeyHash,
787
+ redeemerOutputScript
1462
788
  );
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
789
  }
1487
790
 
1488
791
  /// @notice Used by the wallet to prove the BTC moving funds transaction
@@ -1548,7 +851,9 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1548
851
 
1549
852
  // Process the moving funds transaction input. Specifically, check if
1550
853
  // it refers to the expected wallet's main UTXO.
1551
- processWalletOutboundTxInput(
854
+ OutboundTx.processWalletOutboundTxInput(
855
+ self,
856
+ wallets,
1552
857
  movingFundsTx.inputVector,
1553
858
  mainUtxo,
1554
859
  walletPubKeyHash
@@ -1725,6 +1030,7 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1725
1030
  return (targetWalletsHash, outputsTotalValue);
1726
1031
  }
1727
1032
 
1033
+ /// @notice Returns the addresses of contracts Bridge is interacting with.
1728
1034
  /// @return bank Address of the Bank the Bridge belongs to.
1729
1035
  /// @return relay Address of the Bitcoin relay providing the current Bitcoin
1730
1036
  /// network difficulty.
@@ -1772,6 +1078,53 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1772
1078
  txProofDifficultyFactor = self.txProofDifficultyFactor;
1773
1079
  }
1774
1080
 
1081
+ /// @notice Returns the current values of Bridge redemption parameters.
1082
+ /// @return redemptionDustThreshold The minimal amount that can be requested
1083
+ /// for redemption. Value of this parameter must take into account
1084
+ /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`
1085
+ /// parameters in order to make requests that can incur the
1086
+ /// treasury and transaction fee and still satisfy the redeemer.
1087
+ /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury
1088
+ /// fee taken from each redemption request and transferred to the
1089
+ /// treasury upon successful request finalization. That fee is
1090
+ /// computed as follows:
1091
+ /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`
1092
+ /// For example, if the treasury fee needs to be 2% of each
1093
+ /// redemption request, the `redemptionTreasuryFeeDivisor` should
1094
+ /// be set to `50` because `1/50 = 0.02 = 2%`.
1095
+ /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that
1096
+ /// can be incurred by each redemption request being part of the
1097
+ /// given redemption transaction. If the maximum BTC transaction
1098
+ /// fee is exceeded, such transaction is considered a fraud.
1099
+ /// @return redemptionTimeout Time after which the redemption request can be
1100
+ /// reported as timed out. It is counted from the moment when the
1101
+ /// redemption request was created via `requestRedemption` call.
1102
+ /// Reported timed out requests are cancelled and locked TBTC is
1103
+ /// returned to the redeemer in full amount.
1104
+ /// @return treasury Address where the redemption treasury fees will be
1105
+ /// sent to. Treasury takes part in the operators rewarding process.
1106
+ /// @return txProofDifficultyFactor The number of confirmations on the
1107
+ /// Bitcoin chain required to successfully evaluate an SPV proof.
1108
+ function redemptionParameters()
1109
+ external
1110
+ view
1111
+ returns (
1112
+ uint64 redemptionDustThreshold,
1113
+ uint64 redemptionTreasuryFeeDivisor,
1114
+ uint64 redemptionTxMaxFee,
1115
+ uint256 redemptionTimeout,
1116
+ address treasury,
1117
+ uint256 txProofDifficultyFactor
1118
+ )
1119
+ {
1120
+ redemptionDustThreshold = self.redemptionDustThreshold;
1121
+ redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;
1122
+ redemptionTxMaxFee = self.redemptionTxMaxFee;
1123
+ redemptionTimeout = self.redemptionTimeout;
1124
+ treasury = self.treasury;
1125
+ txProofDifficultyFactor = self.txProofDifficultyFactor;
1126
+ }
1127
+
1775
1128
  /// @notice Indicates if the vault with the given address is trusted or not.
1776
1129
  /// Depositors can route their revealed deposits only to trusted
1777
1130
  /// vaults and have trusted vaults notified about new deposits as
@@ -1794,7 +1147,6 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1794
1147
  view
1795
1148
  returns (Deposit.Request memory)
1796
1149
  {
1797
- // TODO: rename to getDeposit?
1798
1150
  return self.deposits[depositKey];
1799
1151
  }
1800
1152
 
@@ -1807,4 +1159,47 @@ contract Bridge is Ownable, EcdsaWalletOwner {
1807
1159
  function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {
1808
1160
  return self.spentMainUTXOs[utxoKey];
1809
1161
  }
1162
+
1163
+ /// @notice Collection of all pending redemption requests indexed by
1164
+ /// redemption key built as
1165
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1166
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1167
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1168
+ /// public key) and redeemerOutputScript is a Bitcoin script
1169
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock
1170
+ /// redeemed BTC as requested by the redeemer. Requests are added
1171
+ /// to this mapping by the `requestRedemption` method (duplicates
1172
+ /// not allowed) and are removed by one of the following methods:
1173
+ /// - `submitRedemptionProof` in case the request was handled
1174
+ /// successfully
1175
+ /// - `notifyRedemptionTimeout` in case the request was reported
1176
+ /// to be timed out
1177
+ function pendingRedemptions(uint256 redemptionKey)
1178
+ external
1179
+ view
1180
+ returns (Redeem.RedemptionRequest memory)
1181
+ {
1182
+ return self.pendingRedemptions[redemptionKey];
1183
+ }
1184
+
1185
+ /// @notice Collection of all timed out redemptions requests indexed by
1186
+ /// redemption key built as
1187
+ /// keccak256(walletPubKeyHash | redeemerOutputScript). The
1188
+ /// walletPubKeyHash is the 20-byte wallet's public key hash
1189
+ /// (computed using Bitcoin HASH160 over the compressed ECDSA
1190
+ /// public key) and redeemerOutputScript is the Bitcoin script
1191
+ /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed
1192
+ /// out request. Timed out requests are stored in this mapping to
1193
+ /// avoid slashing the wallets multiple times for the same timeout.
1194
+ /// Only one method can add to this mapping:
1195
+ /// - `notifyRedemptionTimeout` which puts the redemption key
1196
+ /// to this mapping basing on a timed out request stored
1197
+ /// previously in `pendingRedemptions` mapping.
1198
+ function timedOutRedemptions(uint256 redemptionKey)
1199
+ external
1200
+ view
1201
+ returns (Redeem.RedemptionRequest memory)
1202
+ {
1203
+ return self.timedOutRedemptions[redemptionKey];
1204
+ }
1810
1205
  }