@atomiqlabs/lp-lib 16.1.2 → 16.2.1

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