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