@atomiqlabs/lp-lib 17.5.1 → 17.5.2

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