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