@atomiqlabs/lp-lib 13.0.0-beta.9 → 13.0.0

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 (160) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +40 -40
  5. package/dist/index.js +56 -56
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +61 -61
  8. package/dist/plugins/IPlugin.d.ts +143 -143
  9. package/dist/plugins/IPlugin.js +34 -34
  10. package/dist/plugins/PluginManager.d.ts +112 -112
  11. package/dist/plugins/PluginManager.js +259 -259
  12. package/dist/prices/BinanceSwapPrice.d.ts +26 -26
  13. package/dist/prices/BinanceSwapPrice.js +92 -92
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +30 -30
  15. package/dist/prices/CoinGeckoSwapPrice.js +64 -64
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +26 -26
  19. package/dist/prices/OKXSwapPrice.js +92 -92
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +18 -18
  23. package/dist/storagemanager/IntermediaryStorageManager.js +104 -104
  24. package/dist/storagemanager/StorageManager.d.ts +12 -12
  25. package/dist/storagemanager/StorageManager.js +57 -57
  26. package/dist/swaps/SwapHandler.d.ts +156 -156
  27. package/dist/swaps/SwapHandler.js +163 -163
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +72 -72
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +172 -172
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +51 -51
  39. package/dist/swaps/escrow/EscrowHandler.js +158 -158
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +101 -101
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +207 -207
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +83 -83
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +107 -107
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +648 -648
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +32 -32
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +88 -88
  58. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +171 -171
  59. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +702 -702
  60. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
  61. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
  62. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  63. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +857 -857
  64. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +23 -23
  65. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +56 -56
  66. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -41
  67. package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
  68. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
  69. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  70. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  71. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +488 -478
  72. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +57 -57
  73. package/dist/swaps/spv_vault_swap/SpvVaults.js +369 -369
  74. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  75. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  76. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  77. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  78. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
  79. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +495 -495
  80. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  81. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  82. package/dist/utils/Utils.d.ts +29 -29
  83. package/dist/utils/Utils.js +88 -88
  84. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  85. package/dist/utils/paramcoders/IParamReader.js +2 -2
  86. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  87. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  88. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  89. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  90. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  91. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  92. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  93. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  94. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  95. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  96. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  97. package/dist/utils/paramcoders/server/ServerParamDecoder.js +105 -105
  98. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  99. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  100. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  101. package/dist/wallets/IBitcoinWallet.js +2 -2
  102. package/dist/wallets/ILightningWallet.d.ts +117 -117
  103. package/dist/wallets/ILightningWallet.js +37 -37
  104. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  105. package/dist/wallets/ISpvVaultSigner.js +2 -2
  106. package/dist/wallets/ISpvVaultWallet.d.ts +42 -42
  107. package/dist/wallets/ISpvVaultWallet.js +2 -2
  108. package/package.json +36 -36
  109. package/src/fees/IBtcFeeEstimator.ts +6 -6
  110. package/src/index.ts +51 -51
  111. package/src/info/InfoHandler.ts +106 -106
  112. package/src/plugins/IPlugin.ts +168 -168
  113. package/src/plugins/PluginManager.ts +336 -336
  114. package/src/prices/BinanceSwapPrice.ts +113 -113
  115. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  116. package/src/prices/ISwapPrice.ts +88 -88
  117. package/src/prices/OKXSwapPrice.ts +113 -113
  118. package/src/storage/IIntermediaryStorage.ts +19 -19
  119. package/src/storagemanager/IntermediaryStorageManager.ts +109 -109
  120. package/src/storagemanager/StorageManager.ts +68 -68
  121. package/src/swaps/SwapHandler.ts +280 -280
  122. package/src/swaps/SwapHandlerSwap.ts +141 -141
  123. package/src/swaps/assertions/AmountAssertions.ts +76 -76
  124. package/src/swaps/assertions/FromBtcAmountAssertions.ts +238 -238
  125. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  126. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  127. package/src/swaps/escrow/EscrowHandler.ts +179 -179
  128. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  129. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  130. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +283 -283
  131. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  132. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  133. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  134. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  135. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +828 -828
  136. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +137 -137
  137. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +876 -876
  138. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
  139. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1107 -1107
  140. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +77 -77
  141. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
  142. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
  143. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +624 -613
  144. package/src/swaps/spv_vault_swap/SpvVaults.ts +440 -440
  145. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  146. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  147. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +592 -592
  148. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  149. package/src/utils/Utils.ts +102 -102
  150. package/src/utils/paramcoders/IParamReader.ts +7 -7
  151. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  152. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  153. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  154. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  155. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  156. package/src/utils/paramcoders/server/ServerParamDecoder.ts +115 -115
  157. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  158. package/src/wallets/IBitcoinWallet.ts +68 -68
  159. package/src/wallets/ILightningWallet.ts +178 -178
  160. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,702 +1,702 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ToBtcAbs = void 0;
