@atomiqlabs/lp-lib 14.0.0-dev.21 → 14.0.0-dev.24

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