forked from PayButton/paybutton-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchronikService.ts
More file actions
1291 lines (1130 loc) · 50.5 KB
/
chronikService.ts
File metadata and controls
1291 lines (1130 loc) · 50.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { BlockInfo, ChronikClient, ConnectionStrategy, ScriptUtxo, Tx, WsConfig, WsEndpoint, WsMsgClient, WsSubScriptClient } from 'chronik-client'
import { encodeCashAddress, decodeCashAddress } from 'ecashaddrjs'
import { AddressWithTransaction, BlockchainInfo, TransactionDetails, ProcessedMessages, SubbedAddressesLog, SyncAndSubscriptionReturn, SubscriptionReturn, SimpleBlockInfo } from 'types/chronikTypes'
import { CHRONIK_MESSAGE_CACHE_DELAY, RESPONSE_MESSAGES, XEC_TIMESTAMP_THRESHOLD, XEC_NETWORK_ID, BCH_NETWORK_ID, BCH_TIMESTAMP_THRESHOLD, CHRONIK_FETCH_N_TXS_PER_PAGE, KeyValueT, NETWORK_IDS_FROM_SLUGS, SOCKET_MESSAGES, NETWORK_IDS, NETWORK_TICKERS, MainNetworkSlugsType, MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME, MEMPOOL_PROCESS_DELAY, CHRONIK_INITIALIZATION_DELAY, LATENCY_TEST_CHECK_DELAY, INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, TX_EMIT_BATCH_SIZE, DB_COMMIT_BATCH_SIZE, MAX_TXS_PER_ADDRESS, TX_BATCH_POLLING_DELAY } from 'constants/index'
import { productionAddresses } from 'prisma-local/seeds/addresses'
import prisma from 'prisma-local/clientInstance'
import {
TransactionWithAddressAndPrices,
createManyTransactions,
deleteTransactions,
fetchUnconfirmedTransactions,
markTransactionsOrphaned,
upsertTransaction,
getSimplifiedTransactions,
getSimplifiedTrasaction
} from './transactionService'
import {
updateClientPaymentStatus,
getClientPayment
} from './clientPaymentService'
import { Address, Prisma, ClientPaymentStatus } from '@prisma/client'
import xecaddr from 'xecaddrjs'
import { getAddressPrefix, satoshisToUnit } from 'utils/index'
import { fetchAddressesArray, fetchAllAddressesForNetworkId, getEarliestUnconfirmedTxTimestampForAddress, getLatestConfirmedTxTimestampForAddress, setSyncing, setSyncingBatch, updateLastSynced } from './addressService'
import * as ws from 'ws'
import { BroadcastTxData } from 'ws-service/types'
import config from 'config'
import io, { Socket } from 'socket.io-client'
import moment from 'moment'
import { OpReturnData, parseError, parseOpReturnData } from 'utils/validators'
import { executeAddressTriggers, executeTriggersBatch } from './triggerService'
import { appendTxsToFile } from 'prisma-local/seeds/transactions'
import { PHASE_PRODUCTION_BUILD } from 'next/dist/shared/lib/constants'
import { AddressType } from 'ecashaddrjs/dist/types'
import { DecimalJsLike } from '@prisma/client/runtime/library'
const decoder = new TextDecoder()
export function getNullDataScriptData (outputScript: string): OpReturnData | null {
if (outputScript.length < 2 || outputScript.length % 2 !== 0) {
throw new Error(RESPONSE_MESSAGES.INVALID_OUTPUT_SCRIPT_LENGTH_500(outputScript.length).message)
}
const opReturnCode = '6a'
const encodedProtocolPushData = '04' // '\x04'
const encodedProtocol = '50415900' // 'PAY\x00'
const prefixLen = (
opReturnCode.length +
encodedProtocolPushData.length +
encodedProtocol.length +
2 // version byte
)
const regexPattern = new RegExp(
`${opReturnCode}${encodedProtocolPushData}${encodedProtocol}.{2}`,
'i'
)
if (!regexPattern.test(outputScript.slice(0, prefixLen))) {
return null
}
let dataStartIndex = prefixLen + 2
if (outputScript.length < dataStartIndex) {
return null
}
let dataPushDataHex = outputScript.slice(prefixLen, dataStartIndex)
if (dataPushDataHex.toLowerCase() === '4c') {
dataStartIndex = dataStartIndex + 2
dataPushDataHex = outputScript.slice(prefixLen + 2, dataStartIndex)
}
const dataPushData = parseInt(dataPushDataHex, 16)
if (outputScript.length < dataStartIndex + dataPushData * 2) {
return null
}
const dataHexBuffer = Buffer.from(
outputScript.slice(dataStartIndex, dataStartIndex + dataPushData * 2),
'hex'
)
const dataString = decoder.decode(dataHexBuffer)
const ret: OpReturnData = {
rawMessage: dataString,
message: parseOpReturnData(dataString),
paymentId: ''
}
const paymentIdPushDataIndex = dataStartIndex + dataPushData * 2
const paymentIdStartIndex = paymentIdPushDataIndex + 2
const hasPaymentId = outputScript.length >= paymentIdStartIndex
if (!hasPaymentId) {
return ret
}
const paymentIdPushDataHex = outputScript.slice(paymentIdPushDataIndex, paymentIdStartIndex)
const paymentIdPushData = parseInt(paymentIdPushDataHex, 16)
let paymentIdString = ''
if (outputScript.length < paymentIdStartIndex + paymentIdPushData * 2) {
return ret
}
for (let i = 0; i < paymentIdPushData; i++) {
const hexByte = outputScript.slice(paymentIdStartIndex + (i * 2), paymentIdStartIndex + (i * 2) + 2)
// we don't decode the hex for the paymentId, since those are just random bytes.
paymentIdString += hexByte
}
ret.paymentId = paymentIdString
return ret
}
interface ChronikTxWithAddress { tx: Tx, address: Address }
interface FetchedTxsBatch {
chronikTxs: ChronikTxWithAddress[]
addressesSynced: string[]
}
export class ChronikBlockchainClient {
chronik!: ChronikClient
networkId!: number
networkSlug!: string
chronikWSEndpoint!: WsEndpoint
confirmedTxsHashesFromLastBlock!: string[]
wsEndpoint!: Socket
CHRONIK_MSG_PREFIX!: string
lastProcessedMessages!: ProcessedMessages
initializing!: boolean
mempoolTxsBeingProcessed!: number
private latencyTestFinished: boolean
constructor (networkSlug: string) {
this.latencyTestFinished = false
void (async () => {
if (process.env.WS_AUTH_KEY === '' || process.env.WS_AUTH_KEY === undefined) {
throw new Error(RESPONSE_MESSAGES.MISSING_WS_AUTH_KEY_400.message)
}
this.initializing = true
this.mempoolTxsBeingProcessed = 0
this.networkSlug = networkSlug
this.networkId = NETWORK_IDS_FROM_SLUGS[networkSlug]
this.chronik = await ChronikClient.useStrategy(
ConnectionStrategy.ClosestFirst,
config.networkBlockchainURLs[networkSlug]
)
this.latencyTestFinished = true
this.chronikWSEndpoint = this.chronik.ws(this.getWsConfig())
this.confirmedTxsHashesFromLastBlock = []
void this.chronikWSEndpoint.waitForOpen()
this.chronikWSEndpoint.subscribeToBlocks()
this.lastProcessedMessages = { confirmed: {}, unconfirmed: {} }
this.CHRONIK_MSG_PREFIX = `[CHRONIK — ${networkSlug}]`
this.wsEndpoint = io(`${config.wsBaseURL}/broadcast`, {
query: {
key: process.env.WS_AUTH_KEY
}
})
})()
}
private getLastSyncTs (addr: Address): number {
return (addr.lastSynced != null) ? Math.floor(new Date(addr.lastSynced).getTime() / 1000) : 0
}
public async waitForLatencyTest (): Promise<void> {
while (true) {
if (this.latencyTestFinished) {
return
}
await new Promise(resolve => setTimeout(resolve, LATENCY_TEST_CHECK_DELAY))
}
}
public getUrls (): string[] {
return this.chronik.proxyInterface().getEndpointArray().map(e => e.url)
}
public setInitialized (): void {
this.initializing = false
}
private clearOldMessages (): void {
const now = moment().unix()
for (const key of Object.keys(this.lastProcessedMessages.unconfirmed)) {
const ageDiffMs = (now - Number(this.lastProcessedMessages.unconfirmed[key])) * 1000
if (ageDiffMs > CHRONIK_MESSAGE_CACHE_DELAY) {
const { [key]: _, ...rest } = this.lastProcessedMessages.unconfirmed
this.lastProcessedMessages.unconfirmed = rest
}
}
for (const key of Object.keys(this.lastProcessedMessages.confirmed)) {
const ageDiffMs = (now - Number(this.lastProcessedMessages.confirmed[key])) * 1000
if (ageDiffMs > CHRONIK_MESSAGE_CACHE_DELAY) {
const { [key]: _, ...rest } = this.lastProcessedMessages.confirmed
this.lastProcessedMessages.confirmed = rest
}
}
}
public getSubscribedAddresses (): string[] {
const ret = this.chronikWSEndpoint.subs.scripts.map((script: WsSubScriptClient) => fromHash160(this.networkSlug, script.scriptType as AddressType, script.payload))
return [...new Set(ret)]
}
private isAlreadyBeingProcessed (txid: string, confirmed: boolean): boolean {
this.clearOldMessages()
if (confirmed) {
const lt = this.lastProcessedMessages.confirmed[txid]
if (lt === undefined) {
this.lastProcessedMessages.confirmed[txid] = moment().unix()
return false
}
return true
} else {
const lt = this.lastProcessedMessages.unconfirmed[txid]
if (lt === undefined) {
this.lastProcessedMessages.unconfirmed[txid] = moment().unix()
return false
}
return true
}
}
private validateNetwork (networkSlug: string): void {
if (NETWORK_IDS_FROM_SLUGS[networkSlug] !== this.networkId) { throw new Error(RESPONSE_MESSAGES.INVALID_NETWORK_SLUG_400.message) }
}
async getBlockchainInfo (networkSlug: string): Promise<BlockchainInfo> {
this.validateNetwork(networkSlug)
const blockchainInfo = await this.chronik.blockchainInfo()
return { height: blockchainInfo.tipHeight, hash: blockchainInfo.tipHash }
}
async getBlockInfo (networkSlug: string, height: number): Promise<SimpleBlockInfo> {
this.validateNetwork(networkSlug)
const blockInfo: BlockInfo = (await this.chronik.block(height)).blockInfo
return { hash: blockInfo.hash, height: blockInfo.height, timestamp: blockInfo.timestamp }
}
private txThesholdFilter (address: Address) {
return (t: Tx, _index: number, _array: Tx[]): boolean => {
return (
t.block === undefined ||
(t.block?.timestamp >= XEC_TIMESTAMP_THRESHOLD && address.networkId === XEC_NETWORK_ID) ||
(t.block?.timestamp >= BCH_TIMESTAMP_THRESHOLD && address.networkId === BCH_NETWORK_ID)
)
}
}
private getTransactionAmountAndData (transaction: Tx, addressString: string): {amount: Prisma.Decimal, opReturn: string} {
let totalOutput = 0n
let totalInput = 0n
const addressFormat = xecaddr.detectAddressFormat(addressString)
const script = toHash160(addressString).hash160
let opReturn = ''
for (const output of transaction.outputs) {
if (output.outputScript.includes(script)) {
totalOutput += output.sats
}
if (opReturn === '') {
const nullScriptData = getNullDataScriptData(output.outputScript)
if (nullScriptData !== null) {
opReturn = JSON.stringify(
nullScriptData
)
}
}
}
for (const input of transaction.inputs) {
if (input?.outputScript?.includes(script) === true) {
totalInput += input.sats
}
}
const satoshis = totalOutput - totalInput
const amount = satoshisToUnit(satoshis, addressFormat)
return {
amount,
opReturn
}
}
private getTransactionFromChronikTransaction (transaction: Tx, address: Address): Prisma.TransactionUncheckedCreateInput {
const { amount, opReturn } = this.getTransactionAmountAndData(transaction, address.address)
const inputAddresses = this.getSortedInputAddresses(transaction)
return {
hash: transaction.txid,
amount,
timestamp: transaction.block !== undefined ? transaction.block.timestamp : transaction.timeFirstSeen,
addressId: address.id,
confirmed: transaction.block !== undefined,
isPayment: amount > 0,
opReturn,
inputs: {
create: inputAddresses
}
}
}
public async getPaginatedTxs (addressString: string, page: number, pageSize: number): Promise<Tx[]> {
const { type, hash160 } = toHash160(addressString)
const txsPage = (await this.chronik.script(type, hash160).history(page, pageSize))
// If there are too many txs, this might be too expensive to sync. Raise an
// error to skip this address.
if (txsPage.numTxs > MAX_TXS_PER_ADDRESS) {
throw new Error(`Address ${addressString} has too many txs to sync (${txsPage.numTxs} > ${MAX_TXS_PER_ADDRESS}).`)
}
return txsPage.txs
}
/*
* For each address, fetch pages in parallel (“burst”),
* then use the burst’s newest/oldest timestamps to decide whether to continue.
* Yields happen only in the generator body (after each slice finishes, and at final flush).
*/
private async * fetchLatestTxsForAddresses (
addresses: Address[]
): AsyncGenerator<FetchedTxsBatch> {
const logPrefix = `${this.CHRONIK_MSG_PREFIX}[PARALLEL FETCHING]`
const totalCount = addresses.length
console.log(
`${logPrefix} >>> Will fetch latest txs for ${totalCount} addresses ` +
`(addressConcurrency=${INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY}, pageConcurrency=1).`
)
let chronikTxs: ChronikTxWithAddress[] = []
const completedAddresses: string[] = []
// Worker pool: maintain exactly INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY active workers
const activeWorkers = new Set<Promise<void>>()
let nextAddressIndex = 0
// Function to process a single address
const processAddress = async (address: Address, addressIndex: number): Promise<void> => {
const addrLogPrefix = `${logPrefix} > ${address.address}: (${addressIndex + 1}/${totalCount})`
const lastSyncedTimestampSeconds = this.getLastSyncTs(address)
const txThresholdFilter = this.txThesholdFilter(address)
let nextBurstBasePageIndex = 0
let hasReachedStoppingCondition = false
let newTxs = 0
try {
while (!hasReachedStoppingCondition) {
const pageIndex = nextBurstBasePageIndex
let pageTxs: Tx[] = []
try {
pageTxs = await this.getPaginatedTxs(address.address, pageIndex, CHRONIK_FETCH_N_TXS_PER_PAGE)
} catch (err: any) {
console.warn(`${addrLogPrefix} page=${pageIndex} failed: ${err.message as string}`)
pageTxs = []
}
if (pageIndex === 0 && pageTxs.length === 0) {
console.log(`${addrLogPrefix} EMPTY ADDRESS`)
break
}
if (pageTxs.length < CHRONIK_FETCH_N_TXS_PER_PAGE) {
hasReachedStoppingCondition = true
}
const newestTs = Number(pageTxs[0].block?.timestamp ?? pageTxs[0].timeFirstSeen)
if (newestTs < lastSyncedTimestampSeconds) {
console.log(`${addrLogPrefix} NO NEW TXS`)
break
}
const oldestTs = Number(pageTxs[pageTxs.length - 1].block?.timestamp ?? pageTxs[pageTxs.length - 1].timeFirstSeen)
pageTxs = pageTxs
.filter(txThresholdFilter)
.filter(t => t.block === undefined || t.block.timestamp >= lastSyncedTimestampSeconds)
const newTxsInThisPage = pageTxs.length
if (newTxsInThisPage > 0) {
chronikTxs.push(...pageTxs.map(tx => ({ tx, address })))
pageTxs = []
}
if (oldestTs < lastSyncedTimestampSeconds) {
hasReachedStoppingCondition = true
}
nextBurstBasePageIndex += 1
if (newTxsInThisPage === 0 && oldestTs < lastSyncedTimestampSeconds) {
hasReachedStoppingCondition = true
}
newTxs += newTxsInThisPage
}
if (newTxs > 0) {
console.log(`${addrLogPrefix} ${newTxs} new txs.`)
}
} catch (err: any) {
console.error(`${logPrefix}: address job failed: ${err.message as string}`)
} finally {
completedAddresses.push(address.address)
}
}
// Start next worker from the queue
const startNextWorker = (): void => {
if (nextAddressIndex >= totalCount) {
// No more addresses
return
}
const currentIndex = nextAddressIndex
nextAddressIndex++
const workerPromise = processAddress(addresses[currentIndex], currentIndex).finally(() => {
activeWorkers.delete(workerPromise)
// Immediately start next worker if queue has more
startNextWorker()
})
activeWorkers.add(workerPromise)
}
// Start initial batch of workers
const initialBatchSize = Math.min(INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY, totalCount)
for (let i = 0; i < initialBatchSize; i++) {
startNextWorker()
}
// Poll and yield batches while workers are active
while (activeWorkers.size > 0 || chronikTxs.length > 0) {
// Yield batches if buffer is large enough. Make sure to drain until there
// are not enough transactions to fill the batch.
while (chronikTxs.length >= TX_EMIT_BATCH_SIZE) {
const chronikTxsSlice = chronikTxs.splice(0, TX_EMIT_BATCH_SIZE)
yield { chronikTxs: chronikTxsSlice, addressesSynced: [] }
}
// If no active workers, yield any remaining transactions (even if < batch size)
if (activeWorkers.size === 0 && chronikTxs.length > 0) {
const remaining = chronikTxs.splice(0)
yield { chronikTxs: remaining, addressesSynced: [] }
}
// Yield completed addresses if any
if (completedAddresses.length > 0) {
const completed = completedAddresses.splice(0)
yield { chronikTxs: [], addressesSynced: completed }
}
// If no active workers and no more transactions, break
if (activeWorkers.size === 0 && chronikTxs.length === 0) {
break
}
// Wait a bit for more transactions or worker completion
await Promise.race([
Promise.all(Array.from(activeWorkers)).then(() => true),
new Promise<boolean>(resolve => setTimeout(() => resolve(false), TX_BATCH_POLLING_DELAY))
])
}
// Wait for all workers to finish (should already be done)
if (activeWorkers.size > 0) {
await Promise.all(Array.from(activeWorkers))
}
// Final TX flush after all addresses processed
if (chronikTxs.length > 0) {
const remaining = chronikTxs
chronikTxs = []
yield { chronikTxs: remaining, addressesSynced: [] }
}
}
public async * syncTransactionsForAddress (address: Address, fully = false, runTriggers = false): AsyncGenerator<TransactionWithAddressAndPrices[]> {
const pageSize = CHRONIK_FETCH_N_TXS_PER_PAGE
let page = 0
const earliestUnconfirmedTxTimestamp = await getEarliestUnconfirmedTxTimestampForAddress(address.id)
const latestTimestamp = earliestUnconfirmedTxTimestamp ?? await getLatestConfirmedTxTimestampForAddress(address.id) ?? 0
let maxTimestamp = 0
while (true) {
let transactions = await this.getPaginatedTxs(address.address, page, pageSize)
// filter out transactions that happened before a certain date set in constants/index,
// this date is understood as the beginning and we don't look past it
transactions = transactions.filter(this.txThesholdFilter(address))
if (transactions.length === 0) {
break
}
const latestBlockTimestamp = Number(transactions[0].block?.timestamp)
if (!fully && latestBlockTimestamp < latestTimestamp) break
const confirmedTransactions = transactions.filter(t => t.block !== undefined)
const unconfirmedTransactions = transactions.filter(t => t.block === undefined)
page += 1
const transactionsToPersist = [...confirmedTransactions, ...unconfirmedTransactions].map(tx => this.getTransactionFromChronikTransaction(tx, address))
const persistedTransactions = await createManyTransactions(transactionsToPersist)
if (persistedTransactions.length > 0) {
// Track the max timestamp from persisted transactions
for (const tx of persistedTransactions) {
maxTimestamp = Math.max(maxTimestamp, tx.timestamp)
}
const simplifiedTransactions = getSimplifiedTransactions(persistedTransactions)
console.log(`${this.CHRONIK_MSG_PREFIX}: added ${simplifiedTransactions.length} txs to ${address.address}`)
const broadcastTxData: BroadcastTxData = {} as BroadcastTxData
broadcastTxData.messageType = 'OldTx'
broadcastTxData.address = address.address
broadcastTxData.txs = simplifiedTransactions
this.wsEndpoint.emit(SOCKET_MESSAGES.TXS_BROADCAST, broadcastTxData)
if (runTriggers) {
await executeAddressTriggers(broadcastTxData, this.networkId)
}
}
yield persistedTransactions
}
await setSyncing(address.address, false)
// Only update lastSynced if new value is greater than current (or if current is null)
const currentAddress = await prisma.address.findUnique({
where: { address: address.address },
select: { lastSynced: true }
})
const currentLastSynced = currentAddress?.lastSynced ?? null
const newDate = new Date(maxTimestamp * 1000)
if ((currentLastSynced == null) || currentLastSynced < newDate) {
await updateLastSynced(address.address, maxTimestamp)
}
}
private async getUtxos (address: string): Promise<ScriptUtxo[]> {
const { type, hash160 } = toHash160(address)
const scriptsUtxos = await this.chronik.script(type, hash160).utxos()
return scriptsUtxos.utxos
}
public async getBalance (address: string): Promise<bigint> {
const utxos = await this.getUtxos(address)
return utxos.reduce((acc, utxo) => acc + utxo.sats, 0n)
}
async getTransactionDetails (hash: string): Promise<TransactionDetails> {
const tx = await this.chronik.tx(hash)
const details: TransactionDetails = {
hash: tx.txid,
version: tx.version,
block: {
hash: tx.block?.hash,
height: tx.block?.height,
timestamp: tx.block?.timestamp.toString()
},
inputs: [],
outputs: []
}
for (const input of tx.inputs) {
details.inputs.push({
value: input.sats,
address: outputScriptToAddress(this.networkSlug, input.outputScript)
})
}
for (const output of tx.outputs) {
details.outputs.push({
value: output.sats,
address: outputScriptToAddress(this.networkSlug, output.outputScript)
})
}
return details
}
private getWsConfig (): WsConfig {
return {
onMessage: (msg: WsMsgClient) => { void this.processWsMessage(msg) },
onError: (e: ws.ErrorEvent) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket error, type: ${e.type} | message: ${e.message} | error: ${e.error as string}`) },
onReconnect: (_: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket unexpectedly closed.`) },
onConnect: (_: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik webSocket connection (re)established.`) },
onEnd: (e: ws.Event) => { console.log(`${this.CHRONIK_MSG_PREFIX}: Chronik WebSocket ended, type: ${e.type}.`) },
autoReconnect: true
}
}
private getSortedInputAddresses (transaction: Tx): Array<{address: string, index: number, amount: Prisma.Decimal}> {
const addressSatsMap = new Map<string, bigint>()
transaction.inputs.forEach((inp) => {
const address = outputScriptToAddress(this.networkSlug, inp.outputScript)
if (address !== undefined && address !== '') {
const currentValue = addressSatsMap.get(address) ?? 0n
addressSatsMap.set(address, currentValue + inp.sats)
}
})
const unitDivisor = this.networkId === XEC_NETWORK_ID
? 1e2
: (this.networkId === BCH_NETWORK_ID ? 1e8 : 1)
const result: Array<{address: string, index: number, amount: Prisma.Decimal}> = []
let index = 0
for (const [address, sats] of addressSatsMap.entries()) {
const decimal = new Prisma.Decimal(sats.toString())
const amount = decimal.dividedBy(unitDivisor)
result.push({ address, index, amount })
index++
}
return result
}
private getSortedOutputAddresses (transaction: Tx): Array<{address: string, index: number, amount: Prisma.Decimal}> {
const addressSatsMap = new Map<string, bigint>()
transaction.outputs.forEach((out) => {
const address = outputScriptToAddress(this.networkSlug, out.outputScript)
if (address !== undefined && address !== '') {
const currentValue = addressSatsMap.get(address) ?? 0n
addressSatsMap.set(address, currentValue + out.sats)
}
})
const unitDivisor = this.networkId === XEC_NETWORK_ID
? 1e2
: (this.networkId === BCH_NETWORK_ID ? 1e8 : 1)
const result: Array<{address: string, index: number, amount: Prisma.Decimal}> = []
let index = 0
for (const [address, sats] of addressSatsMap.entries()) {
const decimal = new Prisma.Decimal(sats.toString())
const amount = decimal.dividedBy(unitDivisor)
result.push({ address, index, amount })
index++
}
return result
}
public async waitForSyncing (txId: string, addressStringArray: string[]): Promise<void> {
if (!this.initializing) return
console.log(`${this.CHRONIK_MSG_PREFIX}: Waiting unblocking addresses for ${txId}`)
while (true) {
const addresses = await fetchAddressesArray(addressStringArray)
if (addresses.every(a => !a.syncing)) {
console.log(`${this.CHRONIK_MSG_PREFIX}: Finished unblocking addresses for ${txId}`)
return
}
await new Promise(resolve => setTimeout(resolve, CHRONIK_INITIALIZATION_DELAY))
}
}
private async handleUpdateClientPaymentStatus (
txAmount: string | number | Prisma.Decimal | DecimalJsLike,
opReturn: string | undefined, status: ClientPaymentStatus,
txAddress: string): Promise<void> {
const parsedOpReturn = parseOpReturnData(opReturn ?? '')
const paymentId = parsedOpReturn.paymentId
if (paymentId === undefined || paymentId === '') {
return
}
const clientPayment = await getClientPayment(paymentId)
if (clientPayment === null || clientPayment.status === 'CONFIRMED') {
return
}
if (clientPayment.amount !== null) {
if (Number(clientPayment.amount) === Number(txAmount) &&
(clientPayment.addressString === txAddress)) {
await updateClientPaymentStatus(paymentId, status)
}
} else {
if (clientPayment.addressString === txAddress) {
await updateClientPaymentStatus(paymentId, status)
}
}
}
private async fetchTxWithRetry (txid: string, tries = 3, delayMs = 1000): Promise<Tx> {
for (let i = 0; i < tries; i++) {
try {
return await this.chronik.tx(txid)
} catch (e: any) {
const msg = String(e?.message ?? e)
const is404 = /not found in the index|404/.test(msg)
if (!is404 || i === tries - 1) throw e
const delay = delayMs * Math.pow(2, i)
console.error(`Got a 404 Error trying to fetch tx ${txid} on the attempt number ${i + 1}, waiting ${(delay / 1000).toFixed(1)}s...`)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
throw new Error('unreachable')
}
private async processWsMessage (msg: WsMsgClient): Promise<void> {
if (msg.type === 'Tx') {
// delete unconfirmed transaction from our database
// if they were cancelled and not confirmed
if (msg.msgType === 'TX_REMOVED_FROM_MEMPOOL') {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] ${msg.txid}`)
const transactionsToDelete = await fetchUnconfirmedTransactions(msg.txid)
try {
await deleteTransactions(transactionsToDelete)
} catch (err: any) {
const parsedError = parseError(err)
if (parsedError.message !== RESPONSE_MESSAGES.NO_TRANSACTION_FOUND_404.message) {
throw err
}
}
} else if (msg.msgType === 'TX_CONFIRMED') {
try {
const transaction = await this.fetchTxWithRetry(msg.txid)
const addressesWithTransactions = await this.getAddressesForTransaction(transaction)
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] ${msg.txid}`)
this.confirmedTxsHashesFromLastBlock = [...this.confirmedTxsHashesFromLastBlock, msg.txid]
for (const addressWithTransaction of addressesWithTransactions) {
const { amount, opReturn } = addressWithTransaction.transaction
await this.handleUpdateClientPaymentStatus(amount, opReturn, 'CONFIRMED' as ClientPaymentStatus, addressWithTransaction.address.address)
}
} catch (e: any) {
const msg404 = String(e?.message ?? e)
const is404 = /not found in the index|404/.test(msg404)
if (is404) {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] tx ${msg.txid} not found in chronik, marking as orphaned`)
await markTransactionsOrphaned(msg.txid)
} else {
console.error(`${this.CHRONIK_MSG_PREFIX}: confirmed tx handler failed for ${msg.txid}`, e)
}
}
} else if (msg.msgType === 'TX_ADDED_TO_MEMPOOL') {
if (this.isAlreadyBeingProcessed(msg.txid, false)) return
while (this.mempoolTxsBeingProcessed >= MAX_MEMPOOL_TXS_TO_PROCESS_AT_A_TIME) {
await new Promise(resolve => setTimeout(resolve, MEMPOOL_PROCESS_DELAY))
}
this.mempoolTxsBeingProcessed += 1
try {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] ${msg.txid}`)
const transaction = await this.fetchTxWithRetry(msg.txid)
const addressesWithTransactions = await this.getAddressesForTransaction(transaction)
await this.waitForSyncing(msg.txid, addressesWithTransactions.map(obj => obj.address.address))
for (const addressWithTransaction of addressesWithTransactions) {
const { created, tx } = await upsertTransaction(addressWithTransaction.transaction)
if (tx !== undefined) {
const broadcastTxData = this.broadcastIncomingTx(addressWithTransaction.address.address, transaction, tx)
if (created) { // only execute trigger for newly added txs
await executeAddressTriggers(broadcastTxData, tx.address.networkId)
}
const { amount, opReturn } = addressWithTransaction.transaction
await this.handleUpdateClientPaymentStatus(amount, opReturn, 'ADDED_TO_MEMPOOL' as ClientPaymentStatus, addressWithTransaction.address.address)
}
}
} catch (e) {
console.error(`${this.CHRONIK_MSG_PREFIX}: mempool handler failed for ${msg.txid}`, e)
} finally {
this.mempoolTxsBeingProcessed = Math.max(0, this.mempoolTxsBeingProcessed - 1)
}
}
} else if (msg.type === 'Block') {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] Height: ${msg.blockHeight} Hash: ${msg.blockHash}`)
if (msg.msgType === 'BLK_FINALIZED') {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] Syncing ${this.confirmedTxsHashesFromLastBlock.length} txs on the block...`)
while (this.initializing) {
await new Promise(resolve => setTimeout(resolve, CHRONIK_INITIALIZATION_DELAY))
}
await this.syncBlockTransactions(msg.blockHash)
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.msgType}] Syncing done.`)
const subsCount = this.chronikWSEndpoint.subs.scripts.length
console.log(`${this.CHRONIK_MSG_PREFIX}: [INFO] *Currently Subscribed to ${subsCount} addresses*`)
this.confirmedTxsHashesFromLastBlock = []
}
} else if (msg.type === 'Error') {
console.log(`${this.CHRONIK_MSG_PREFIX}: [${msg.type}] ${JSON.stringify(msg.msg)}`)
}
}
private broadcastIncomingTx (addressString: string, chronikTx: Tx, createdTx: TransactionWithAddressAndPrices): BroadcastTxData {
const broadcastTxData: BroadcastTxData = {} as BroadcastTxData
broadcastTxData.address = addressString
broadcastTxData.messageType = 'NewTx'
const inputAddresses = this.getSortedInputAddresses(chronikTx)
const outputAddresses = this.getSortedOutputAddresses(chronikTx)
const newSimplifiedTransaction = getSimplifiedTrasaction(createdTx, inputAddresses, outputAddresses)
broadcastTxData.txs = [newSimplifiedTransaction]
try { // emit broadcast for both unconfirmed and confirmed txs
this.wsEndpoint.emit(SOCKET_MESSAGES.TXS_BROADCAST, broadcastTxData)
} catch (err: any) {
console.error(RESPONSE_MESSAGES.COULD_NOT_BROADCAST_TX_TO_WS_SERVER_500.message, err.stack)
}
return broadcastTxData
}
private async syncBlockTransactions (blockHash: string): Promise<void> {
let page = 0
const pageSize = 200
let blockPageTxs = (await this.chronik.blockTxs(blockHash, page, pageSize)).txs
let blockTxsToSync: Tx[] = []
while (blockPageTxs.length > 0 && blockTxsToSync.length !== this.confirmedTxsHashesFromLastBlock.length) {
const thisBlockTxsToSync = blockPageTxs.filter(tx => this.confirmedTxsHashesFromLastBlock.includes(tx.txid))
blockTxsToSync = [...blockTxsToSync, ...thisBlockTxsToSync]
page += 1
blockPageTxs = (await this.chronik.blockTxs(blockHash, page, pageSize)).txs
}
for (const transaction of blockTxsToSync) {
const addressesWithTransactions = await this.getAddressesForTransaction(transaction)
for (const addressWithTransaction of addressesWithTransactions) {
const { created, tx } = await upsertTransaction(addressWithTransaction.transaction)
if (tx !== undefined) {
const broadcastTxData = this.broadcastIncomingTx(addressWithTransaction.address.address, transaction, tx)
if (created) { // only execute trigger for newly added txs
await executeAddressTriggers(broadcastTxData, tx.address.networkId)
}
}
}
}
}
private getRelatedAddressesForTransaction (transaction: Tx): string[] {
const inputAddresses = transaction.inputs.map(inp => outputScriptToAddress(this.networkSlug, inp.outputScript))
const outputAddresses = transaction.outputs.map(out => outputScriptToAddress(this.networkSlug, out.outputScript))
return [...inputAddresses, ...outputAddresses].filter(a => a !== undefined)
}
private async getAddressesForTransaction (transaction: Tx): Promise<AddressWithTransaction[]> {
const relatedAddresses = this.getRelatedAddressesForTransaction(transaction)
const addressesFromStringArray = await fetchAddressesArray(relatedAddresses)
const addressesWithTransactions: AddressWithTransaction[] = addressesFromStringArray.map(
address => {
return {
address,
transaction: this.getTransactionFromChronikTransaction(transaction, address)
}
}
)
const zero = new Prisma.Decimal(0)
return addressesWithTransactions.filter(
addressWithTransaction => !(zero.equals(addressWithTransaction.transaction.amount as Prisma.Decimal))
)
}
public async subscribeAddresses (addresses: Address[]): Promise<SubscriptionReturn> {
const failedAddressesWithErrors: KeyValueT<string> = {}
const subscribedAddresses = this.getSubscribedAddresses()
addresses = addresses
.filter(addr => (
addr.networkId === this.networkId &&
!subscribedAddresses.includes(addr.address))
)
if (addresses.length === 0) return { failedAddressesWithErrors }
await Promise.all(
addresses.map(async (address) => {
try {
this.chronikWSEndpoint.subscribeToAddress(address.address)
} catch (err: any) {
failedAddressesWithErrors[address.address] = err.stack
}
})
)
return {
failedAddressesWithErrors
}
}
private async commitTransactionsBatch (
commitTuples: Array<{ row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string }>,
productionAddressesIds: string[],
runTriggers: boolean
): Promise<void> {
const rows = commitTuples.map(p => p.row)
const createdTxs = await createManyTransactions(rows)
console.log(`${this.CHRONIK_MSG_PREFIX} committed — created=${createdTxs.length}/${commitTuples.length}`)
const createdForProd = createdTxs.filter(t => productionAddressesIds.includes(t.addressId))
if (createdForProd.length > 0) {
await appendTxsToFile(createdForProd as unknown as Prisma.TransactionCreateManyInput[])
}
if (createdTxs.length > 0) {
const triggerBatch: BroadcastTxData[] = []
for (const createdTx of createdTxs) {
const tuple = commitTuples.find(t => t.row.hash === createdTx.hash)
if (tuple == null) {
continue
}
const bd = this.broadcastIncomingTx(createdTx.address.address, tuple.raw, createdTx)
triggerBatch.push(bd)
}
if (runTriggers && triggerBatch.length > 0) {
await executeTriggersBatch(triggerBatch, this.networkId)
}
// Release memory
createdTxs.length = 0
triggerBatch.length = 0
}
// Get the latest timestamp of all committed transactions (including pre-existent) for each address.
// This is redundant under normal circumstances, but is more robust than only updating for the newly created transactions.
const addressMaxTimestamp = new Map<string, number>()
for (const { row, addressString } of commitTuples) {
const currentMax = addressMaxTimestamp.get(addressString) ?? 0
addressMaxTimestamp.set(addressString, Math.max(currentMax, row.timestamp))
}
// Fetch current lastSynced values for all addresses
const addressesToUpdate = Array.from(addressMaxTimestamp.keys())
const currentAddresses = await prisma.address.findMany({
where: {
address: { in: addressesToUpdate }
},
select: {
address: true,
lastSynced: true
}
})
const currentLastSyncedMap = new Map<string, Date | null>(
currentAddresses.map((a: { address: string, lastSynced: Date | null }) => [a.address, a.lastSynced])
)
// Update lastSynced for the processed addresses (only if new value is greater)
for (const [addr, maxTs] of addressMaxTimestamp) {
const currentLastSynced = currentLastSyncedMap.get(addr)
const newDate = new Date(maxTs * 1000)
// Only update if new value is greater than current (or if current is null)
if ((currentLastSynced == null) || currentLastSynced < newDate) {
try {
await updateLastSynced(addr, maxTs)
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: Failed to update lastSynced for ${addr}: ${err.message as string}`)
}
}
}
}
public async syncAddresses (addresses: Address[], runTriggers = false): Promise<SyncAndSubscriptionReturn> {
const failedAddressesWithErrors: KeyValueT<string> = {}
const successfulAddressesWithCount: KeyValueT<number> = {}
const productionAddressesIds = productionAddresses.filter(a => a.networkId === this.networkId).map(a => a.id)
if (addresses.length === 0) {
return { failedAddressesWithErrors, successfulAddressesWithCount }
}
console.log(`${this.CHRONIK_MSG_PREFIX} Syncing ${addresses.length} addresses...`)
console.time(`${this.CHRONIK_MSG_PREFIX} syncAddresses`)
await setSyncingBatch(addresses.map(a => a.address), true)
const perAddrCount = new Map<string, number>()
addresses.forEach(a => perAddrCount.set(a.id, 0))
interface RowWithRaw { row: Prisma.TransactionUncheckedCreateInput, raw: Tx, addressString: string }
let toCommit: RowWithRaw[] = []
try {
const pfx = `${this.CHRONIK_MSG_PREFIX}[PARALLEL FETCHING]`
console.log(`${pfx} will fetch batches of ${INITIAL_ADDRESS_SYNC_FETCH_CONCURRENTLY} addresses from chronik`)
for await (const batch of this.fetchLatestTxsForAddresses(addresses)) {
if (batch.addressesSynced.length > 0) {
// marcador de slice => desmarca syncing
await setSyncingBatch(batch.addressesSynced, false)
continue
}
const involvedAddrIds = new Set(batch.chronikTxs.map(({ address }) => address.id))
try {
const tupleFromBatch: RowWithRaw[] = batch.chronikTxs.map(({ tx, address }) => {
const row = this.getTransactionFromChronikTransaction(tx, address)
return { row, raw: tx, addressString: address.address }
})
for (const { row } of tupleFromBatch) {
perAddrCount.set(row.addressId, (perAddrCount.get(row.addressId) ?? 0) + 1)
}
toCommit.push(...tupleFromBatch)
// Release memory
tupleFromBatch.length = 0
if (toCommit.length >= DB_COMMIT_BATCH_SIZE) {
const commitPairs = toCommit.splice(0, DB_COMMIT_BATCH_SIZE)
await this.commitTransactionsBatch(commitPairs, productionAddressesIds, runTriggers)
// Clear commitPairs
commitPairs.length = 0
}
} catch (err: any) {
console.error(`${this.CHRONIK_MSG_PREFIX}: ERROR in batch (scoped): ${err.message as string}`)
// Only mark addresses that were actually in this batch