4
- const ToBtcSwapAbs_1 = require("./ToBtcSwapAbs");
5
- const SwapHandler_1 = require("../../SwapHandler");
6
- const base_1 = require("@atomiqlabs/base");
7
- const Utils_1 = require("../../../utils/Utils");
8
- const PluginManager_1 = require("../../../plugins/PluginManager");
9
- const crypto_1 = require("crypto");
10
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
- const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
- const ToBtcBaseSwapHandler_1 = require("../ToBtcBaseSwapHandler");
13
- const promise_queue_ts_1 = require("promise-queue-ts");
14
- const OUTPUT_SCRIPT_MAX_LENGTH = 200;
15
- /**
16
- * Handler for to BTC swaps, utilizing PTLCs (proof-time locked contracts) using btc relay (on-chain bitcoin SPV)
17
- */
18
- class ToBtcAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
19
- constructor(storageDirectory, path, chainData, bitcoin, swapPricing, bitcoinRpc, config) {
20
- super(storageDirectory, path, chainData, swapPricing, config);
21
- this.type = SwapHandler_1.SwapHandlerType.TO_BTC;
22
- this.swapType = base_1.ChainSwapType.CHAIN_NONCED;
23
- this.activeSubscriptions = {};
24
- this.sendBtcQueue = new promise_queue_ts_1.PromiseQueue();
25
- this.bitcoinRpc = bitcoinRpc;
26
- this.bitcoin = bitcoin;
27
- this.config = config;
28
- }
29
- /**
30
- * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
31
- *
32
- * @param chainIdentifier
33
- * @param address
34
- * @param confirmations
35
- * @param nonce
36
- * @param amount
37
- */
38
- getHash(chainIdentifier, address, confirmations, nonce, amount) {
39
- const parsedOutputScript = this.bitcoin.toOutputScript(address);
40
- const { swapContract } = this.getChain(chainIdentifier);
41
- return swapContract.getHashForOnchain(parsedOutputScript, amount, confirmations, nonce);
42
- }
43
- /**
44
- * Tries to claim the swap after our transaction was confirmed
45
- *
46
- * @param tx
47
- * @param swap
48
- * @param vout
49
- */
50
- async tryClaimSwap(tx, swap, vout) {
51
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
52
- const blockHeader = await this.bitcoinRpc.getBlockHeader(tx.blockhash);
53
- //Set flag that we are sending the transaction already, so we don't end up with race condition
54
- const unlock = swap.lock(swapContract.claimWithTxDataTimeout);
55
- if (unlock == null)
56
- return false;
57
- try {
58
- this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout);
59
- const result = await swapContract.claimWithTxData(signer, swap.data, { ...tx, height: blockHeader.getHeight() }, swap.requiredConfirmations, vout, null, null, false, {
60
- waitForConfirmation: true
61
- });
62
- this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout + " address: " + swap.address);
63
- if (swap.metadata != null)
64
- swap.metadata.times.txClaimed = Date.now();
65
- unlock();
66
- return true;
67
- }
68
- catch (e) {
69
- this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout + " address: " + swap.address, e);
70
- return false;
71
- }
72
- }
73
- async processPastSwap(swap) {
74
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
75
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
76
- const isSignatureExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
77
- if (isSignatureExpired) {
78
- const isCommitted = await swapContract.isCommited(swap.data);
79
- if (!isCommitted) {
80
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, address: " + swap.address);
81
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CANCELED);
82
- }
83
- else {
84
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), address: " + swap.address);
85
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
86
- await this.saveSwapData(swap);
87
- }
88
- return;
89
- }
90
- }
91
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
92
- if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
93
- this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE|SAVED): swap expired, cancelling, address: " + swap.address);
94
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CANCELED);
95
- return;
96
- }
97
- }
98
- //Sanity check for sent swaps
99
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT) {
100
- const isCommited = await swapContract.isCommited(swap.data);
101
- if (!isCommited) {
102
- const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
103
- if (status === base_1.SwapCommitStatus.PAID) {
104
- this.swapLogger.info(swap, "processPastSwap(state=BTC_SENT): swap claimed (detected from processPastSwap), address: " + swap.address);
105
- this.unsubscribePayment(swap);
106
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CLAIMED);
107
- }
108
- else if (status === base_1.SwapCommitStatus.EXPIRED) {
109
- this.swapLogger.warn(swap, "processPastSwap(state=BTC_SENT): swap expired, but bitcoin was probably already sent, txId: " + swap.txId + " address: " + swap.address);
110
- this.unsubscribePayment(swap);
111
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.REFUNDED);
112
- }
113
- return;
114
- }
115
- }
116
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT) {
117
- await this.processInitialized(swap);
118
- return;
119
- }
120
- }
121
- /**
122
- * Checks past swaps, deletes ones that are already expired.
123
- */
124
- async processPastSwaps() {
125
- const queriedData = await this.storageManager.query([
126
- {
127
- key: "state",
128
- values: [
129
- ToBtcSwapAbs_1.ToBtcSwapState.SAVED,
130
- ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE,
131
- ToBtcSwapAbs_1.ToBtcSwapState.COMMITED,
132
- ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING,
133
- ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT,
134
- ]
135
- }
136
- ]);
137
- for (let { obj: swap } of queriedData) {
138
- await this.processPastSwap(swap);
139
- }
140
- }
141
- async processBtcTx(swap, tx) {
142
- tx.confirmations = tx.confirmations || 0;
143
- //Check transaction has enough confirmations
144
- const hasEnoughConfirmations = tx.confirmations >= swap.requiredConfirmations;
145
- if (!hasEnoughConfirmations) {
146
- return false;
147
- }
148
- this.swapLogger.debug(swap, "processBtcTx(): address: " + swap.address + " amount: " + swap.amount.toString(10) + " btcTx: " + tx);
149
- //Search for required transaction output (vout)
150
- const outputScript = this.bitcoin.toOutputScript(swap.address);
151
- const vout = tx.outs.find(e => BigInt(e.value) === swap.amount && Buffer.from(e.scriptPubKey.hex, "hex").equals(outputScript));
152
- if (vout == null) {
153
- this.swapLogger.warn(swap, "processBtcTx(): cannot find correct vout," +
154
- " required output script: " + outputScript.toString("hex") +
155
- " required amount: " + swap.amount.toString(10) +
156
- " vouts: ", tx.outs);
157
- return false;
158
- }
159
- if (swap.metadata != null)
160
- swap.metadata.times.payTxConfirmed = Date.now();
161
- const success = await this.tryClaimSwap(tx, swap, vout.n);
162
- return success;
163
- }
164
- /**
165
- * Checks active sent out bitcoin transactions
166
- */
167
- async processBtcTxs() {
168
- const unsubscribeSwaps = [];
169
- for (let txId in this.activeSubscriptions) {
170
- const swap = this.activeSubscriptions[txId];
171
- //TODO: RBF the transaction if it's already taking too long to confirm
172
- try {
173
- let tx = await this.bitcoin.getWalletTransaction(txId);
174
- if (tx == null)
175
- continue;
176
- if (await this.processBtcTx(swap, tx)) {
177
- this.swapLogger.info(swap, "processBtcTxs(): swap claimed successfully, txId: " + tx.txid + " address: " + swap.address);
178
- unsubscribeSwaps.push(swap);
179
- }
180
- }
181
- catch (e) {
182
- this.swapLogger.error(swap, "processBtcTxs(): error processing btc transaction", e);
183
- }
184
- }
185
- unsubscribeSwaps.forEach(swap => {
186
- this.unsubscribePayment(swap);
187
- });
188
- }
189
- /**
190
- * Subscribes to and periodically checks txId used to send out funds for the swap for enough confirmations
191
- *
192
- * @param payment
193
- */
194
- subscribeToPayment(payment) {
195
- this.swapLogger.info(payment, "subscribeToPayment(): subscribing to swap, txId: " + payment.txId + " address: " + payment.address);
196
- this.activeSubscriptions[payment.txId] = payment;
197
- }
198
- unsubscribePayment(payment) {
199
- if (payment.txId != null) {
200
- if (this.activeSubscriptions[payment.txId] != null) {
201
- this.swapLogger.info(payment, "unsubscribePayment(): unsubscribing swap, txId: " + payment.txId + " address: " + payment.address);
202
- delete this.activeSubscriptions[payment.txId];
203
- }
204
- }
205
- }
206
- /**
207
- * Checks if expiry time on the swap leaves us enough room to send a transaction and for the transaction to confirm
208
- *
209
- * @param swap
210
- * @private
211
- * @throws DefinedRuntimeError will throw an error in case there isn't enough time for us to send a BTC payout tx
212
- */
213
- checkExpiresTooSoon(swap) {
214
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
215
- const tsDelta = swap.data.getExpiry() - currentTimestamp;
216
- const minRequiredCLTV = this.getExpiryFromCLTV(swap.preferedConfirmationTarget, swap.requiredConfirmations);
217
- const hasRequiredCLTVDelta = tsDelta >= minRequiredCLTV;
218
- if (!hasRequiredCLTVDelta)
219
- throw {
220
- code: 90001,
221
- msg: "TS delta too low",
222
- data: {
223
- required: minRequiredCLTV.toString(10),
224
- actual: tsDelta.toString(10)
225
- }
226
- };
227
- }
228
- /**
229
- * Checks if the actual fee for the swap is no higher than the quoted estimate
230
- *
231
- * @param quotedSatsPerVbyte
232
- * @param actualSatsPerVbyte
233
- * @private
234
- * @throws DefinedRuntimeError will throw an error in case the actual fee is higher than quoted fee
235
- */
236
- checkCalculatedTxFee(quotedSatsPerVbyte, actualSatsPerVbyte) {
237
- const swapPaysEnoughNetworkFee = quotedSatsPerVbyte >= actualSatsPerVbyte;
238
- if (!swapPaysEnoughNetworkFee)
239
- throw {
240
- code: 90003,
241
- msg: "Fee changed too much!",
242
- data: {
243
- quotedFee: quotedSatsPerVbyte.toString(10),
244
- actualFee: actualSatsPerVbyte.toString(10)
245
- }
246
- };
247
- }
248
- /**
249
- * Sends a bitcoin transaction to payout BTC for a swap
250
- *
251
- * @param swap
252
- * @private
253
- * @throws DefinedRuntimeError will throw an error in case the payment cannot be initiated
254
- */
255
- sendBitcoinPayment(swap) {
256
- //Make sure that bitcoin payouts are processed sequentially to avoid race conditions between multiple payouts,
257
- // e.g. that 2 payouts share the same input and would effectively double-spend each other
258
- return this.sendBtcQueue.enqueue(async () => {
259
- //Run checks
260
- this.checkExpiresTooSoon(swap);
261
- if (swap.metadata != null)
262
- swap.metadata.times.payCLTVChecked = Date.now();
263
- const satsPerVbyte = await this.bitcoin.getFeeRate();
264
- this.checkCalculatedTxFee(swap.satsPerVbyte, BigInt(satsPerVbyte));
265
- if (swap.metadata != null)
266
- swap.metadata.times.payChainFee = Date.now();
267
- const signResult = await this.bitcoin.getSignedTransaction(swap.address, Number(swap.amount), satsPerVbyte, swap.nonce, Number(swap.satsPerVbyte));
268
- if (signResult == null)
269
- throw {
270
- code: 90002,
271
- msg: "Failed to create signed transaction (not enough funds?)"
272
- };
273
- if (swap.metadata != null)
274
- swap.metadata.times.paySignPSBT = Date.now();
275
- this.swapLogger.debug(swap, "sendBitcoinPayment(): signed raw transaction: " + signResult.raw);
276
- swap.txId = signResult.tx.id;
277
- swap.setRealNetworkFee(BigInt(signResult.networkFee));
278
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING);
279
- await this.saveSwapData(swap);
280
- await this.bitcoin.sendRawTransaction(signResult.raw);
281
- if (swap.metadata != null)
282
- swap.metadata.times.payTxSent = Date.now();
283
- this.swapLogger.info(swap, "sendBitcoinPayment(): btc transaction generated, signed & broadcasted, txId: " + swap.txId + " address: " + swap.address);
284
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT);
285
- await this.saveSwapData(swap);
286
- });
287
- }
288
- /**
289
- * Called after swap was successfully committed, will check if bitcoin tx is already sent, if not tries to send it and subscribes to it
290
- *
291
- * @param swap
292
- */
293
- async processInitialized(swap) {
294
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING) {
295
- //Bitcoin transaction was signed (maybe also sent)
296
- const tx = await this.bitcoin.getWalletTransaction(swap.txId);
297
- const isTxSent = tx != null;
298
- if (!isTxSent) {
299
- //Reset the state to COMMITED
300
- this.swapLogger.info(swap, "processInitialized(state=BTC_SENDING): btc transaction not found, resetting to COMMITED state, txId: " + swap.txId + " address: " + swap.address);
301
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
302
- }
303
- else {
304
- this.swapLogger.info(swap, "processInitialized(state=BTC_SENDING): btc transaction found, advancing to BTC_SENT state, txId: " + swap.txId + " address: " + swap.address);
305
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT);
306
- await this.saveSwapData(swap);
307
- }
308
- }
309
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
310
- this.swapLogger.info(swap, "processInitialized(state=SAVED): advancing to COMMITED state, address: " + swap.address);
311
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
312
- await this.saveSwapData(swap);
313
- }
314
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED) {
315
- const unlock = swap.lock(60);
316
- if (unlock == null)
317
- return;
318
- this.swapLogger.debug(swap, "processInitialized(state=COMMITED): sending bitcoin transaction, address: " + swap.address);
319
- try {
320
- await this.sendBitcoinPayment(swap);
321
- this.swapLogger.info(swap, "processInitialized(state=COMMITED): btc transaction sent, address: " + swap.address);
322
- }
323
- catch (e) {
324
- if ((0, Utils_1.isDefinedRuntimeError)(e)) {
325
- this.swapLogger.error(swap, "processInitialized(state=COMMITED): setting state to NON_PAYABLE due to send bitcoin payment error", e);
326
- if (swap.metadata != null)
327
- swap.metadata.payError = e;
328
- await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE);
329
- await this.saveSwapData(swap);
330
- }
331
- else {
332
- this.swapLogger.error(swap, "processInitialized(state=COMMITED): send bitcoin payment error", e);
333
- throw e;
334
- }
335
- }
336
- unlock();
337
- }
338
- if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE)
339
- return;
340
- this.subscribeToPayment(swap);
341
- }
342
- async processInitializeEvent(chainIdentifier, swap, event) {
343
- this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, address: " + swap.address);
344
- await this.processInitialized(swap);
345
- }
346
- async processClaimEvent(chainIdentifier, swap, event) {
347
- this.swapLogger.info(swap, "SC: ClaimEvent: swap successfully claimed to us, address: " + swap.address);
348
- //Also remove transaction from active subscriptions
349
- this.unsubscribePayment(swap);
350
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CLAIMED);
351
- }
352
- async processRefundEvent(chainIdentifier, swap, event) {
353
- this.swapLogger.info(swap, "SC: RefundEvent: swap successfully refunded by the user, address: " + swap.address);
354
- //Also remove transaction from active subscriptions
355
- this.unsubscribePayment(swap);
356
- await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.REFUNDED);
357
- }
358
- /**
359
- * Returns required expiry delta for swap params
360
- *
361
- * @param confirmationTarget
362
- * @param confirmations
363
- */
364
- getExpiryFromCLTV(confirmationTarget, confirmations) {
365
- //Blocks = 10 + (confirmations + confirmationTarget)*2
366
- //Time = 3600 + (600*blocks*2)
367
- const cltv = this.config.minChainCltv + (BigInt(confirmations + confirmationTarget) * this.config.sendSafetyFactor);
368
- return this.config.gracePeriod + (this.config.bitcoinBlocktime * cltv * this.config.safetyFactor);
369
- }
370
- /**
371
- * Checks if the requested nonce is valid
372
- *
373
- * @param nonce
374
- * @throws {DefinedRuntimeError} will throw an error if the nonce is invalid
375
- */
376
- checkNonceValid(nonce) {
377
- if (nonce < 0 || nonce >= (2n ** 64n))
378
- throw {
379
- code: 20021,
380
- msg: "Invalid request body (nonce - cannot be parsed)"
381
- };
382
- const firstPart = nonce >> 24n;
383
- const maxAllowedValue = BigInt(Math.floor(Date.now() / 1000) - 600000000);
384
- if (firstPart > maxAllowedValue)
385
- throw {
386
- code: 20022,
387
- msg: "Invalid request body (nonce - too high)"
388
- };
389
- }
390
- /**
391
- * Checks if confirmation target is within configured bounds
392
- *
393
- * @param confirmationTarget
394
- * @throws {DefinedRuntimeError} will throw an error if the confirmationTarget is out of bounds
395
- */
396
- checkConfirmationTarget(confirmationTarget) {
397
- if (confirmationTarget > this.config.maxConfTarget)
398
- throw {
399
- code: 20023,
400
- msg: "Invalid request body (confirmationTarget - too high)"
401
- };
402
- if (confirmationTarget < this.config.minConfTarget)
403
- throw {
404
- code: 20024,
405
- msg: "Invalid request body (confirmationTarget - too low)"
406
- };
407
- }
408
- /**
409
- * Checks if the required confirmations are within configured bounds
410
- *
411
- * @param confirmations
412
- * @throws {DefinedRuntimeError} will throw an error if the confirmations are out of bounds
413
- */
414
- checkRequiredConfirmations(confirmations) {
415
- if (confirmations > this.config.maxConfirmations)
416
- throw {
417
- code: 20025,
418
- msg: "Invalid request body (confirmations - too high)"
419
- };
420
- if (confirmations < this.config.minConfirmations)
421
- throw {
422
- code: 20026,
423
- msg: "Invalid request body (confirmations - too low)"
424
- };
425
- }
426
- /**
427
- * Checks the validity of the provided address, also checks if the resulting output script isn't too large
428
- *
429
- * @param address
430
- * @throws {DefinedRuntimeError} will throw an error if the address is invalid
431
- */
432
- checkAddress(address) {
433
- let parsedOutputScript;
434
- try {
435
- parsedOutputScript = this.bitcoin.toOutputScript(address);
436
- }
437
- catch (e) {
438
- throw {
439
- code: 20031,
440
- msg: "Invalid request body (address - cannot be parsed)"
441
- };
442
- }
443
- if (parsedOutputScript.length > OUTPUT_SCRIPT_MAX_LENGTH)
444
- throw {
445
- code: 20032,
446
- msg: "Invalid request body (address's output script - too long)"
447
- };
448
- }
449
- /**
450
- * Checks if the swap is expired, taking into consideration on-chain time skew
451
- *
452
- * @param swap
453
- * @throws {DefinedRuntimeError} will throw an error if the swap is expired
454
- */
455
- async checkExpired(swap) {
456
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
457
- const isExpired = await swapContract.isExpired(signer.getAddress(), swap.data);
458
- if (isExpired)
459
- throw {
460
- _httpStatus: 200,
461
- code: 20010,
462
- msg: "Payment expired"
463
- };
464
- }
465
- /**
466
- * Checks & returns the network fee needed for a transaction
467
- *
468
- * @param address
469
- * @param amount
470
- * @throws {DefinedRuntimeError} will throw an error if there are not enough BTC funds
471
- */
472
- async checkAndGetNetworkFee(address, amount) {
473
- let chainFeeResp = await this.bitcoin.estimateFee(address, Number(amount), null, this.config.networkFeeMultiplier);
474
- const hasEnoughFunds = chainFeeResp != null;
475
- if (!hasEnoughFunds)
476
- throw {
477
- code: 20002,
478
- msg: "Not enough liquidity"
479
- };
480
- return {
481
- networkFee: BigInt(chainFeeResp.networkFee),
482
- satsPerVbyte: BigInt(chainFeeResp.satsPerVbyte)
483
- };
484
- }
485
- startRestServer(restServer) {
486
- restServer.use(this.path + "/payInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
487
- restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
488
- const metadata = { request: {}, times: {} };
489
- const chainIdentifier = req.query.chain ?? this.chains.default;
490
- const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
491
- metadata.times.requestReceived = Date.now();
492
- /**
493
- *Sent initially:
494
- * address: string Bitcoin destination address
495
- * amount: string Amount to send (in satoshis)
496
- * confirmationTarget: number Desired confirmation target for the swap, how big of a fee should be assigned to TX
497
- * confirmations: number Required number of confirmations for us to claim the swap
498
- * nonce: string Nonce for the swap (used for replay protection)
499
- * token: string Desired token to use
500
- * offerer: string Address of the caller
501
- * exactIn: boolean Whether the swap should be an exact in instead of exact out swap
502
- *
503
- *Sent later:
504
- * feeRate: string Fee rate to use for the init signature
505
- */
506
- const parsedBody = await req.paramReader.getParams({
507
- address: SchemaVerifier_1.FieldTypeEnum.String,
508
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
509
- confirmationTarget: SchemaVerifier_1.FieldTypeEnum.Number,
510
- confirmations: SchemaVerifier_1.FieldTypeEnum.Number,
511
- nonce: SchemaVerifier_1.FieldTypeEnum.BigInt,
512
- token: (val) => val != null &&
513
- typeof (val) === "string" &&
514
- this.isTokenSupported(chainIdentifier, val) ? val : null,
515
- offerer: (val) => val != null &&
516
- typeof (val) === "string" &&
517
- chainInterface.isValidAddress(val) ? val : null,
518
- exactIn: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
519
- });
520
- if (parsedBody == null)
521
- throw {
522
- code: 20100,
523
- msg: "Invalid request body"
524
- };
525
- metadata.request = parsedBody;
526
- const requestedAmount = { input: !!parsedBody.exactIn, amount: parsedBody.amount, token: parsedBody.token };
527
- const request = {
528
- chainIdentifier,
529
- raw: req,
530
- parsed: parsedBody,
531
- metadata
532
- };
533
- const useToken = parsedBody.token;
534
- const responseStream = res.responseStream;
535
- this.checkNonceValid(parsedBody.nonce);
536
- this.checkConfirmationTarget(parsedBody.confirmationTarget);
537
- this.checkRequiredConfirmations(parsedBody.confirmations);
538
- this.checkAddress(parsedBody.address);
539
- await this.checkVaultInitialized(chainIdentifier, parsedBody.token);
540
- const fees = await this.AmountAssertions.preCheckToBtcAmounts(this.type, request, requestedAmount);
541
- metadata.times.requestChecked = Date.now();
542
- //Initialize abort controller for the parallel async operations
543
- const abortController = (0, Utils_1.getAbortController)(responseStream);
544
- const { pricePrefetchPromise, signDataPrefetchPromise } = this.getToBtcPrefetches(chainIdentifier, useToken, responseStream, abortController);
545
- const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = await this.AmountAssertions.checkToBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, async (amount) => {
546
- metadata.times.amountsChecked = Date.now();
547
- const resp = await this.checkAndGetNetworkFee(parsedBody.address, amount);
548
- this.logger.debug("checkToBtcAmount(): network fee calculated, amount: " + amount.toString(10) + " fee: " + resp.networkFee.toString(10));
549
- metadata.times.chainFeeCalculated = Date.now();
550
- return resp;
551
- }, abortController.signal);
552
- metadata.times.priceCalculated = Date.now();
553
- const paymentHash = this.getHash(chainIdentifier, parsedBody.address, parsedBody.confirmations, parsedBody.nonce, amountBD).toString("hex");
554
- //Add grace period another time, so the user has 1 hour to commit
555
- const expirySeconds = this.getExpiryFromCLTV(parsedBody.confirmationTarget, parsedBody.confirmations) + this.config.gracePeriod;
556
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
557
- const minRequiredExpiry = currentTimestamp + expirySeconds;
558
- const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
559
- const payObject = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN_NONCED, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, paymentHash, sequence, minRequiredExpiry, true, false, 0n, 0n);
560
- abortController.signal.throwIfAborted();
561
- metadata.times.swapCreated = Date.now();
562
- const sigData = await this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
563
- metadata.times.swapSigned = Date.now();
564
- const createdSwap = new ToBtcSwapAbs_1.ToBtcSwapAbs(chainIdentifier, parsedBody.address, amountBD, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken, networkFeeData.satsPerVbyte, parsedBody.nonce, parsedBody.confirmations, parsedBody.confirmationTarget);
565
- createdSwap.data = payObject;
566
- createdSwap.metadata = metadata;
567
- createdSwap.prefix = sigData.prefix;
568
- createdSwap.timeout = sigData.timeout;
569
- createdSwap.signature = sigData.signature;
570
- createdSwap.feeRate = sigData.feeRate;
571
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
572
- await this.saveSwapData(createdSwap);
573
- this.swapLogger.info(createdSwap, "REST: /payInvoice: created swap address: " + createdSwap.address + " amount: " + amountBD.toString(10));
574
- await responseStream.writeParamsAndEnd({
575
- code: 20000,
576
- msg: "Success",
577
- data: {
578
- amount: amountBD.toString(10),
579
- address: signer.getAddress(),
580
- satsPervByte: networkFeeData.satsPerVbyte.toString(10),
581
- networkFee: networkFeeInToken.toString(10),
582
- swapFee: swapFeeInToken.toString(10),
583
- totalFee: (swapFeeInToken + networkFeeInToken).toString(10),
584
- total: totalInToken.toString(10),
585
- minRequiredExpiry: minRequiredExpiry.toString(10),
586
- data: payObject.serialize(),
587
- prefix: sigData.prefix,
588
- timeout: sigData.timeout,
589
- signature: sigData.signature
590
- }
591
- });
592
- }));
593
- const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
594
- /**
595
- * paymentHash: string Payment hash identifier of the swap
596
- * sequence: BN Sequence identifier of the swap
597
- */
598
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
599
- paymentHash: (val) => val != null &&
600
- typeof (val) === "string" &&
601
- Utils_1.HEX_REGEX.test(val) ? val : null,
602
- sequence: SchemaVerifier_1.FieldTypeEnum.BigInt
603
- });
604
- if (parsedBody == null)
605
- throw {
606
- code: 20100,
607
- msg: "Invalid request body/query (paymentHash/sequence)"
608
- };
609
- this.checkSequence(parsedBody.sequence);
610
- const payment = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
611
- if (payment == null || payment.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED)
612
- throw {
613
- _httpStatus: 200,
614
- code: 20007,
615
- msg: "Payment not found"
616
- };
617
- await this.checkExpired(payment);
618
- if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED)
619
- throw {
620
- _httpStatus: 200,
621
- code: 20008,
622
- msg: "Payment processing"
623
- };
624
- if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT || payment.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING)
625
- throw {
626
- _httpStatus: 200,
627
- code: 20006,
628
- msg: "Already paid",
629
- data: {
630
- txId: payment.txId
631
- }
632
- };
633
- const { swapContract, signer } = this.getChain(payment.chainIdentifier);
634
- if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE) {
635
- const isCommited = await swapContract.isCommited(payment.data);
636
- if (!isCommited)
637
- throw {
638
- code: 20005,
639
- msg: "Not committed"
640
- };
641
- const refundResponse = await swapContract.getRefundSignature(signer, payment.data, this.config.refundAuthorizationTimeout);
642
- //Double check the state after promise result
643
- if (payment.state !== ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE)
644
- throw {
645
- code: 20005,
646
- msg: "Not committed"
647
- };
648
- this.swapLogger.info(payment, "REST: /getRefundAuthorization: returning refund authorization, because swap is in NON_PAYABLE state, address: " + payment.address);
649
- res.status(200).json({
650
- code: 20000,
651
- msg: "Success",
652
- data: {
653
- address: signer.getAddress(),
654
- prefix: refundResponse.prefix,
655
- timeout: refundResponse.timeout,
656
- signature: refundResponse.signature
657
- }
658
- });
659
- return;
660
- }
661
- throw {
662
- _httpStatus: 500,
663
- code: 20009,
664
- msg: "Invalid payment status"
665
- };
666
- });
667
- restServer.post(this.path + "/getRefundAuthorization", getRefundAuthorization);
668
- restServer.get(this.path + "/getRefundAuthorization", getRefundAuthorization);
669
- this.logger.info("started at path: ", this.path);
670
- }
671
- /**
672
- * Starts watchdog checking sent bitcoin transactions
673
- */
674
- async startTxTimer() {
675
- let rerun;
676
- rerun = async () => {
677
- await this.processBtcTxs().catch(e => this.logger.error("startTxTimer(): call to processBtcTxs() errored", e));
678
- setTimeout(rerun, this.config.txCheckInterval);
679
- };
680
- await rerun();
681
- }
682
- async startWatchdog() {
683
- await super.startWatchdog();
684
- await this.startTxTimer();
685
- }
686
- async init() {
687
- await this.loadData(ToBtcSwapAbs_1.ToBtcSwapAbs);
688
- this.subscribeToEvents();
689
- await PluginManager_1.PluginManager.serviceInitialize(this);
690
- }
691
- getInfoData() {
692
- return {
693
- minCltv: Number(this.config.minChainCltv),
694
- minConfirmations: this.config.minConfirmations,
695
- maxConfirmations: this.config.maxConfirmations,
696
- minConfTarget: this.config.minConfTarget,
697
- maxConfTarget: this.config.maxConfTarget,
698
- maxOutputScriptLen: OUTPUT_SCRIPT_MAX_LENGTH
699
- };
700
- }
701
- }
702
- exports.ToBtcAbs = ToBtcAbs;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToBtcAbs = void 0;
4
+ const ToBtcSwapAbs_1 = require("./ToBtcSwapAbs");
5
+ const SwapHandler_1 = require("../../SwapHandler");
6
+ const base_1 = require("@atomiqlabs/base");
7
+ const Utils_1 = require("../../../utils/Utils");
8
+ const PluginManager_1 = require("../../../plugins/PluginManager");
9
+ const crypto_1 = require("crypto");
10
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
+ const ToBtcBaseSwapHandler_1 = require("../ToBtcBaseSwapHandler");
13
+ const promise_queue_ts_1 = require("promise-queue-ts");
14
+ const OUTPUT_SCRIPT_MAX_LENGTH = 200;
15
+ /**
16
+ * Handler for to BTC swaps, utilizing PTLCs (proof-time locked contracts) using btc relay (on-chain bitcoin SPV)
17
+ */
18
+ class ToBtcAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
19
+ constructor(storageDirectory, path, chainData, bitcoin, swapPricing, bitcoinRpc, config) {
20
+ super(storageDirectory, path, chainData, swapPricing, config);
21
+ this.type = SwapHandler_1.SwapHandlerType.TO_BTC;
22
+ this.swapType = base_1.ChainSwapType.CHAIN_NONCED;
23
+ this.activeSubscriptions = {};
24
+ this.sendBtcQueue = new promise_queue_ts_1.PromiseQueue();
25
+ this.bitcoinRpc = bitcoinRpc;
26
+ this.bitcoin = bitcoin;
27
+ this.config = config;
28
+ }
29
+ /**
30
+ * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
31
+ *
32
+ * @param chainIdentifier
33
+ * @param address
34
+ * @param confirmations
35
+ * @param nonce
36
+ * @param amount
37
+ */
38
+ getHash(chainIdentifier, address, confirmations, nonce, amount) {
39
+ const parsedOutputScript = this.bitcoin.toOutputScript(address);
40
+ const { swapContract } = this.getChain(chainIdentifier);
41
+ return swapContract.getHashForOnchain(parsedOutputScript, amount, confirmations, nonce);
42
+ }
43
+ /**
44
+ * Tries to claim the swap after our transaction was confirmed
45
+ *
46
+ * @param tx
47
+ * @param swap
48
+ * @param vout
49
+ */
50
+ async tryClaimSwap(tx, swap, vout) {
51
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
52
+ const blockHeader = await this.bitcoinRpc.getBlockHeader(tx.blockhash);
53
+ //Set flag that we are sending the transaction already, so we don't end up with race condition
54
+ const unlock = swap.lock(swapContract.claimWithTxDataTimeout);
55
+ if (unlock == null)
56
+ return false;
57
+ try {
58
+ this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout);
59
+ const result = await swapContract.claimWithTxData(signer, swap.data, { ...tx, height: blockHeader.getHeight() }, swap.requiredConfirmations, vout, null, null, false, {
60
+ waitForConfirmation: true
61
+ });
62
+ this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout + " address: " + swap.address);
63
+ if (swap.metadata != null)
64
+ swap.metadata.times.txClaimed = Date.now();
65
+ unlock();
66
+ return true;
67
+ }
68
+ catch (e) {
69
+ this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, height: " + blockHeader.getHeight() + " utxo: " + tx.txid + ":" + vout + " address: " + swap.address, e);
70
+ return false;
71
+ }
72
+ }
73
+ async processPastSwap(swap) {
74
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
75
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
76
+ const isSignatureExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
77
+ if (isSignatureExpired) {
78
+ const isCommitted = await swapContract.isCommited(swap.data);
79
+ if (!isCommitted) {
80
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, address: " + swap.address);
81
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CANCELED);
82
+ }
83
+ else {
84
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), address: " + swap.address);
85
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
86
+ await this.saveSwapData(swap);
87
+ }
88
+ return;
89
+ }
90
+ }
91
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
92
+ if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
93
+ this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE|SAVED): swap expired, cancelling, address: " + swap.address);
94
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CANCELED);
95
+ return;
96
+ }
97
+ }
98
+ //Sanity check for sent swaps
99
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT) {
100
+ const isCommited = await swapContract.isCommited(swap.data);
101
+ if (!isCommited) {
102
+ const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
103
+ if (status === base_1.SwapCommitStatus.PAID) {
104
+ this.swapLogger.info(swap, "processPastSwap(state=BTC_SENT): swap claimed (detected from processPastSwap), address: " + swap.address);
105
+ this.unsubscribePayment(swap);
106
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CLAIMED);
107
+ }
108
+ else if (status === base_1.SwapCommitStatus.EXPIRED) {
109
+ this.swapLogger.warn(swap, "processPastSwap(state=BTC_SENT): swap expired, but bitcoin was probably already sent, txId: " + swap.txId + " address: " + swap.address);
110
+ this.unsubscribePayment(swap);
111
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.REFUNDED);
112
+ }
113
+ return;
114
+ }
115
+ }
116
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING || swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT) {
117
+ await this.processInitialized(swap);
118
+ return;
119
+ }
120
+ }
121
+ /**
122
+ * Checks past swaps, deletes ones that are already expired.
123
+ */
124
+ async processPastSwaps() {
125
+ const queriedData = await this.storageManager.query([
126
+ {
127
+ key: "state",
128
+ values: [
129
+ ToBtcSwapAbs_1.ToBtcSwapState.SAVED,
130
+ ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE,
131
+ ToBtcSwapAbs_1.ToBtcSwapState.COMMITED,
132
+ ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING,
133
+ ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT,
134
+ ]
135
+ }
136
+ ]);
137
+ for (let { obj: swap } of queriedData) {
138
+ await this.processPastSwap(swap);
139
+ }
140
+ }
141
+ async processBtcTx(swap, tx) {
142
+ tx.confirmations = tx.confirmations || 0;
143
+ //Check transaction has enough confirmations
144
+ const hasEnoughConfirmations = tx.confirmations >= swap.requiredConfirmations;
145
+ if (!hasEnoughConfirmations) {
146
+ return false;
147
+ }
148
+ this.swapLogger.debug(swap, "processBtcTx(): address: " + swap.address + " amount: " + swap.amount.toString(10) + " btcTx: " + tx);
149
+ //Search for required transaction output (vout)
150
+ const outputScript = this.bitcoin.toOutputScript(swap.address);
151
+ const vout = tx.outs.find(e => BigInt(e.value) === swap.amount && Buffer.from(e.scriptPubKey.hex, "hex").equals(outputScript));
152
+ if (vout == null) {
153
+ this.swapLogger.warn(swap, "processBtcTx(): cannot find correct vout," +
154
+ " required output script: " + outputScript.toString("hex") +
155
+ " required amount: " + swap.amount.toString(10) +
156
+ " vouts: ", tx.outs);
157
+ return false;
158
+ }
159
+ if (swap.metadata != null)
160
+ swap.metadata.times.payTxConfirmed = Date.now();
161
+ const success = await this.tryClaimSwap(tx, swap, vout.n);
162
+ return success;
163
+ }
164
+ /**
165
+ * Checks active sent out bitcoin transactions
166
+ */
167
+ async processBtcTxs() {
168
+ const unsubscribeSwaps = [];
169
+ for (let txId in this.activeSubscriptions) {
170
+ const swap = this.activeSubscriptions[txId];
171
+ //TODO: RBF the transaction if it's already taking too long to confirm
172
+ try {
173
+ let tx = await this.bitcoin.getWalletTransaction(txId);
174
+ if (tx == null)
175
+ continue;
176
+ if (await this.processBtcTx(swap, tx)) {
177
+ this.swapLogger.info(swap, "processBtcTxs(): swap claimed successfully, txId: " + tx.txid + " address: " + swap.address);
178
+ unsubscribeSwaps.push(swap);
179
+ }
180
+ }
181
+ catch (e) {
182
+ this.swapLogger.error(swap, "processBtcTxs(): error processing btc transaction", e);
183
+ }
184
+ }
185
+ unsubscribeSwaps.forEach(swap => {
186
+ this.unsubscribePayment(swap);
187
+ });
188
+ }
189
+ /**
190
+ * Subscribes to and periodically checks txId used to send out funds for the swap for enough confirmations
191
+ *
192
+ * @param payment
193
+ */
194
+ subscribeToPayment(payment) {
195
+ this.swapLogger.info(payment, "subscribeToPayment(): subscribing to swap, txId: " + payment.txId + " address: " + payment.address);
196
+ this.activeSubscriptions[payment.txId] = payment;
197
+ }
198
+ unsubscribePayment(payment) {
199
+ if (payment.txId != null) {
200
+ if (this.activeSubscriptions[payment.txId] != null) {
201
+ this.swapLogger.info(payment, "unsubscribePayment(): unsubscribing swap, txId: " + payment.txId + " address: " + payment.address);
202
+ delete this.activeSubscriptions[payment.txId];
203
+ }
204
+ }
205
+ }
206
+ /**
207
+ * Checks if expiry time on the swap leaves us enough room to send a transaction and for the transaction to confirm
208
+ *
209
+ * @param swap
210
+ * @private
211
+ * @throws DefinedRuntimeError will throw an error in case there isn't enough time for us to send a BTC payout tx
212
+ */
213
+ checkExpiresTooSoon(swap) {
214
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
215
+ const tsDelta = swap.data.getExpiry() - currentTimestamp;
216
+ const minRequiredCLTV = this.getExpiryFromCLTV(swap.preferedConfirmationTarget, swap.requiredConfirmations);
217
+ const hasRequiredCLTVDelta = tsDelta >= minRequiredCLTV;
218
+ if (!hasRequiredCLTVDelta)
219
+ throw {
220
+ code: 90001,
221
+ msg: "TS delta too low",
222
+ data: {
223
+ required: minRequiredCLTV.toString(10),
224
+ actual: tsDelta.toString(10)
225
+ }
226
+ };
227
+ }
228
+ /**
229
+ * Checks if the actual fee for the swap is no higher than the quoted estimate
230
+ *
231
+ * @param quotedSatsPerVbyte
232
+ * @param actualSatsPerVbyte
233
+ * @private
234
+ * @throws DefinedRuntimeError will throw an error in case the actual fee is higher than quoted fee
235
+ */
236
+ checkCalculatedTxFee(quotedSatsPerVbyte, actualSatsPerVbyte) {
237
+ const swapPaysEnoughNetworkFee = quotedSatsPerVbyte >= actualSatsPerVbyte;
238
+ if (!swapPaysEnoughNetworkFee)
239
+ throw {
240
+ code: 90003,
241
+ msg: "Fee changed too much!",
242
+ data: {
243
+ quotedFee: quotedSatsPerVbyte.toString(10),
244
+ actualFee: actualSatsPerVbyte.toString(10)
245
+ }
246
+ };
247
+ }
248
+ /**
249
+ * Sends a bitcoin transaction to payout BTC for a swap
250
+ *
251
+ * @param swap
252
+ * @private
253
+ * @throws DefinedRuntimeError will throw an error in case the payment cannot be initiated
254
+ */
255
+ sendBitcoinPayment(swap) {
256
+ //Make sure that bitcoin payouts are processed sequentially to avoid race conditions between multiple payouts,
257
+ // e.g. that 2 payouts share the same input and would effectively double-spend each other
258
+ return this.sendBtcQueue.enqueue(async () => {
259
+ //Run checks
260
+ this.checkExpiresTooSoon(swap);
261
+ if (swap.metadata != null)
262
+ swap.metadata.times.payCLTVChecked = Date.now();
263
+ const satsPerVbyte = await this.bitcoin.getFeeRate();
264
+ this.checkCalculatedTxFee(swap.satsPerVbyte, BigInt(satsPerVbyte));
265
+ if (swap.metadata != null)
266
+ swap.metadata.times.payChainFee = Date.now();
267
+ const signResult = await this.bitcoin.getSignedTransaction(swap.address, Number(swap.amount), satsPerVbyte, swap.nonce, Number(swap.satsPerVbyte));
268
+ if (signResult == null)
269
+ throw {
270
+ code: 90002,
271
+ msg: "Failed to create signed transaction (not enough funds?)"
272
+ };
273
+ if (swap.metadata != null)
274
+ swap.metadata.times.paySignPSBT = Date.now();
275
+ this.swapLogger.debug(swap, "sendBitcoinPayment(): signed raw transaction: " + signResult.raw);
276
+ swap.txId = signResult.tx.id;
277
+ swap.setRealNetworkFee(BigInt(signResult.networkFee));
278
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING);
279
+ await this.saveSwapData(swap);
280
+ await this.bitcoin.sendRawTransaction(signResult.raw);
281
+ if (swap.metadata != null)
282
+ swap.metadata.times.payTxSent = Date.now();
283
+ this.swapLogger.info(swap, "sendBitcoinPayment(): btc transaction generated, signed & broadcasted, txId: " + swap.txId + " address: " + swap.address);
284
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT);
285
+ await this.saveSwapData(swap);
286
+ });
287
+ }
288
+ /**
289
+ * Called after swap was successfully committed, will check if bitcoin tx is already sent, if not tries to send it and subscribes to it
290
+ *
291
+ * @param swap
292
+ */
293
+ async processInitialized(swap) {
294
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING) {
295
+ //Bitcoin transaction was signed (maybe also sent)
296
+ const tx = await this.bitcoin.getWalletTransaction(swap.txId);
297
+ const isTxSent = tx != null;
298
+ if (!isTxSent) {
299
+ //Reset the state to COMMITED
300
+ this.swapLogger.info(swap, "processInitialized(state=BTC_SENDING): btc transaction not found, resetting to COMMITED state, txId: " + swap.txId + " address: " + swap.address);
301
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
302
+ }
303
+ else {
304
+ this.swapLogger.info(swap, "processInitialized(state=BTC_SENDING): btc transaction found, advancing to BTC_SENT state, txId: " + swap.txId + " address: " + swap.address);
305
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT);
306
+ await this.saveSwapData(swap);
307
+ }
308
+ }
309
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED) {
310
+ this.swapLogger.info(swap, "processInitialized(state=SAVED): advancing to COMMITED state, address: " + swap.address);
311
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.COMMITED);
312
+ await this.saveSwapData(swap);
313
+ }
314
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED) {
315
+ const unlock = swap.lock(60);
316
+ if (unlock == null)
317
+ return;
318
+ this.swapLogger.debug(swap, "processInitialized(state=COMMITED): sending bitcoin transaction, address: " + swap.address);
319
+ try {
320
+ await this.sendBitcoinPayment(swap);
321
+ this.swapLogger.info(swap, "processInitialized(state=COMMITED): btc transaction sent, address: " + swap.address);
322
+ }
323
+ catch (e) {
324
+ if ((0, Utils_1.isDefinedRuntimeError)(e)) {
325
+ this.swapLogger.error(swap, "processInitialized(state=COMMITED): setting state to NON_PAYABLE due to send bitcoin payment error", e);
326
+ if (swap.metadata != null)
327
+ swap.metadata.payError = e;
328
+ await swap.setState(ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE);
329
+ await this.saveSwapData(swap);
330
+ }
331
+ else {
332
+ this.swapLogger.error(swap, "processInitialized(state=COMMITED): send bitcoin payment error", e);
333
+ throw e;
334
+ }
335
+ }
336
+ unlock();
337
+ }
338
+ if (swap.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE)
339
+ return;
340
+ this.subscribeToPayment(swap);
341
+ }
342
+ async processInitializeEvent(chainIdentifier, swap, event) {
343
+ this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, address: " + swap.address);
344
+ await this.processInitialized(swap);
345
+ }
346
+ async processClaimEvent(chainIdentifier, swap, event) {
347
+ this.swapLogger.info(swap, "SC: ClaimEvent: swap successfully claimed to us, address: " + swap.address);
348
+ //Also remove transaction from active subscriptions
349
+ this.unsubscribePayment(swap);
350
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.CLAIMED);
351
+ }
352
+ async processRefundEvent(chainIdentifier, swap, event) {
353
+ this.swapLogger.info(swap, "SC: RefundEvent: swap successfully refunded by the user, address: " + swap.address);
354
+ //Also remove transaction from active subscriptions
355
+ this.unsubscribePayment(swap);
356
+ await this.removeSwapData(swap, ToBtcSwapAbs_1.ToBtcSwapState.REFUNDED);
357
+ }
358
+ /**
359
+ * Returns required expiry delta for swap params
360
+ *
361
+ * @param confirmationTarget
362
+ * @param confirmations
363
+ */
364
+ getExpiryFromCLTV(confirmationTarget, confirmations) {
365
+ //Blocks = 10 + (confirmations + confirmationTarget)*2
366
+ //Time = 3600 + (600*blocks*2)
367
+ const cltv = this.config.minChainCltv + (BigInt(confirmations + confirmationTarget) * this.config.sendSafetyFactor);
368
+ return this.config.gracePeriod + (this.config.bitcoinBlocktime * cltv * this.config.safetyFactor);
369
+ }
370
+ /**
371
+ * Checks if the requested nonce is valid
372
+ *
373
+ * @param nonce
374
+ * @throws {DefinedRuntimeError} will throw an error if the nonce is invalid
375
+ */
376
+ checkNonceValid(nonce) {
377
+ if (nonce < 0 || nonce >= (2n ** 64n))
378
+ throw {
379
+ code: 20021,
380
+ msg: "Invalid request body (nonce - cannot be parsed)"
381
+ };
382
+ const firstPart = nonce >> 24n;
383
+ const maxAllowedValue = BigInt(Math.floor(Date.now() / 1000) - 600000000);
384
+ if (firstPart > maxAllowedValue)
385
+ throw {
386
+ code: 20022,
387
+ msg: "Invalid request body (nonce - too high)"
388
+ };
389
+ }
390
+ /**
391
+ * Checks if confirmation target is within configured bounds
392
+ *
393
+ * @param confirmationTarget
394
+ * @throws {DefinedRuntimeError} will throw an error if the confirmationTarget is out of bounds
395
+ */
396
+ checkConfirmationTarget(confirmationTarget) {
397
+ if (confirmationTarget > this.config.maxConfTarget)
398
+ throw {
399
+ code: 20023,
400
+ msg: "Invalid request body (confirmationTarget - too high)"
401
+ };
402
+ if (confirmationTarget < this.config.minConfTarget)
403
+ throw {
404
+ code: 20024,
405
+ msg: "Invalid request body (confirmationTarget - too low)"
406
+ };
407
+ }
408
+ /**
409
+ * Checks if the required confirmations are within configured bounds
410
+ *
411
+ * @param confirmations
412
+ * @throws {DefinedRuntimeError} will throw an error if the confirmations are out of bounds
413
+ */
414
+ checkRequiredConfirmations(confirmations) {
415
+ if (confirmations > this.config.maxConfirmations)
416
+ throw {
417
+ code: 20025,
418
+ msg: "Invalid request body (confirmations - too high)"
419
+ };
420
+ if (confirmations < this.config.minConfirmations)
421
+ throw {
422
+ code: 20026,
423
+ msg: "Invalid request body (confirmations - too low)"
424
+ };
425
+ }
426
+ /**
427
+ * Checks the validity of the provided address, also checks if the resulting output script isn't too large
428
+ *
429
+ * @param address
430
+ * @throws {DefinedRuntimeError} will throw an error if the address is invalid
431
+ */
432
+ checkAddress(address) {
433
+ let parsedOutputScript;
434
+ try {
435
+ parsedOutputScript = this.bitcoin.toOutputScript(address);
436
+ }
437
+ catch (e) {
438
+ throw {
439
+ code: 20031,
440
+ msg: "Invalid request body (address - cannot be parsed)"
441
+ };
442
+ }
443
+ if (parsedOutputScript.length > OUTPUT_SCRIPT_MAX_LENGTH)
444
+ throw {
445
+ code: 20032,
446
+ msg: "Invalid request body (address's output script - too long)"
447
+ };
448
+ }
449
+ /**
450
+ * Checks if the swap is expired, taking into consideration on-chain time skew
451
+ *
452
+ * @param swap
453
+ * @throws {DefinedRuntimeError} will throw an error if the swap is expired
454
+ */
455
+ async checkExpired(swap) {
456
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
457
+ const isExpired = await swapContract.isExpired(signer.getAddress(), swap.data);
458
+ if (isExpired)
459
+ throw {
460
+ _httpStatus: 200,
461
+ code: 20010,
462
+ msg: "Payment expired"
463
+ };
464
+ }
465
+ /**
466
+ * Checks & returns the network fee needed for a transaction
467
+ *
468
+ * @param address
469
+ * @param amount
470
+ * @throws {DefinedRuntimeError} will throw an error if there are not enough BTC funds
471
+ */
472
+ async checkAndGetNetworkFee(address, amount) {
473
+ let chainFeeResp = await this.bitcoin.estimateFee(address, Number(amount), null, this.config.networkFeeMultiplier);
474
+ const hasEnoughFunds = chainFeeResp != null;
475
+ if (!hasEnoughFunds)
476
+ throw {
477
+ code: 20002,
478
+ msg: "Not enough liquidity"
479
+ };
480
+ return {
481
+ networkFee: BigInt(chainFeeResp.networkFee),
482
+ satsPerVbyte: BigInt(chainFeeResp.satsPerVbyte)
483
+ };
484
+ }
485
+ startRestServer(restServer) {
486
+ restServer.use(this.path + "/payInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
487
+ restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
488
+ const metadata = { request: {}, times: {} };
489
+ const chainIdentifier = req.query.chain ?? this.chains.default;
490
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
491
+ metadata.times.requestReceived = Date.now();
492
+ /**
493
+ *Sent initially:
494
+ * address: string Bitcoin destination address
495
+ * amount: string Amount to send (in satoshis)
496
+ * confirmationTarget: number Desired confirmation target for the swap, how big of a fee should be assigned to TX
497
+ * confirmations: number Required number of confirmations for us to claim the swap
498
+ * nonce: string Nonce for the swap (used for replay protection)
499
+ * token: string Desired token to use
500
+ * offerer: string Address of the caller
501
+ * exactIn: boolean Whether the swap should be an exact in instead of exact out swap
502
+ *
503
+ *Sent later:
504
+ * feeRate: string Fee rate to use for the init signature
505
+ */
506
+ const parsedBody = await req.paramReader.getParams({
507
+ address: SchemaVerifier_1.FieldTypeEnum.String,
508
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
509
+ confirmationTarget: SchemaVerifier_1.FieldTypeEnum.Number,
510
+ confirmations: SchemaVerifier_1.FieldTypeEnum.Number,
511
+ nonce: SchemaVerifier_1.FieldTypeEnum.BigInt,
512
+ token: (val) => val != null &&
513
+ typeof (val) === "string" &&
514
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
515
+ offerer: (val) => val != null &&
516
+ typeof (val) === "string" &&
517
+ chainInterface.isValidAddress(val) ? val : null,
518
+ exactIn: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
519
+ });
520
+ if (parsedBody == null)
521
+ throw {
522
+ code: 20100,
523
+ msg: "Invalid request body"
524
+ };
525
+ metadata.request = parsedBody;
526
+ const requestedAmount = { input: !!parsedBody.exactIn, amount: parsedBody.amount, token: parsedBody.token };
527
+ const request = {
528
+ chainIdentifier,
529
+ raw: req,
530
+ parsed: parsedBody,
531
+ metadata
532
+ };
533
+ const useToken = parsedBody.token;
534
+ const responseStream = res.responseStream;
535
+ this.checkNonceValid(parsedBody.nonce);
536
+ this.checkConfirmationTarget(parsedBody.confirmationTarget);
537
+ this.checkRequiredConfirmations(parsedBody.confirmations);
538
+ this.checkAddress(parsedBody.address);
539
+ await this.checkVaultInitialized(chainIdentifier, parsedBody.token);
540
+ const fees = await this.AmountAssertions.preCheckToBtcAmounts(this.type, request, requestedAmount);
541
+ metadata.times.requestChecked = Date.now();
542
+ //Initialize abort controller for the parallel async operations
543
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
544
+ const { pricePrefetchPromise, signDataPrefetchPromise } = this.getToBtcPrefetches(chainIdentifier, useToken, responseStream, abortController);
545
+ const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = await this.AmountAssertions.checkToBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, async (amount) => {
546
+ metadata.times.amountsChecked = Date.now();
547
+ const resp = await this.checkAndGetNetworkFee(parsedBody.address, amount);
548
+ this.logger.debug("checkToBtcAmount(): network fee calculated, amount: " + amount.toString(10) + " fee: " + resp.networkFee.toString(10));
549
+ metadata.times.chainFeeCalculated = Date.now();
550
+ return resp;
551
+ }, abortController.signal);
552
+ metadata.times.priceCalculated = Date.now();
553
+ const paymentHash = this.getHash(chainIdentifier, parsedBody.address, parsedBody.confirmations, parsedBody.nonce, amountBD).toString("hex");
554
+ //Add grace period another time, so the user has 1 hour to commit
555
+ const expirySeconds = this.getExpiryFromCLTV(parsedBody.confirmationTarget, parsedBody.confirmations) + this.config.gracePeriod;
556
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
557
+ const minRequiredExpiry = currentTimestamp + expirySeconds;
558
+ const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
559
+ const payObject = await swapContract.createSwapData(base_1.ChainSwapType.CHAIN_NONCED, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, paymentHash, sequence, minRequiredExpiry, true, false, 0n, 0n);
560
+ abortController.signal.throwIfAborted();
561
+ metadata.times.swapCreated = Date.now();
562
+ const sigData = await this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
563
+ metadata.times.swapSigned = Date.now();
564
+ const createdSwap = new ToBtcSwapAbs_1.ToBtcSwapAbs(chainIdentifier, parsedBody.address, amountBD, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken, networkFeeData.satsPerVbyte, parsedBody.nonce, parsedBody.confirmations, parsedBody.confirmationTarget);
565
+ createdSwap.data = payObject;
566
+ createdSwap.metadata = metadata;
567
+ createdSwap.prefix = sigData.prefix;
568
+ createdSwap.timeout = sigData.timeout;
569
+ createdSwap.signature = sigData.signature;
570
+ createdSwap.feeRate = sigData.feeRate;
571
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
572
+ await this.saveSwapData(createdSwap);
573
+ this.swapLogger.info(createdSwap, "REST: /payInvoice: created swap address: " + createdSwap.address + " amount: " + amountBD.toString(10));
574
+ await responseStream.writeParamsAndEnd({
575
+ code: 20000,
576
+ msg: "Success",
577
+ data: {
578
+ amount: amountBD.toString(10),
579
+ address: signer.getAddress(),
580
+ satsPervByte: networkFeeData.satsPerVbyte.toString(10),
581
+ networkFee: networkFeeInToken.toString(10),
582
+ swapFee: swapFeeInToken.toString(10),
583
+ totalFee: (swapFeeInToken + networkFeeInToken).toString(10),
584
+ total: totalInToken.toString(10),
585
+ minRequiredExpiry: minRequiredExpiry.toString(10),
586
+ data: payObject.serialize(),
587
+ prefix: sigData.prefix,
588
+ timeout: sigData.timeout,
589
+ signature: sigData.signature
590
+ }
591
+ });
592
+ }));
593
+ const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
594
+ /**
595
+ * paymentHash: string Payment hash identifier of the swap
596
+ * sequence: BN Sequence identifier of the swap
597
+ */
598
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
599
+ paymentHash: (val) => val != null &&
600
+ typeof (val) === "string" &&
601
+ Utils_1.HEX_REGEX.test(val) ? val : null,
602
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt
603
+ });
604
+ if (parsedBody == null)
605
+ throw {
606
+ code: 20100,
607
+ msg: "Invalid request body/query (paymentHash/sequence)"
608
+ };
609
+ this.checkSequence(parsedBody.sequence);
610
+ const payment = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
611
+ if (payment == null || payment.state === ToBtcSwapAbs_1.ToBtcSwapState.SAVED)
612
+ throw {
613
+ _httpStatus: 200,
614
+ code: 20007,
615
+ msg: "Payment not found"
616
+ };
617
+ await this.checkExpired(payment);
618
+ if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.COMMITED)
619
+ throw {
620
+ _httpStatus: 200,
621
+ code: 20008,
622
+ msg: "Payment processing"
623
+ };
624
+ if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENT || payment.state === ToBtcSwapAbs_1.ToBtcSwapState.BTC_SENDING)
625
+ throw {
626
+ _httpStatus: 200,
627
+ code: 20006,
628
+ msg: "Already paid",
629
+ data: {
630
+ txId: payment.txId
631
+ }
632
+ };
633
+ const { swapContract, signer } = this.getChain(payment.chainIdentifier);
634
+ if (payment.state === ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE) {
635
+ const isCommited = await swapContract.isCommited(payment.data);
636
+ if (!isCommited)
637
+ throw {
638
+ code: 20005,
639
+ msg: "Not committed"
640
+ };
641
+ const refundResponse = await swapContract.getRefundSignature(signer, payment.data, this.config.refundAuthorizationTimeout);
642
+ //Double check the state after promise result
643
+ if (payment.state !== ToBtcSwapAbs_1.ToBtcSwapState.NON_PAYABLE)
644
+ throw {
645
+ code: 20005,
646
+ msg: "Not committed"
647
+ };
648
+ this.swapLogger.info(payment, "REST: /getRefundAuthorization: returning refund authorization, because swap is in NON_PAYABLE state, address: " + payment.address);
649
+ res.status(200).json({
650
+ code: 20000,
651
+ msg: "Success",
652
+ data: {
653
+ address: signer.getAddress(),
654
+ prefix: refundResponse.prefix,
655
+ timeout: refundResponse.timeout,
656
+ signature: refundResponse.signature
657
+ }
658
+ });
659
+ return;
660
+ }
661
+ throw {
662
+ _httpStatus: 500,
663
+ code: 20009,
664
+ msg: "Invalid payment status"
665
+ };
666
+ });
667
+ restServer.post(this.path + "/getRefundAuthorization", getRefundAuthorization);
668
+ restServer.get(this.path + "/getRefundAuthorization", getRefundAuthorization);
669
+ this.logger.info("started at path: ", this.path);
670
+ }
671
+ /**
672
+ * Starts watchdog checking sent bitcoin transactions
673
+ */
674
+ async startTxTimer() {
675
+ let rerun;
676
+ rerun = async () => {
677
+ await this.processBtcTxs().catch(e => this.logger.error("startTxTimer(): call to processBtcTxs() errored", e));
678
+ setTimeout(rerun, this.config.txCheckInterval);
679
+ };
680
+ await rerun();
681
+ }
682
+ async startWatchdog() {
683
+ await super.startWatchdog();
684
+ await this.startTxTimer();
685
+ }
686
+ async init() {
687
+ await this.loadData(ToBtcSwapAbs_1.ToBtcSwapAbs);
688
+ this.subscribeToEvents();
689
+ await PluginManager_1.PluginManager.serviceInitialize(this);
690
+ }
691
+ getInfoData() {
692
+ return {
693
+ minCltv: Number(this.config.minChainCltv),
694
+ minConfirmations: this.config.minConfirmations,
695
+ maxConfirmations: this.config.maxConfirmations,
696
+ minConfTarget: this.config.minConfTarget,
697
+ maxConfTarget: this.config.maxConfTarget,
698
+ maxOutputScriptLen: OUTPUT_SCRIPT_MAX_LENGTH
699
+ };
700
+ }
701
+ }
702
+ exports.ToBtcAbs = ToBtcAbs;