@atomiqlabs/lp-lib 13.0.0-beta.8 → 13.0.0

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