@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,719 +1,719 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromBtcLnAbs = void 0;
4
- const crypto_1 = require("crypto");
5
- const FromBtcLnSwapAbs_1 = require("./FromBtcLnSwapAbs");
6
- const SwapHandler_1 = require("../../SwapHandler");
7
- const base_1 = require("@atomiqlabs/base");
8
- const Utils_1 = require("../../../utils/Utils");
9
- const PluginManager_1 = require("../../../plugins/PluginManager");
10
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
- const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
- const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
- const LightningAssertions_1 = require("../../assertions/LightningAssertions");
14
- const IPlugin_1 = require("../../../plugins/IPlugin");
15
- /**
16
- * Swap handler handling from BTCLN swaps using submarine swaps
17
- */
18
- class FromBtcLnAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
19
- constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
20
- super(storageDirectory, path, chains, swapPricing, config);
21
- this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN;
22
- this.swapType = base_1.ChainSwapType.HTLC;
23
- this.inflightSwapStates = new Set([FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED, FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED, FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED]);
24
- this.config = config;
25
- this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
26
- this.lightning = lightning;
27
- this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
28
- }
29
- async processPastSwap(swap) {
30
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
31
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
32
- //Check if already paid
33
- const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
34
- const invoice = await this.lightning.getInvoice(parsedPR.id);
35
- const isBeingPaid = invoice.status === "held";
36
- if (!isBeingPaid) {
37
- //Not paid
38
- const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
39
- if (!isInvoiceExpired)
40
- return null;
41
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
42
- await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
43
- return "CANCEL";
44
- }
45
- //Adjust the state of the swap and expiry
46
- try {
47
- await this.htlcReceived(swap, invoice);
48
- //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
49
- }
50
- catch (e) {
51
- this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
52
- }
53
- return null;
54
- }
55
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED || swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED) {
56
- const onchainStatus = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
57
- const state = swap.state;
58
- if (onchainStatus.type === base_1.SwapCommitStateType.PAID) {
59
- //Extract the swap secret
60
- if (state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED && state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED) {
61
- const secretHex = await onchainStatus.getClaimResult();
62
- const secret = Buffer.from(secretHex, "hex");
63
- const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
64
- const paymentHashHex = paymentHash.toString("hex");
65
- if (swap.lnPaymentHash !== paymentHashHex) {
66
- //TODO: Possibly fatal failure
67
- this.swapLogger.error(swap, "processPastSwap(state=RECEIVED|COMMITED): onchainStatus=PAID, Invalid swap secret specified: " + secretHex + " for paymentHash: " + paymentHashHex);
68
- return null;
69
- }
70
- swap.secret = secretHex;
71
- await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED);
72
- await this.saveSwapData(swap);
73
- this.swapLogger.warn(swap, "processPastSwap(state=RECEIVED|COMMITED): swap settled (detected from processPastSwap), invoice: " + swap.pr);
74
- return "SETTLE";
75
- }
76
- return null;
77
- }
78
- if (onchainStatus.type === base_1.SwapCommitStateType.COMMITED) {
79
- if (state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
80
- await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED);
81
- await this.saveSwapData(swap);
82
- this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
83
- }
84
- return null;
85
- }
86
- if (onchainStatus.type === base_1.SwapCommitStateType.NOT_COMMITED || onchainStatus.type === base_1.SwapCommitStateType.EXPIRED) {
87
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
88
- const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
89
- if (isAuthorizationExpired) {
90
- this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap not committed before authorization expiry, cancelling the LN invoice, invoice: " + swap.pr);
91
- await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
92
- return "CANCEL";
93
- }
94
- }
95
- else {
96
- if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
97
- this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
98
- return "REFUND";
99
- }
100
- }
101
- }
102
- if (onchainStatus.type === base_1.SwapCommitStateType.REFUNDABLE) {
103
- this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
104
- return "REFUND";
105
- }
106
- }
107
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED)
108
- return "SETTLE";
109
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED)
110
- return "CANCEL";
111
- }
112
- async refundSwaps(refundSwaps) {
113
- for (let refundSwap of refundSwaps) {
114
- const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
115
- const unlock = refundSwap.lock(swapContract.refundTimeout);
116
- if (unlock == null)
117
- continue;
118
- this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
119
- await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
120
- this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: " + refundSwap.pr);
121
- await refundSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.REFUNDED);
122
- unlock();
123
- }
124
- }
125
- async cancelInvoices(swaps) {
126
- for (let swap of swaps) {
127
- //Refund
128
- const paymentHash = swap.lnPaymentHash;
129
- try {
130
- await this.lightning.cancelHodlInvoice(paymentHash);
131
- this.swapLogger.info(swap, "cancelInvoices(): invoice cancelled!");
132
- await this.removeSwapData(swap);
133
- }
134
- catch (e) {
135
- this.swapLogger.error(swap, "cancelInvoices(): cannot cancel hodl invoice id", e);
136
- }
137
- }
138
- }
139
- async settleInvoices(swaps) {
140
- for (let swap of swaps) {
141
- try {
142
- await this.lightning.settleHodlInvoice(swap.secret);
143
- if (swap.metadata != null)
144
- swap.metadata.times.htlcSettled = Date.now();
145
- await this.removeSwapData(swap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED);
146
- this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: " + swap.secret);
147
- }
148
- catch (e) {
149
- this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
150
- }
151
- }
152
- }
153
- /**
154
- * Checks past swaps, refunds and deletes ones that are already expired.
155
- */
156
- async processPastSwaps() {
157
- const settleInvoices = [];
158
- const cancelInvoices = [];
159
- const refundSwaps = [];
160
- const queriedData = await this.storageManager.query([
161
- {
162
- key: "state",
163
- value: [
164
- FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED,
165
- FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED,
166
- FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED,
167
- FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED,
168
- FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED,
169
- ]
170
- }
171
- ]);
172
- for (let { obj: swap } of queriedData) {
173
- switch (await this.processPastSwap(swap)) {
174
- case "CANCEL":
175
- cancelInvoices.push(swap);
176
- break;
177
- case "SETTLE":
178
- settleInvoices.push(swap);
179
- break;
180
- case "REFUND":
181
- refundSwaps.push(swap);
182
- break;
183
- }
184
- }
185
- await this.refundSwaps(refundSwaps);
186
- await this.cancelInvoices(cancelInvoices);
187
- await this.settleInvoices(settleInvoices);
188
- }
189
- async processInitializeEvent(chainIdentifier, savedSwap, event) {
190
- this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: " + savedSwap.pr);
191
- if (savedSwap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
192
- await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED);
193
- await this.saveSwapData(savedSwap);
194
- }
195
- }
196
- async processClaimEvent(chainIdentifier, savedSwap, event) {
197
- //Claim
198
- //This is the important part, we need to catch the claim TX, else we may lose money
199
- const secret = Buffer.from(event.result, "hex");
200
- const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
201
- const secretHex = secret.toString("hex");
202
- const paymentHashHex = paymentHash.toString("hex");
203
- if (savedSwap.lnPaymentHash !== paymentHashHex)
204
- return;
205
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: " + savedSwap.pr);
206
- try {
207
- await this.lightning.settleHodlInvoice(secretHex);
208
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: " + secretHex);
209
- savedSwap.secret = secretHex;
210
- if (savedSwap.metadata != null)
211
- savedSwap.metadata.times.htlcSettled = Date.now();
212
- await this.removeSwapData(savedSwap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED);
213
- }
214
- catch (e) {
215
- this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
216
- savedSwap.secret = secretHex;
217
- await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED);
218
- await this.saveSwapData(savedSwap);
219
- }
220
- }
221
- async processRefundEvent(chainIdentifier, savedSwap, event) {
222
- this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: " + savedSwap.pr);
223
- try {
224
- await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
225
- this.swapLogger.info(savedSwap, "SC: RefundEvent: invoice cancelled");
226
- await this.removeSwapData(savedSwap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.REFUNDED);
227
- }
228
- catch (e) {
229
- this.swapLogger.error(savedSwap, "SC: RefundEvent: cannot cancel invoice", e);
230
- await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
231
- // await PluginManager.swapStateChange(savedSwap);
232
- await this.saveSwapData(savedSwap);
233
- }
234
- }
235
- /**
236
- * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
237
- * smart chain authorization starts ticking as soon as this HTLC is received
238
- *
239
- * @param invoiceData
240
- * @param invoice
241
- */
242
- async htlcReceived(invoiceData, invoice) {
243
- this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
244
- if (invoiceData.metadata != null)
245
- invoiceData.metadata.times.htlcReceived = Date.now();
246
- const useToken = invoiceData.token;
247
- const escrowAmount = invoiceData.totalTokens;
248
- try {
249
- this.checkTooManyInflightSwaps();
250
- }
251
- catch (e) {
252
- if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
253
- invoiceData.metadata.htlcReceiveError = e;
254
- if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
255
- await this.cancelSwapAndInvoice(invoiceData);
256
- throw e;
257
- }
258
- //Create abort controller for parallel fetches
259
- const abortController = new AbortController();
260
- //Pre-fetch data
261
- const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
262
- const blockheightPrefetch = this.getBlockheightPrefetch(abortController);
263
- const signDataPrefetchPromise = this.getSignDataPrefetch(invoiceData.chainIdentifier, abortController);
264
- let expiryTimeout;
265
- try {
266
- //Check if we have enough liquidity to proceed
267
- await this.checkBalance(escrowAmount, balancePrefetch, abortController.signal);
268
- if (invoiceData.metadata != null)
269
- invoiceData.metadata.times.htlcBalanceChecked = Date.now();
270
- //Check if HTLC expiry is long enough
271
- expiryTimeout = await this.checkHtlcExpiry(invoice, blockheightPrefetch, abortController.signal);
272
- if (invoiceData.metadata != null)
273
- invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
274
- }
275
- catch (e) {
276
- if (!abortController.signal.aborted) {
277
- if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
278
- invoiceData.metadata.htlcReceiveError = e;
279
- if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
280
- await this.cancelSwapAndInvoice(invoiceData);
281
- }
282
- throw e;
283
- }
284
- const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
285
- //Create real swap data
286
- const payInvoiceObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), invoiceData.claimer, useToken, escrowAmount, invoiceData.claimHash, 0n, BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout, false, true, invoiceData.securityDeposit, 0n, invoiceData.depositToken);
287
- abortController.signal.throwIfAborted();
288
- if (invoiceData.metadata != null)
289
- invoiceData.metadata.times.htlcSwapCreated = Date.now();
290
- //Sign swap data
291
- const sigData = await swapContract.getInitSignature(signer, payInvoiceObject, this.getInitAuthorizationTimeout(invoiceData.chainIdentifier), signDataPrefetchPromise == null ? null : await signDataPrefetchPromise, invoiceData.feeRate);
292
- //No need to check abortController anymore since all pending promises are resolved by now
293
- if (invoiceData.metadata != null)
294
- invoiceData.metadata.times.htlcSwapSigned = Date.now();
295
- const pluginCheckResult = await PluginManager_1.PluginManager.onHandlePreFromBtcExecute(SwapHandler_1.SwapHandlerType.FROM_BTCLN, invoiceData);
296
- if ((0, IPlugin_1.isQuoteThrow)(pluginCheckResult)) {
297
- const error = {
298
- code: 29999,
299
- msg: pluginCheckResult.message
300
- };
301
- if (invoiceData.metadata != null)
302
- invoiceData.metadata.htlcReceiveError = error;
303
- if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
304
- await this.cancelSwapAndInvoice(invoiceData);
305
- throw error;
306
- }
307
- //Important to prevent race condition and issuing 2 signed init messages at the same time
308
- if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
309
- //Re-check right before signing
310
- try {
311
- this.checkTooManyInflightSwaps();
312
- }
313
- catch (e) {
314
- if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
315
- invoiceData.metadata.htlcReceiveError = e;
316
- if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
317
- await this.cancelSwapAndInvoice(invoiceData);
318
- throw e;
319
- }
320
- invoiceData.data = payInvoiceObject;
321
- invoiceData.prefix = sigData.prefix;
322
- invoiceData.timeout = sigData.timeout;
323
- invoiceData.signature = sigData.signature;
324
- //Setting the state variable is done outside the promise, so is done synchronously
325
- await invoiceData.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED);
326
- await this.saveSwapData(invoiceData);
327
- return;
328
- }
329
- }
330
- /**
331
- * Checks invoice description
332
- *
333
- * @param description
334
- * @throws {DefinedRuntimeError} will throw an error if the description is invalid
335
- */
336
- checkDescription(description) {
337
- if (description != null && Buffer.byteLength(description, "utf8") > 500) {
338
- throw {
339
- code: 20100,
340
- msg: "Invalid request body (description)"
341
- };
342
- }
343
- }
344
- /**
345
- * Checks invoice description hash
346
- *
347
- * @param descriptionHash
348
- * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
349
- */
350
- checkDescriptionHash(descriptionHash) {
351
- if (descriptionHash != null) {
352
- if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
353
- throw {
354
- code: 20100,
355
- msg: "Invalid request body (descriptionHash)"
356
- };
357
- }
358
- }
359
- }
360
- /**
361
- * Starts LN channels pre-fetch
362
- *
363
- * @param abortController
364
- */
365
- getBlockheightPrefetch(abortController) {
366
- return this.lightning.getBlockheight().catch(e => {
367
- this.logger.error("getBlockheightPrefetch(): error", e);
368
- abortController.abort(e);
369
- return null;
370
- });
371
- }
372
- /**
373
- * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
374
- *
375
- * @param responseStream
376
- */
377
- sendPublicKeyAsync(responseStream) {
378
- this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
379
- lnPublicKey: publicKey
380
- })).catch(e => {
381
- this.logger.error("sendPublicKeyAsync(): error", e);
382
- });
383
- }
384
- /**
385
- * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
386
- * received (MPP) it returns the lowest of the timeouts
387
- *
388
- * @param invoice
389
- */
390
- getInvoicePaymentsTimeout(invoice) {
391
- let timeout = null;
392
- invoice.payments.forEach((curr) => {
393
- if (timeout == null || timeout > curr.timeout)
394
- timeout = curr.timeout;
395
- });
396
- return timeout;
397
- }
398
- /**
399
- * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
400
- *
401
- * @param invoice
402
- * @param blockheightPrefetch
403
- * @param signal
404
- * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
405
- * @returns expiry timeout in seconds
406
- */
407
- async checkHtlcExpiry(invoice, blockheightPrefetch, signal) {
408
- const timeout = this.getInvoicePaymentsTimeout(invoice);
409
- const current_block_height = await blockheightPrefetch;
410
- signal.throwIfAborted();
411
- const blockDelta = BigInt(timeout - current_block_height);
412
- const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
413
- if (htlcExpiresTooSoon) {
414
- throw {
415
- code: 20002,
416
- msg: "Not enough time to reliably process the swap",
417
- data: {
418
- requiredDelta: this.config.minCltv.toString(10),
419
- actualDelta: blockDelta.toString(10)
420
- }
421
- };
422
- }
423
- return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
424
- }
425
- /**
426
- * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
427
- *
428
- * @param invoiceData
429
- */
430
- async cancelSwapAndInvoice(invoiceData) {
431
- if (invoiceData.state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
432
- return;
433
- await invoiceData.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
434
- await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
435
- await this.removeSwapData(invoiceData);
436
- this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
437
- }
438
- ;
439
- getDummySwapData(chainIdentifier, useToken, address, paymentHash) {
440
- const { swapContract, signer } = this.getChain(chainIdentifier);
441
- const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
442
- return swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForHtlc(Buffer.from(paymentHash, "hex")).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)), false, true, BigInt(Math.floor(Math.random() * 0x10000)), 0n);
443
- }
444
- /**
445
- *
446
- * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
447
- *
448
- * @param paymentHash
449
- * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
450
- * @returns the fetched lightning invoice
451
- */
452
- async checkInvoiceStatus(paymentHash) {
453
- const invoice = await this.lightning.getInvoice(paymentHash);
454
- if (invoice == null)
455
- throw {
456
- _httpStatus: 200,
457
- code: 10001,
458
- msg: "Invoice expired/canceled"
459
- };
460
- switch (invoice.status) {
461
- case "canceled":
462
- throw {
463
- _httpStatus: 200,
464
- code: 10001,
465
- msg: "Invoice expired/canceled"
466
- };
467
- case "confirmed":
468
- throw {
469
- _httpStatus: 200,
470
- code: 10002,
471
- msg: "Invoice already paid"
472
- };
473
- case "unpaid":
474
- throw {
475
- _httpStatus: 200,
476
- code: 10003,
477
- msg: "Invoice yet unpaid"
478
- };
479
- default:
480
- return invoice;
481
- }
482
- }
483
- startRestServer(restServer) {
484
- restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
485
- restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
486
- const metadata = { request: {}, times: {} };
487
- const chainIdentifier = req.query.chain;
488
- const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
489
- const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
490
- this.checkAllowedDepositToken(chainIdentifier, depositToken);
491
- metadata.times.requestReceived = Date.now();
492
- /**
493
- * address: string solana address of the recipient
494
- * paymentHash: string payment hash of the to-be-created invoice
495
- * amount: string amount (in sats) of the invoice
496
- * token: string Desired token to swap
497
- * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
498
- * description: string Description of the invoice (max 500 bytes)
499
- * descriptionHash: string Description hash of the invoice
500
- *
501
- *Sent later:
502
- * feeRate: string Fee rate to use for the init signature
503
- */
504
- const parsedBody = await req.paramReader.getParams({
505
- address: (val) => val != null &&
506
- typeof (val) === "string" &&
507
- chainInterface.isValidAddress(val, true) ? val : null,
508
- paymentHash: (val) => val != null &&
509
- typeof (val) === "string" &&
510
- val.length === 64 &&
511
- Utils_1.HEX_REGEX.test(val) ? val : null,
512
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
513
- token: (val) => val != null &&
514
- typeof (val) === "string" &&
515
- this.isTokenSupported(chainIdentifier, val) ? val : null,
516
- descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
517
- exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
518
- });
519
- if (parsedBody == null)
520
- throw {
521
- code: 20100,
522
- msg: "Invalid request body"
523
- };
524
- metadata.request = parsedBody;
525
- const descriptionBodyPart = req.paramReader.getExistingParamsOrNull({
526
- description: SchemaVerifier_1.FieldTypeEnum.StringOptional
527
- });
528
- const description = descriptionBodyPart?.description;
529
- const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
530
- const request = {
531
- chainIdentifier,
532
- raw: req,
533
- parsed: parsedBody,
534
- metadata
535
- };
536
- const useToken = parsedBody.token;
537
- //Check request params
538
- this.checkTooManyInflightSwaps();
539
- this.checkDescription(description);
540
- this.checkDescriptionHash(parsedBody.descriptionHash);
541
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
542
- metadata.times.requestChecked = Date.now();
543
- //Create abortController for parallel prefetches
544
- const responseStream = res.responseStream;
545
- const abortController = (0, Utils_1.getAbortController)(responseStream);
546
- //Pre-fetch data
547
- const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
548
- const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
549
- const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
550
- const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
551
- const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address, parsedBody.paymentHash);
552
- abortController.signal.throwIfAborted();
553
- const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
554
- //Asynchronously send the node's public key to the client
555
- this.sendPublicKeyAsync(responseStream);
556
- await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
557
- //Check valid amount specified (min/max)
558
- const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
559
- metadata.times.priceCalculated = Date.now();
560
- if (securityDepositApyPPM != null)
561
- fees.securityDepositApyPPM = securityDepositApyPPM;
562
- if (securityDepositBaseMultiplierPPM != null)
563
- fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
564
- //Check if we have enough funds to honor the request
565
- await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
566
- await this.LightningAssertions.checkInboundLiquidity(amountBD, channelsPrefetch, abortController.signal);
567
- metadata.times.balanceChecked = Date.now();
568
- //Create swap
569
- const hodlInvoiceObj = {
570
- description: description ?? (chainIdentifier + "-" + parsedBody.address),
571
- cltvDelta: Number(this.config.minCltv) + 5,
572
- expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
573
- id: parsedBody.paymentHash,
574
- mtokens: amountBD * 1000n,
575
- descriptionHash: parsedBody.descriptionHash
576
- };
577
- metadata.invoiceRequest = hodlInvoiceObj;
578
- const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
579
- abortController.signal.throwIfAborted();
580
- metadata.times.invoiceCreated = Date.now();
581
- metadata.invoiceResponse = { ...hodlInvoice };
582
- //Pre-compute the security deposit
583
- const expiryTimeout = (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
584
- const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
585
- metadata.times.securityDepositCalculated = Date.now();
586
- const createdSwap = new FromBtcLnSwapAbs_1.FromBtcLnSwapAbs(chainIdentifier, hodlInvoice.request, parsedBody.paymentHash, hodlInvoice.mtokens, swapFee, swapFeeInToken, parsedBody.address, useToken, totalInToken, swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"), totalSecurityDeposit, depositToken);
587
- metadata.times.swapCreated = Date.now();
588
- createdSwap.metadata = metadata;
589
- //Save the desired fee rate for the signature
590
- const feeRateObj = await req.paramReader.getParams({
591
- feeRate: SchemaVerifier_1.FieldTypeEnum.String
592
- }).catch(() => null);
593
- abortController.signal.throwIfAborted();
594
- createdSwap.feeRate = feeRateObj?.feeRate != null && typeof (feeRateObj.feeRate) === "string" ? feeRateObj.feeRate : null;
595
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
596
- await this.saveSwapData(createdSwap);
597
- this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + amountBD.toString(10));
598
- await responseStream.writeParamsAndEnd({
599
- code: 20000,
600
- msg: "Success",
601
- data: {
602
- pr: hodlInvoice.request,
603
- swapFee: swapFeeInToken.toString(10),
604
- total: totalInToken.toString(10),
605
- intermediaryKey: signer.getAddress(),
606
- securityDeposit: totalSecurityDeposit.toString(10)
607
- }
608
- });
609
- }));
610
- const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
611
- /**
612
- * paymentHash: string payment hash of the invoice
613
- */
614
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
615
- paymentHash: (val) => val != null &&
616
- typeof (val) === "string" &&
617
- val.length === 64 &&
618
- Utils_1.HEX_REGEX.test(val) ? val : null,
619
- });
620
- await this.checkInvoiceStatus(parsedBody.paymentHash);
621
- res.status(200).json({
622
- code: 10000,
623
- msg: "Success"
624
- });
625
- });
626
- restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
627
- restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
628
- const getInvoicePaymentAuth = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
629
- /**
630
- * paymentHash: string payment hash of the invoice
631
- */
632
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
633
- paymentHash: (val) => val != null &&
634
- typeof (val) === "string" &&
635
- val.length === 64 &&
636
- Utils_1.HEX_REGEX.test(val) ? val : null,
637
- });
638
- const invoice = await this.checkInvoiceStatus(parsedBody.paymentHash);
639
- const swap = await this.storageManager.getData(parsedBody.paymentHash, null);
640
- if (swap == null)
641
- throw {
642
- _httpStatus: 200,
643
- code: 10001,
644
- msg: "Invoice expired/canceled"
645
- };
646
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
647
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
648
- if (await swapContract.isInitAuthorizationExpired(swap.data, swap))
649
- throw {
650
- _httpStatus: 200,
651
- code: 10001,
652
- msg: "Invoice expired/canceled"
653
- };
654
- }
655
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
656
- try {
657
- await this.htlcReceived(swap, invoice);
658
- }
659
- catch (e) {
660
- if ((0, Utils_1.isDefinedRuntimeError)(e))
661
- e._httpStatus = 200;
662
- throw e;
663
- }
664
- this.swapLogger.info(swap, "REST: /getInvoicePaymentAuth: swap processed through htlcReceived, invoice: " + swap.pr);
665
- }
666
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED)
667
- throw {
668
- _httpStatus: 200,
669
- code: 10001,
670
- msg: "Invoice expired/canceled"
671
- };
672
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED)
673
- throw {
674
- _httpStatus: 200,
675
- code: 10004,
676
- msg: "Invoice already committed"
677
- };
678
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED)
679
- throw {
680
- _httpStatus: 200,
681
- code: 10005,
682
- msg: "Invoice already committed & claimed"
683
- };
684
- if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED)
685
- res.status(200).json({
686
- code: 10000,
687
- msg: "Success",
688
- data: {
689
- address: signer.getAddress(),
690
- data: swap.data.serialize(),
691
- prefix: swap.prefix,
692
- timeout: swap.timeout,
693
- signature: swap.signature
694
- }
695
- });
696
- });
697
- restServer.post(this.path + "/getInvoicePaymentAuth", getInvoicePaymentAuth);
698
- restServer.get(this.path + "/getInvoicePaymentAuth", getInvoicePaymentAuth);
699
- this.logger.info("started at path: ", this.path);
700
- }
701
- async init() {
702
- await this.loadData(FromBtcLnSwapAbs_1.FromBtcLnSwapAbs);
703
- //Check if all swaps contain a valid amount
704
- for (let { obj: swap } of await this.storageManager.query([])) {
705
- if (swap.amount == null) {
706
- const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
707
- swap.amount = (parsedPR.mtokens + 999n) / 1000n;
708
- }
709
- }
710
- this.subscribeToEvents();
711
- await PluginManager_1.PluginManager.serviceInitialize(this);
712
- }
713
- getInfoData() {
714
- return {
715
- minCltv: Number(this.config.minCltv)
716
- };
717
- }
718
- }
719
- exports.FromBtcLnAbs = FromBtcLnAbs;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcLnAbs = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const FromBtcLnSwapAbs_1 = require("./FromBtcLnSwapAbs");
6
+ const SwapHandler_1 = require("../../SwapHandler");
7
+ const base_1 = require("@atomiqlabs/base");
8
+ const Utils_1 = require("../../../utils/Utils");
9
+ const PluginManager_1 = require("../../../plugins/PluginManager");
10
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
+ const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
+ const LightningAssertions_1 = require("../../assertions/LightningAssertions");
14
+ const IPlugin_1 = require("../../../plugins/IPlugin");
15
+ /**
16
+ * Swap handler handling from BTCLN swaps using submarine swaps
17
+ */
18
+ class FromBtcLnAbs extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
19
+ constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
20
+ super(storageDirectory, path, chains, swapPricing, config);
21
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN;
22
+ this.swapType = base_1.ChainSwapType.HTLC;
23
+ this.inflightSwapStates = new Set([FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED, FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED, FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED]);
24
+ this.config = config;
25
+ this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
26
+ this.lightning = lightning;
27
+ this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
28
+ }
29
+ async processPastSwap(swap) {
30
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
31
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
32
+ //Check if already paid
33
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
34
+ const invoice = await this.lightning.getInvoice(parsedPR.id);
35
+ const isBeingPaid = invoice.status === "held";
36
+ if (!isBeingPaid) {
37
+ //Not paid
38
+ const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
39
+ if (!isInvoiceExpired)
40
+ return null;
41
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
42
+ await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
43
+ return "CANCEL";
44
+ }
45
+ //Adjust the state of the swap and expiry
46
+ try {
47
+ await this.htlcReceived(swap, invoice);
48
+ //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
49
+ }
50
+ catch (e) {
51
+ this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
52
+ }
53
+ return null;
54
+ }
55
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED || swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED) {
56
+ const onchainStatus = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
57
+ const state = swap.state;
58
+ if (onchainStatus.type === base_1.SwapCommitStateType.PAID) {
59
+ //Extract the swap secret
60
+ if (state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED && state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED) {
61
+ const secretHex = await onchainStatus.getClaimResult();
62
+ const secret = Buffer.from(secretHex, "hex");
63
+ const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
64
+ const paymentHashHex = paymentHash.toString("hex");
65
+ if (swap.lnPaymentHash !== paymentHashHex) {
66
+ //TODO: Possibly fatal failure
67
+ this.swapLogger.error(swap, "processPastSwap(state=RECEIVED|COMMITED): onchainStatus=PAID, Invalid swap secret specified: " + secretHex + " for paymentHash: " + paymentHashHex);
68
+ return null;
69
+ }
70
+ swap.secret = secretHex;
71
+ await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED);
72
+ await this.saveSwapData(swap);
73
+ this.swapLogger.warn(swap, "processPastSwap(state=RECEIVED|COMMITED): swap settled (detected from processPastSwap), invoice: " + swap.pr);
74
+ return "SETTLE";
75
+ }
76
+ return null;
77
+ }
78
+ if (onchainStatus.type === base_1.SwapCommitStateType.COMMITED) {
79
+ if (state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
80
+ await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED);
81
+ await this.saveSwapData(swap);
82
+ this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
83
+ }
84
+ return null;
85
+ }
86
+ if (onchainStatus.type === base_1.SwapCommitStateType.NOT_COMMITED || onchainStatus.type === base_1.SwapCommitStateType.EXPIRED) {
87
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
88
+ const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
89
+ if (isAuthorizationExpired) {
90
+ this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap not committed before authorization expiry, cancelling the LN invoice, invoice: " + swap.pr);
91
+ await swap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
92
+ return "CANCEL";
93
+ }
94
+ }
95
+ else {
96
+ if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
97
+ this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
98
+ return "REFUND";
99
+ }
100
+ }
101
+ }
102
+ if (onchainStatus.type === base_1.SwapCommitStateType.REFUNDABLE) {
103
+ this.swapLogger.info(swap, "processPastSwap(state=RECEIVED|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
104
+ return "REFUND";
105
+ }
106
+ }
107
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED)
108
+ return "SETTLE";
109
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED)
110
+ return "CANCEL";
111
+ }
112
+ async refundSwaps(refundSwaps) {
113
+ for (let refundSwap of refundSwaps) {
114
+ const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
115
+ const unlock = refundSwap.lock(swapContract.refundTimeout);
116
+ if (unlock == null)
117
+ continue;
118
+ this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
119
+ await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
120
+ this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: " + refundSwap.pr);
121
+ await refundSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.REFUNDED);
122
+ unlock();
123
+ }
124
+ }
125
+ async cancelInvoices(swaps) {
126
+ for (let swap of swaps) {
127
+ //Refund
128
+ const paymentHash = swap.lnPaymentHash;
129
+ try {
130
+ await this.lightning.cancelHodlInvoice(paymentHash);
131
+ this.swapLogger.info(swap, "cancelInvoices(): invoice cancelled!");
132
+ await this.removeSwapData(swap);
133
+ }
134
+ catch (e) {
135
+ this.swapLogger.error(swap, "cancelInvoices(): cannot cancel hodl invoice id", e);
136
+ }
137
+ }
138
+ }
139
+ async settleInvoices(swaps) {
140
+ for (let swap of swaps) {
141
+ try {
142
+ await this.lightning.settleHodlInvoice(swap.secret);
143
+ if (swap.metadata != null)
144
+ swap.metadata.times.htlcSettled = Date.now();
145
+ await this.removeSwapData(swap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED);
146
+ this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: " + swap.secret);
147
+ }
148
+ catch (e) {
149
+ this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
150
+ }
151
+ }
152
+ }
153
+ /**
154
+ * Checks past swaps, refunds and deletes ones that are already expired.
155
+ */
156
+ async processPastSwaps() {
157
+ const settleInvoices = [];
158
+ const cancelInvoices = [];
159
+ const refundSwaps = [];
160
+ const queriedData = await this.storageManager.query([
161
+ {
162
+ key: "state",
163
+ value: [
164
+ FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED,
165
+ FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED,
166
+ FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED,
167
+ FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED,
168
+ FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED,
169
+ ]
170
+ }
171
+ ]);
172
+ for (let { obj: swap } of queriedData) {
173
+ switch (await this.processPastSwap(swap)) {
174
+ case "CANCEL":
175
+ cancelInvoices.push(swap);
176
+ break;
177
+ case "SETTLE":
178
+ settleInvoices.push(swap);
179
+ break;
180
+ case "REFUND":
181
+ refundSwaps.push(swap);
182
+ break;
183
+ }
184
+ }
185
+ await this.refundSwaps(refundSwaps);
186
+ await this.cancelInvoices(cancelInvoices);
187
+ await this.settleInvoices(settleInvoices);
188
+ }
189
+ async processInitializeEvent(chainIdentifier, savedSwap, event) {
190
+ this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: " + savedSwap.pr);
191
+ if (savedSwap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
192
+ await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED);
193
+ await this.saveSwapData(savedSwap);
194
+ }
195
+ }
196
+ async processClaimEvent(chainIdentifier, savedSwap, event) {
197
+ //Claim
198
+ //This is the important part, we need to catch the claim TX, else we may lose money
199
+ const secret = Buffer.from(event.result, "hex");
200
+ const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
201
+ const secretHex = secret.toString("hex");
202
+ const paymentHashHex = paymentHash.toString("hex");
203
+ if (savedSwap.lnPaymentHash !== paymentHashHex)
204
+ return;
205
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: " + savedSwap.pr);
206
+ try {
207
+ await this.lightning.settleHodlInvoice(secretHex);
208
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: " + secretHex);
209
+ savedSwap.secret = secretHex;
210
+ if (savedSwap.metadata != null)
211
+ savedSwap.metadata.times.htlcSettled = Date.now();
212
+ await this.removeSwapData(savedSwap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.SETTLED);
213
+ }
214
+ catch (e) {
215
+ this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
216
+ savedSwap.secret = secretHex;
217
+ await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED);
218
+ await this.saveSwapData(savedSwap);
219
+ }
220
+ }
221
+ async processRefundEvent(chainIdentifier, savedSwap, event) {
222
+ this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: " + savedSwap.pr);
223
+ try {
224
+ await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
225
+ this.swapLogger.info(savedSwap, "SC: RefundEvent: invoice cancelled");
226
+ await this.removeSwapData(savedSwap, FromBtcLnSwapAbs_1.FromBtcLnSwapState.REFUNDED);
227
+ }
228
+ catch (e) {
229
+ this.swapLogger.error(savedSwap, "SC: RefundEvent: cannot cancel invoice", e);
230
+ await savedSwap.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
231
+ // await PluginManager.swapStateChange(savedSwap);
232
+ await this.saveSwapData(savedSwap);
233
+ }
234
+ }
235
+ /**
236
+ * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
237
+ * smart chain authorization starts ticking as soon as this HTLC is received
238
+ *
239
+ * @param invoiceData
240
+ * @param invoice
241
+ */
242
+ async htlcReceived(invoiceData, invoice) {
243
+ this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
244
+ if (invoiceData.metadata != null)
245
+ invoiceData.metadata.times.htlcReceived = Date.now();
246
+ const useToken = invoiceData.token;
247
+ const escrowAmount = invoiceData.totalTokens;
248
+ try {
249
+ this.checkTooManyInflightSwaps();
250
+ }
251
+ catch (e) {
252
+ if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
253
+ invoiceData.metadata.htlcReceiveError = e;
254
+ if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
255
+ await this.cancelSwapAndInvoice(invoiceData);
256
+ throw e;
257
+ }
258
+ //Create abort controller for parallel fetches
259
+ const abortController = new AbortController();
260
+ //Pre-fetch data
261
+ const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
262
+ const blockheightPrefetch = this.getBlockheightPrefetch(abortController);
263
+ const signDataPrefetchPromise = this.getSignDataPrefetch(invoiceData.chainIdentifier, abortController);
264
+ let expiryTimeout;
265
+ try {
266
+ //Check if we have enough liquidity to proceed
267
+ await this.checkBalance(escrowAmount, balancePrefetch, abortController.signal);
268
+ if (invoiceData.metadata != null)
269
+ invoiceData.metadata.times.htlcBalanceChecked = Date.now();
270
+ //Check if HTLC expiry is long enough
271
+ expiryTimeout = await this.checkHtlcExpiry(invoice, blockheightPrefetch, abortController.signal);
272
+ if (invoiceData.metadata != null)
273
+ invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
274
+ }
275
+ catch (e) {
276
+ if (!abortController.signal.aborted) {
277
+ if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
278
+ invoiceData.metadata.htlcReceiveError = e;
279
+ if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
280
+ await this.cancelSwapAndInvoice(invoiceData);
281
+ }
282
+ throw e;
283
+ }
284
+ const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
285
+ //Create real swap data
286
+ const payInvoiceObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), invoiceData.claimer, useToken, escrowAmount, invoiceData.claimHash, 0n, BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout, false, true, invoiceData.securityDeposit, 0n, invoiceData.depositToken);
287
+ abortController.signal.throwIfAborted();
288
+ if (invoiceData.metadata != null)
289
+ invoiceData.metadata.times.htlcSwapCreated = Date.now();
290
+ //Sign swap data
291
+ const sigData = await swapContract.getInitSignature(signer, payInvoiceObject, this.getInitAuthorizationTimeout(invoiceData.chainIdentifier), signDataPrefetchPromise == null ? null : await signDataPrefetchPromise, invoiceData.feeRate);
292
+ //No need to check abortController anymore since all pending promises are resolved by now
293
+ if (invoiceData.metadata != null)
294
+ invoiceData.metadata.times.htlcSwapSigned = Date.now();
295
+ const pluginCheckResult = await PluginManager_1.PluginManager.onHandlePreFromBtcExecute(SwapHandler_1.SwapHandlerType.FROM_BTCLN, invoiceData);
296
+ if ((0, IPlugin_1.isQuoteThrow)(pluginCheckResult)) {
297
+ const error = {
298
+ code: 29999,
299
+ msg: pluginCheckResult.message
300
+ };
301
+ if (invoiceData.metadata != null)
302
+ invoiceData.metadata.htlcReceiveError = error;
303
+ if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
304
+ await this.cancelSwapAndInvoice(invoiceData);
305
+ throw error;
306
+ }
307
+ //Important to prevent race condition and issuing 2 signed init messages at the same time
308
+ if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
309
+ //Re-check right before signing
310
+ try {
311
+ this.checkTooManyInflightSwaps();
312
+ }
313
+ catch (e) {
314
+ if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
315
+ invoiceData.metadata.htlcReceiveError = e;
316
+ if (invoiceData.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
317
+ await this.cancelSwapAndInvoice(invoiceData);
318
+ throw e;
319
+ }
320
+ invoiceData.data = payInvoiceObject;
321
+ invoiceData.prefix = sigData.prefix;
322
+ invoiceData.timeout = sigData.timeout;
323
+ invoiceData.signature = sigData.signature;
324
+ //Setting the state variable is done outside the promise, so is done synchronously
325
+ await invoiceData.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED);
326
+ await this.saveSwapData(invoiceData);
327
+ return;
328
+ }
329
+ }
330
+ /**
331
+ * Checks invoice description
332
+ *
333
+ * @param description
334
+ * @throws {DefinedRuntimeError} will throw an error if the description is invalid
335
+ */
336
+ checkDescription(description) {
337
+ if (description != null && Buffer.byteLength(description, "utf8") > 500) {
338
+ throw {
339
+ code: 20100,
340
+ msg: "Invalid request body (description)"
341
+ };
342
+ }
343
+ }
344
+ /**
345
+ * Checks invoice description hash
346
+ *
347
+ * @param descriptionHash
348
+ * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
349
+ */
350
+ checkDescriptionHash(descriptionHash) {
351
+ if (descriptionHash != null) {
352
+ if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
353
+ throw {
354
+ code: 20100,
355
+ msg: "Invalid request body (descriptionHash)"
356
+ };
357
+ }
358
+ }
359
+ }
360
+ /**
361
+ * Starts LN channels pre-fetch
362
+ *
363
+ * @param abortController
364
+ */
365
+ getBlockheightPrefetch(abortController) {
366
+ return this.lightning.getBlockheight().catch(e => {
367
+ this.logger.error("getBlockheightPrefetch(): error", e);
368
+ abortController.abort(e);
369
+ return null;
370
+ });
371
+ }
372
+ /**
373
+ * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
374
+ *
375
+ * @param responseStream
376
+ */
377
+ sendPublicKeyAsync(responseStream) {
378
+ this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
379
+ lnPublicKey: publicKey
380
+ })).catch(e => {
381
+ this.logger.error("sendPublicKeyAsync(): error", e);
382
+ });
383
+ }
384
+ /**
385
+ * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
386
+ * received (MPP) it returns the lowest of the timeouts
387
+ *
388
+ * @param invoice
389
+ */
390
+ getInvoicePaymentsTimeout(invoice) {
391
+ let timeout = null;
392
+ invoice.payments.forEach((curr) => {
393
+ if (timeout == null || timeout > curr.timeout)
394
+ timeout = curr.timeout;
395
+ });
396
+ return timeout;
397
+ }
398
+ /**
399
+ * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
400
+ *
401
+ * @param invoice
402
+ * @param blockheightPrefetch
403
+ * @param signal
404
+ * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
405
+ * @returns expiry timeout in seconds
406
+ */
407
+ async checkHtlcExpiry(invoice, blockheightPrefetch, signal) {
408
+ const timeout = this.getInvoicePaymentsTimeout(invoice);
409
+ const current_block_height = await blockheightPrefetch;
410
+ signal.throwIfAborted();
411
+ const blockDelta = BigInt(timeout - current_block_height);
412
+ const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
413
+ if (htlcExpiresTooSoon) {
414
+ throw {
415
+ code: 20002,
416
+ msg: "Not enough time to reliably process the swap",
417
+ data: {
418
+ requiredDelta: this.config.minCltv.toString(10),
419
+ actualDelta: blockDelta.toString(10)
420
+ }
421
+ };
422
+ }
423
+ return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
424
+ }
425
+ /**
426
+ * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
427
+ *
428
+ * @param invoiceData
429
+ */
430
+ async cancelSwapAndInvoice(invoiceData) {
431
+ if (invoiceData.state !== FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED)
432
+ return;
433
+ await invoiceData.setState(FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED);
434
+ await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
435
+ await this.removeSwapData(invoiceData);
436
+ this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
437
+ }
438
+ ;
439
+ getDummySwapData(chainIdentifier, useToken, address, paymentHash) {
440
+ const { swapContract, signer } = this.getChain(chainIdentifier);
441
+ const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
442
+ return swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), address, useToken, dummyAmount, swapContract.getHashForHtlc(Buffer.from(paymentHash, "hex")).toString("hex"), base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8)), BigInt(Math.floor(Date.now() / 1000)), false, true, BigInt(Math.floor(Math.random() * 0x10000)), 0n);
443
+ }
444
+ /**
445
+ *
446
+ * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
447
+ *
448
+ * @param paymentHash
449
+ * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
450
+ * @returns the fetched lightning invoice
451
+ */
452
+ async checkInvoiceStatus(paymentHash) {
453
+ const invoice = await this.lightning.getInvoice(paymentHash);
454
+ if (invoice == null)
455
+ throw {
456
+ _httpStatus: 200,
457
+ code: 10001,
458
+ msg: "Invoice expired/canceled"
459
+ };
460
+ switch (invoice.status) {
461
+ case "canceled":
462
+ throw {
463
+ _httpStatus: 200,
464
+ code: 10001,
465
+ msg: "Invoice expired/canceled"
466
+ };
467
+ case "confirmed":
468
+ throw {
469
+ _httpStatus: 200,
470
+ code: 10002,
471
+ msg: "Invoice already paid"
472
+ };
473
+ case "unpaid":
474
+ throw {
475
+ _httpStatus: 200,
476
+ code: 10003,
477
+ msg: "Invoice yet unpaid"
478
+ };
479
+ default:
480
+ return invoice;
481
+ }
482
+ }
483
+ startRestServer(restServer) {
484
+ restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
485
+ restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
486
+ const metadata = { request: {}, times: {} };
487
+ const chainIdentifier = req.query.chain;
488
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
489
+ const depositToken = req.query.depositToken ?? chainInterface.getNativeCurrencyAddress();
490
+ this.checkAllowedDepositToken(chainIdentifier, depositToken);
491
+ metadata.times.requestReceived = Date.now();
492
+ /**
493
+ * address: string solana address of the recipient
494
+ * paymentHash: string payment hash of the to-be-created invoice
495
+ * amount: string amount (in sats) of the invoice
496
+ * token: string Desired token to swap
497
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
498
+ * description: string Description of the invoice (max 500 bytes)
499
+ * descriptionHash: string Description hash of the invoice
500
+ *
501
+ *Sent later:
502
+ * feeRate: string Fee rate to use for the init signature
503
+ */
504
+ const parsedBody = await req.paramReader.getParams({
505
+ address: (val) => val != null &&
506
+ typeof (val) === "string" &&
507
+ chainInterface.isValidAddress(val, true) ? val : null,
508
+ paymentHash: (val) => val != null &&
509
+ typeof (val) === "string" &&
510
+ val.length === 64 &&
511
+ Utils_1.HEX_REGEX.test(val) ? val : null,
512
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
513
+ token: (val) => val != null &&
514
+ typeof (val) === "string" &&
515
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
516
+ descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
517
+ exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
518
+ });
519
+ if (parsedBody == null)
520
+ throw {
521
+ code: 20100,
522
+ msg: "Invalid request body"
523
+ };
524
+ metadata.request = parsedBody;
525
+ const descriptionBodyPart = req.paramReader.getExistingParamsOrNull({
526
+ description: SchemaVerifier_1.FieldTypeEnum.StringOptional
527
+ });
528
+ const description = descriptionBodyPart?.description;
529
+ const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
530
+ const request = {
531
+ chainIdentifier,
532
+ raw: req,
533
+ parsed: parsedBody,
534
+ metadata
535
+ };
536
+ const useToken = parsedBody.token;
537
+ //Check request params
538
+ this.checkTooManyInflightSwaps();
539
+ this.checkDescription(description);
540
+ this.checkDescriptionHash(parsedBody.descriptionHash);
541
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount);
542
+ metadata.times.requestChecked = Date.now();
543
+ //Create abortController for parallel prefetches
544
+ const responseStream = res.responseStream;
545
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
546
+ //Pre-fetch data
547
+ const { pricePrefetchPromise, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, depositToken, abortController);
548
+ const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
549
+ const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
550
+ const nativeBalancePrefetch = this.prefetchNativeBalanceIfNeeded(chainIdentifier, abortController);
551
+ const dummySwapData = await this.getDummySwapData(chainIdentifier, useToken, parsedBody.address, parsedBody.paymentHash);
552
+ abortController.signal.throwIfAborted();
553
+ const baseSDPromise = this.getBaseSecurityDepositPrefetch(chainIdentifier, dummySwapData, depositToken, gasTokenPricePrefetchPromise, depositTokenPricePrefetchPromise, abortController);
554
+ //Asynchronously send the node's public key to the client
555
+ this.sendPublicKeyAsync(responseStream);
556
+ await this.checkNativeBalance(chainIdentifier, nativeBalancePrefetch, abortController.signal);
557
+ //Check valid amount specified (min/max)
558
+ const { amountBD, swapFee, swapFeeInToken, totalInToken, securityDepositApyPPM, securityDepositBaseMultiplierPPM } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal);
559
+ metadata.times.priceCalculated = Date.now();
560
+ if (securityDepositApyPPM != null)
561
+ fees.securityDepositApyPPM = securityDepositApyPPM;
562
+ if (securityDepositBaseMultiplierPPM != null)
563
+ fees.securityDepositBaseMultiplierPPM = securityDepositBaseMultiplierPPM;
564
+ //Check if we have enough funds to honor the request
565
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
566
+ await this.LightningAssertions.checkInboundLiquidity(amountBD, channelsPrefetch, abortController.signal);
567
+ metadata.times.balanceChecked = Date.now();
568
+ //Create swap
569
+ const hodlInvoiceObj = {
570
+ description: description ?? (chainIdentifier + "-" + parsedBody.address),
571
+ cltvDelta: Number(this.config.minCltv) + 5,
572
+ expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
573
+ id: parsedBody.paymentHash,
574
+ mtokens: amountBD * 1000n,
575
+ descriptionHash: parsedBody.descriptionHash
576
+ };
577
+ metadata.invoiceRequest = hodlInvoiceObj;
578
+ const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
579
+ abortController.signal.throwIfAborted();
580
+ metadata.times.invoiceCreated = Date.now();
581
+ metadata.invoiceResponse = { ...hodlInvoice };
582
+ //Pre-compute the security deposit
583
+ const expiryTimeout = (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
584
+ const totalSecurityDeposit = await this.getSecurityDeposit(chainIdentifier, amountBD, swapFee, expiryTimeout, baseSDPromise, depositToken, depositTokenPricePrefetchPromise, fees, abortController.signal, metadata);
585
+ metadata.times.securityDepositCalculated = Date.now();
586
+ const createdSwap = new FromBtcLnSwapAbs_1.FromBtcLnSwapAbs(chainIdentifier, hodlInvoice.request, parsedBody.paymentHash, hodlInvoice.mtokens, swapFee, swapFeeInToken, parsedBody.address, useToken, totalInToken, swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"), totalSecurityDeposit, depositToken);
587
+ metadata.times.swapCreated = Date.now();
588
+ createdSwap.metadata = metadata;
589
+ //Save the desired fee rate for the signature
590
+ const feeRateObj = await req.paramReader.getParams({
591
+ feeRate: SchemaVerifier_1.FieldTypeEnum.String
592
+ }).catch(() => null);
593
+ abortController.signal.throwIfAborted();
594
+ createdSwap.feeRate = feeRateObj?.feeRate != null && typeof (feeRateObj.feeRate) === "string" ? feeRateObj.feeRate : null;
595
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
596
+ await this.saveSwapData(createdSwap);
597
+ this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + amountBD.toString(10));
598
+ await responseStream.writeParamsAndEnd({
599
+ code: 20000,
600
+ msg: "Success",
601
+ data: {
602
+ pr: hodlInvoice.request,
603
+ swapFee: swapFeeInToken.toString(10),
604
+ total: totalInToken.toString(10),
605
+ intermediaryKey: signer.getAddress(),
606
+ securityDeposit: totalSecurityDeposit.toString(10)
607
+ }
608
+ });
609
+ }));
610
+ const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
611
+ /**
612
+ * paymentHash: string payment hash of the invoice
613
+ */
614
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
615
+ paymentHash: (val) => val != null &&
616
+ typeof (val) === "string" &&
617
+ val.length === 64 &&
618
+ Utils_1.HEX_REGEX.test(val) ? val : null,
619
+ });
620
+ await this.checkInvoiceStatus(parsedBody.paymentHash);
621
+ res.status(200).json({
622
+ code: 10000,
623
+ msg: "Success"
624
+ });
625
+ });
626
+ restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
627
+ restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
628
+ const getInvoicePaymentAuth = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
629
+ /**
630
+ * paymentHash: string payment hash of the invoice
631
+ */
632
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
633
+ paymentHash: (val) => val != null &&
634
+ typeof (val) === "string" &&
635
+ val.length === 64 &&
636
+ Utils_1.HEX_REGEX.test(val) ? val : null,
637
+ });
638
+ const invoice = await this.checkInvoiceStatus(parsedBody.paymentHash);
639
+ const swap = await this.storageManager.getData(parsedBody.paymentHash, null);
640
+ if (swap == null)
641
+ throw {
642
+ _httpStatus: 200,
643
+ code: 10001,
644
+ msg: "Invoice expired/canceled"
645
+ };
646
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
647
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED) {
648
+ if (await swapContract.isInitAuthorizationExpired(swap.data, swap))
649
+ throw {
650
+ _httpStatus: 200,
651
+ code: 10001,
652
+ msg: "Invoice expired/canceled"
653
+ };
654
+ }
655
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CREATED) {
656
+ try {
657
+ await this.htlcReceived(swap, invoice);
658
+ }
659
+ catch (e) {
660
+ if ((0, Utils_1.isDefinedRuntimeError)(e))
661
+ e._httpStatus = 200;
662
+ throw e;
663
+ }
664
+ this.swapLogger.info(swap, "REST: /getInvoicePaymentAuth: swap processed through htlcReceived, invoice: " + swap.pr);
665
+ }
666
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CANCELED)
667
+ throw {
668
+ _httpStatus: 200,
669
+ code: 10001,
670
+ msg: "Invoice expired/canceled"
671
+ };
672
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.COMMITED)
673
+ throw {
674
+ _httpStatus: 200,
675
+ code: 10004,
676
+ msg: "Invoice already committed"
677
+ };
678
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.CLAIMED)
679
+ throw {
680
+ _httpStatus: 200,
681
+ code: 10005,
682
+ msg: "Invoice already committed & claimed"
683
+ };
684
+ if (swap.state === FromBtcLnSwapAbs_1.FromBtcLnSwapState.RECEIVED)
685
+ res.status(200).json({
686
+ code: 10000,
687
+ msg: "Success",
688
+ data: {
689
+ address: signer.getAddress(),
690
+ data: swap.data.serialize(),
691
+ prefix: swap.prefix,
692
+ timeout: swap.timeout,
693
+ signature: swap.signature
694
+ }
695
+ });
696
+ });
697
+ restServer.post(this.path + "/getInvoicePaymentAuth", getInvoicePaymentAuth);
698
+ restServer.get(this.path + "/getInvoicePaymentAuth", getInvoicePaymentAuth);
699
+ this.logger.info("started at path: ", this.path);
700
+ }
701
+ async init() {
702
+ await this.loadData(FromBtcLnSwapAbs_1.FromBtcLnSwapAbs);
703
+ //Check if all swaps contain a valid amount
704
+ for (let { obj: swap } of await this.storageManager.query([])) {
705
+ if (swap.amount == null) {
706
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
707
+ swap.amount = (parsedPR.mtokens + 999n) / 1000n;
708
+ }
709
+ }
710
+ this.subscribeToEvents();
711
+ await PluginManager_1.PluginManager.serviceInitialize(this);
712
+ }
713
+ getInfoData() {
714
+ return {
715
+ minCltv: Number(this.config.minCltv)
716
+ };
717
+ }
718
+ }
719
+ exports.FromBtcLnAbs = FromBtcLnAbs;