-
Notifications
You must be signed in to change notification settings - Fork 4
/
TransactionQueue.ts
7651 lines (6912 loc) · 375 KB
/
TransactionQueue.ts
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 { P2P as P2PTypes, StateManager as StateManagerTypes } from '@shardus/types'
import StateManager from '.'
import Crypto from '../crypto'
import Logger, { logFlags } from '../logger'
import * as Apoptosis from '../p2p/Apoptosis'
import * as Archivers from '../p2p/Archivers'
import { P2PModuleContext as P2P, network as networkContext, config as configContext } from '../p2p/Context'
import * as CycleChain from '../p2p/CycleChain'
import { nodes, byPubKey, potentiallyRemoved } from '../p2p/NodeList'
import * as Shardus from '../shardus/shardus-types'
import Storage from '../storage'
import * as utils from '../utils'
import {Signature, SignedObject} from '@shardus/crypto-utils'
import {
errorToStringFull,
inRangeOfCurrentTime,
withTimeout,
XOR,
} from '../utils'
import { Utils } from '@shardus/types'
import * as Self from '../p2p/Self'
import * as Comms from '../p2p/Comms'
import { nestedCountersInstance } from '../utils/nestedCounters'
import Profiler, { cUninitializedSize, profilerInstance } from '../utils/profiler'
import ShardFunctions from './shardFunctions'
import * as NodeList from '../p2p/NodeList'
import {
AcceptedTx,
AccountFilter,
AppliedReceipt,
AppliedReceipt2,
CommitConsensedTransactionResult,
PreApplyAcceptedTransactionResult,
ProcessQueueStats,
QueueCountsResult,
QueueEntry,
RequestReceiptForTxResp,
RequestReceiptForTxResp_old,
RequestStateForTxReq,
RequestStateForTxResp,
SeenAccounts,
SimpleNumberStats,
StringBoolObjectMap,
StringNodeObjectMap,
TxDebug,
WrappedResponses,
ArchiverReceipt,
NonceQueueItem,
AppliedVote
} from './state-manager-types'
import { isInternalTxAllowed, networkMode } from '../p2p/Modes'
import { Node } from '@shardus/types/build/src/p2p/NodeListTypes'
import { Logger as L4jsLogger } from 'log4js'
import { ipInfo, shardusGetTime } from '../network'
import { InternalBinaryHandler } from '../types/Handler'
import {
BroadcastStateReq,
deserializeBroadcastStateReq,
serializeBroadcastStateReq,
} from '../types/BroadcastStateReq'
import {
getStreamWithTypeCheck,
requestErrorHandler,
verificationDataCombiner,
verificationDataSplitter,
} from '../types/Helpers'
import { RequestErrorEnum } from '../types/enum/RequestErrorEnum'
import { InternalRouteEnum } from '../types/enum/InternalRouteEnum'
import { TypeIdentifierEnum } from '../types/enum/TypeIdentifierEnum'
import {
BroadcastFinalStateReq,
deserializeBroadcastFinalStateReq,
serializeBroadcastFinalStateReq,
} from '../types/BroadcastFinalStateReq'
import { verifyPayload } from '../types/ajv/Helpers'
import {
SpreadTxToGroupSyncingReq,
deserializeSpreadTxToGroupSyncingReq,
serializeSpreadTxToGroupSyncingReq,
} from '../types/SpreadTxToGroupSyncingReq'
import { RequestTxAndStateReq, serializeRequestTxAndStateReq } from '../types/RequestTxAndStateReq'
import { RequestTxAndStateResp, deserializeRequestTxAndStateResp } from '../types/RequestTxAndStateResp'
import { deserializeRequestStateForTxReq, serializeRequestStateForTxReq } from '../types/RequestStateForTxReq'
import {
deserializeRequestStateForTxResp,
RequestStateForTxRespSerialized,
serializeRequestStateForTxResp,
} from '../types/RequestStateForTxResp'
import {
deserializeRequestReceiptForTxResp,
RequestReceiptForTxRespSerialized,
} from '../types/RequestReceiptForTxResp'
import {
RequestReceiptForTxReqSerialized,
serializeRequestReceiptForTxReq,
} from '../types/RequestReceiptForTxReq'
import { isNodeInRotationBounds } from '../p2p/Utils'
import { ResponseError } from '../types/ResponseError'
import { error } from 'console'
interface Receipt {
tx: AcceptedTx
}
const txStatBucketSize = {
default: [
1, 2, 4, 8, 16, 30, 60, 125, 250, 500, 1000, 2000, 4000, 8000, 10000, 20000, 30000, 60000, 100000,
],
}
export enum DebugComplete {
Incomplete = 0,
Completed = 1,
}
class TransactionQueue {
app: Shardus.App
crypto: Crypto
config: Shardus.StrictServerConfiguration
profiler: Profiler
logger: Logger
p2p: P2P
storage: Storage
stateManager: StateManager
mainLogger: L4jsLogger
seqLogger: L4jsLogger
fatalLogger: L4jsLogger
shardLogger: L4jsLogger
statsLogger: L4jsLogger
statemanager_fatal: (key: string, log: string) => void
_transactionQueue: QueueEntry[] //old name: newAcceptedTxQueue
pendingTransactionQueue: QueueEntry[] //old name: newAcceptedTxQueueTempInjest
archivedQueueEntries: QueueEntry[]
txDebugStatList: utils.FIFOCache<string, TxDebug>
_transactionQueueByID: Map<string, QueueEntry> //old name: newAcceptedTxQueueByID
pendingTransactionQueueByID: Map<string, QueueEntry> //old name: newAcceptedTxQueueTempInjestByID
archivedQueueEntriesByID: Map<string, QueueEntry>
receiptsToForward: ArchiverReceipt[]
forwardedReceiptsByTimestamp: Map<number, ArchiverReceipt>
receiptsBundleByInterval: Map<number, ArchiverReceipt[]>
receiptsForwardedTimestamp: number
queueStopped: boolean
queueEntryCounter: number
queueRestartCounter: number
archivedQueueEntryMaxCount: number
transactionProcessingQueueRunning: boolean //archivedQueueEntryMaxCount is a maximum amount of queue entries to store, usually we should never have this many stored since tx age will be used to clean up the list
processingLastRunTime: number
processingMinRunBreak: number
transactionQueueHasRemainingWork: boolean
executeInOneShard: boolean
useNewPOQ: boolean
txCoverageMap: { [key: symbol]: unknown }
/** This is a set of updates to rework how TXs can time out in the queue. After a enough testing this should become the default and we can remove the old code */
queueTimingFixes: boolean
/** process loop stats. This map contains the latest and the last of each time overage category */
lastProcessStats: { [limitName: string]: ProcessQueueStats }
largePendingQueueReported: boolean
queueReads: Set<string>
queueWrites: Set<string>
queueReadWritesOld: Set<string>
/** is the processing queue currently considered stuck */
isStuckProcessing: boolean
/** this s how many times the processing queue has transitioned from unstuck to stuck */
stuckProcessingCount: number
/** this is how many cycles processing is stuck becuase it has not run recently */
stuckProcessingCyclesCount: number
/** this is how many cycles processing is stuck and we can confirm the queue did not finish */
stuckProcessingQueueLockedCyclesCount: number
/** these three strings help us have a trail if the processing queue becomes stuck */
debugLastAwaitedCall: string
debugLastAwaitedCallInner: string
debugLastAwaitedAppCall: string
debugLastAwaitedCallInnerStack: { [key: string]: number }
debugLastAwaitedAppCallStack: { [key: string]: number }
debugLastProcessingQueueStartTime: number
debugRecentQueueEntry: QueueEntry
nonceQueue: Map<string, NonceQueueItem[]>
constructor(
stateManager: StateManager,
profiler: Profiler,
app: Shardus.App,
logger: Logger,
storage: Storage,
p2p: P2P,
crypto: Crypto,
config: Shardus.StrictServerConfiguration,
) {
this.crypto = crypto
this.app = app
this.logger = logger
this.config = config
this.profiler = profiler
this.p2p = p2p
this.storage = storage
this.stateManager = stateManager
this.useNewPOQ = this.config.stateManager.useNewPOQ
this.mainLogger = logger.getLogger('main')
this.seqLogger = logger.getLogger('seq')
this.fatalLogger = logger.getLogger('fatal')
this.shardLogger = logger.getLogger('shardDump')
this.statsLogger = logger.getLogger('statsDump')
this.statemanager_fatal = stateManager.statemanager_fatal
this.queueStopped = false
this.queueEntryCounter = 0
this.queueRestartCounter = 0
this._transactionQueue = []
this.pendingTransactionQueue = []
this.archivedQueueEntries = []
this.nonceQueue = new Map()
this.txDebugStatList = new utils.FIFOCache<string, TxDebug>(this.config.debug.debugStatListMaxSize)
this.receiptsToForward = []
this.forwardedReceiptsByTimestamp = new Map()
this.receiptsBundleByInterval = new Map()
this.receiptsForwardedTimestamp = shardusGetTime()
this._transactionQueueByID = new Map()
this.pendingTransactionQueueByID = new Map()
this.archivedQueueEntriesByID = new Map()
this.archivedQueueEntryMaxCount = 5000 // was 50000 but this too high
// 10k will fit into memory and should persist long enough at desired loads
this.transactionProcessingQueueRunning = false
this.processingLastRunTime = 0
this.processingMinRunBreak = 200 //20 //200ms breaks between processing loops
this.transactionQueueHasRemainingWork = false
this.executeInOneShard = false
if (this.config.sharding.executeInOneShard === true) {
this.executeInOneShard = true
}
this.txCoverageMap = {}
this.queueTimingFixes = true
this.lastProcessStats = {}
this.largePendingQueueReported = false
this.isStuckProcessing = false
this.stuckProcessingCount = 0
this.stuckProcessingCyclesCount = 0
this.stuckProcessingQueueLockedCyclesCount = 0
this.debugLastAwaitedCall = ''
this.debugLastAwaitedCallInner = ''
this.debugLastAwaitedAppCall = ''
this.debugLastProcessingQueueStartTime = 0
this.debugLastAwaitedCallInnerStack = {}
this.debugLastAwaitedAppCallStack = {}
this.debugRecentQueueEntry = null
}
/***
* ######## ## ## ######## ######## ####### #### ## ## ######## ######
* ## ### ## ## ## ## ## ## ## ## ### ## ## ## ##
* ## #### ## ## ## ## ## ## ## ## #### ## ## ##
* ###### ## ## ## ## ## ######## ## ## ## ## ## ## ## ######
* ## ## #### ## ## ## ## ## ## ## #### ## ##
* ## ## ### ## ## ## ## ## ## ## ### ## ## ##
* ######## ## ## ######## ## ####### #### ## ## ## ######
*/
setupHandlers(): void {
this.p2p.registerInternal(
'broadcast_state',
async (payload: { txid: string; stateList: Shardus.WrappedResponse[] }) => {
profilerInstance.scopedProfileSectionStart('broadcast_state')
try {
// Save the wrappedAccountState with the rest our queue data
// let message = { stateList: datas, txid: queueEntry.acceptedTX.id }
// this.p2p.tell([correspondingEdgeNode], 'broadcast_state', message)
// make sure we have it
const queueEntry = this.getQueueEntrySafe(payload.txid) // , payload.timestamp)
//It is okay to ignore this transaction if the txId is not found in the queue.
if (queueEntry == null) {
//In the past we would enqueue the TX, expecially if syncing but that has been removed.
//The normal mechanism of sharing TXs is good enough.
nestedCountersInstance.countEvent('processing', 'broadcast_state_noQueueEntry')
return
}
// add the data in
for (const data of payload.stateList) {
this.queueEntryAddData(queueEntry, data)
if (queueEntry.state === 'syncing') {
/* prettier-ignore */ if (logFlags.playback) this.logger.playbackLogNote('shrd_sync_gotBroadcastData', `${queueEntry.acceptedTx.txId}`, ` qId: ${queueEntry.entryID} data:${data.accountId}`)
}
}
} finally {
profilerInstance.scopedProfileSectionEnd('broadcast_state')
}
}
)
this.p2p.registerInternal(
'broadcast_state_complete_data',
async (payload: { txid: string; stateList: Shardus.WrappedResponse[] }) => {
profilerInstance.scopedProfileSectionStart('broadcast_state_complete_data')
try {
const queueEntry = this.getQueueEntrySafe(payload.txid) // , payload.timestamp)
if (queueEntry == null) {
nestedCountersInstance.countEvent('processing', 'broadcast_state_complete_data_noQueueEntry')
return
}
if (queueEntry.gossipedCompleteData === true) {
return
}
for (const data of payload.stateList) {
this.queueEntryAddData(queueEntry, data)
}
Comms.sendGossip(
'broadcast_state_complete_data',
payload,
undefined,
undefined,
queueEntry.executionGroup,
false,
6,
queueEntry.acceptedTx.txId
)
queueEntry.gossipedCompleteData = true
} finally {
profilerInstance.scopedProfileSectionEnd('broadcast_state_complete_data')
}
}
)
const broadcastStateRoute: P2PTypes.P2PTypes.Route<InternalBinaryHandler<Buffer>> = {
name: InternalRouteEnum.binary_broadcast_state,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
handler: (payload, respond, header, sign) => {
const route = InternalRouteEnum.binary_broadcast_state
nestedCountersInstance.countEvent('internal', route)
profilerInstance.scopedProfileSectionStart(route, false, payload.length)
const errorHandler = (
errorType: RequestErrorEnum,
opts?: { customErrorLog?: string; customCounterSuffix?: string }
): void => requestErrorHandler(route, errorType, header, opts)
try {
const requestStream = getStreamWithTypeCheck(payload, TypeIdentifierEnum.cBroadcastStateReq)
if (!requestStream) {
return errorHandler(RequestErrorEnum.InvalidRequest)
}
// verification data checks
if (header.verification_data == null) {
return errorHandler(RequestErrorEnum.MissingVerificationData)
}
const verificationDataParts = verificationDataSplitter(header.verification_data)
if (verificationDataParts.length !== 3) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
const [vTxId, vStateSize, vStateAddress] = verificationDataParts
const queueEntry = this.getQueueEntrySafe(vTxId)
//It is okay to ignore this transaction if the txId is not found in the queue.
if (queueEntry == null) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`${route} cant find queueEntry for: ${utils.makeShortHash(vTxId)}`)
return errorHandler(RequestErrorEnum.InvalidVerificationData, {
customCounterSuffix: 'queueEntryNotFound',
})
}
const isSenderValid = this.validateCorrespondingTellSender(
queueEntry,
vStateAddress,
header.sender_id
)
/* prettier-ignore */ if (logFlags.verbose && logFlags.console) console.log(`${route} TxId: ${vTxId} isSenderValid: ${isSenderValid}`)
if (!isSenderValid) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`${route} validateCorrespondingTellSender failed`)
return errorHandler(RequestErrorEnum.InvalidSender)
}
const req = deserializeBroadcastStateReq(requestStream)
if (req.txid !== vTxId) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
if (req.stateList.length !== parseInt(vStateSize)) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
/* prettier-ignore */ if (logFlags.verbose && logFlags.console) console.log(`${route}: txId: ${req.txid} stateSize: ${req.stateList.length} stateAddress: ${vStateAddress}`)
for (let i = 0; i < req.stateList.length; i++) {
// eslint-disable-next-line security/detect-object-injection
const state = req.stateList[i]
if (
i !== 0 &&
!this.validateCorrespondingTellSender(queueEntry, state.accountId, header.sender_id)
) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`${route} validateCorrespondingTellSender failed for ${state.accountId}`)
return errorHandler(RequestErrorEnum.InvalidSender)
}
this.queueEntryAddData(queueEntry, state)
if (queueEntry.state === 'syncing') {
/* prettier-ignore */ if (logFlags.playback) this.logger.playbackLogNote('shrd_sync_gotBroadcastData', `${queueEntry.acceptedTx.txId}`, ` qId: ${queueEntry.entryID} data:${state.accountId}`)
}
}
} catch (e) {
nestedCountersInstance.countEvent('internal', `${route}-exception`)
this.mainLogger.error(`${route}: Exception executing request: ${errorToStringFull(e)}`)
} finally {
profilerInstance.scopedProfileSectionEnd(route, payload.length)
}
},
}
this.p2p.registerInternalBinary(broadcastStateRoute.name, broadcastStateRoute.handler)
this.p2p.registerInternal(
'broadcast_finalstate',
async (payload: { txid: string; stateList: Shardus.WrappedResponse[] }) => {
profilerInstance.scopedProfileSectionStart('broadcast_finalstate')
try {
// make sure we have it
const queueEntry = this.getQueueEntrySafe(payload.txid) // , payload.timestamp)
//It is okay to ignore this transaction if the txId is not found in the queue.
if (queueEntry == null) {
//In the past we would enqueue the TX, expecially if syncing but that has been removed.
//The normal mechanism of sharing TXs is good enough.
nestedCountersInstance.countEvent('processing', 'broadcast_finalstate_noQueueEntry')
return
}
if (logFlags.debug)
this.mainLogger.debug(`broadcast_finalstate ${queueEntry.logID}, ${Utils.safeStringify(payload.stateList)}`)
// add the data in
const savedAccountIds: Set<string> = new Set()
for (const data of payload.stateList) {
//let wrappedResponse = data as Shardus.WrappedResponse
//this.queueEntryAddData(queueEntry, data)
if (data == null) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`broadcast_finalstate data == null`)
continue
}
if (queueEntry.collectedFinalData[data.accountId] == null) {
queueEntry.collectedFinalData[data.accountId] = data
savedAccountIds.add(data.accountId)
/* prettier-ignore */ if (logFlags.playback && logFlags.verbose) this.logger.playbackLogNote('broadcast_finalstate', `${queueEntry.logID}`, `broadcast_finalstate addFinalData qId: ${queueEntry.entryID} data:${utils.makeShortHash(data.accountId)} collected keys: ${utils.stringifyReduce(Object.keys(queueEntry.collectedFinalData))}`)
}
// if (queueEntry.state === 'syncing') {
// /* prettier-ignore */ if (logFlags.playback) this.logger.playbackLogNote('shrd_sync_gotBroadcastfinalstate', `${queueEntry.acceptedTx.txId}`, ` qId: ${queueEntry.entryID} data:${data.accountId}`)
// }
}
const nodesToSendTo: Set<Node> = new Set()
for (const data of payload.stateList) {
if (data == null) {
continue
}
if (savedAccountIds.has(data.accountId) === false) {
continue
}
const storageNodes = this.stateManager.transactionQueue.getStorageGroupForAccount(data.accountId)
for (const node of storageNodes) {
nodesToSendTo.add(node)
}
}
if (nodesToSendTo.size > 0) {
Comms.sendGossip(
'gossip-final-state',
payload,
null,
null,
Array.from(nodesToSendTo),
false,
4,
queueEntry.acceptedTx.txId
)
nestedCountersInstance.countEvent(`processing`, `forwarded final data to storage nodes`)
}
} finally {
profilerInstance.scopedProfileSectionEnd('broadcast_finalstate')
}
}
)
const broadcastFinalStateRoute: P2PTypes.P2PTypes.Route<InternalBinaryHandler<Buffer>> = {
name: InternalRouteEnum.binary_broadcast_finalstate,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
handler: (payload, response, header, sign) => {
const route = InternalRouteEnum.binary_broadcast_finalstate
nestedCountersInstance.countEvent('internal', route)
profilerInstance.scopedProfileSectionStart(route, false, payload.length)
const errorHandler = (
errorType: RequestErrorEnum,
opts?: { customErrorLog?: string; customCounterSuffix?: string }
): void => requestErrorHandler(route, errorType, header, opts)
try {
const requestStream = getStreamWithTypeCheck(payload, TypeIdentifierEnum.cBroadcastFinalStateReq)
if (!requestStream) {
return errorHandler(RequestErrorEnum.InvalidRequest)
}
// verification data checks
if (header.verification_data == null) {
return errorHandler(RequestErrorEnum.MissingVerificationData)
}
const verificationDataParts = verificationDataSplitter(header.verification_data)
if (verificationDataParts.length !== 2) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
const [vTxId, vStateSize] = verificationDataParts
const queueEntry = this.getQueueEntrySafe(vTxId)
//It is okay to ignore this transaction if the txId is not found in the queue.
if (queueEntry == null) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`${route} cant find queueEntry for: ${utils.makeShortHash(vTxId)}`)
return errorHandler(RequestErrorEnum.InvalidVerificationData, {
customCounterSuffix: 'queueEntryNotFound',
})
}
// deserialization
const req = deserializeBroadcastFinalStateReq(requestStream)
if (req.txid !== vTxId) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
if (req.stateList.length !== parseInt(vStateSize)) {
return errorHandler(RequestErrorEnum.InvalidVerificationData)
}
/* prettier-ignore */ if (logFlags.verbose && logFlags.console) console.log(`${route}: txId: ${req.txid} stateSize: ${req.stateList.length}`)
let saveSomething = false
for (const data of req.stateList) {
//let wrappedResponse = data as Shardus.WrappedResponse
//this.queueEntryAddData(queueEntry, data)
if (data == null) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`broadcast_finalstate data == null`)
continue
}
if (queueEntry.collectedFinalData[data.accountId] == null) {
queueEntry.collectedFinalData[data.accountId] = data
saveSomething = true
/* prettier-ignore */ if (logFlags.playback && logFlags.verbose) this.logger.playbackLogNote('broadcast_finalstate', `${queueEntry.logID}`, `broadcast_finalstate addFinalData qId: ${queueEntry.entryID} data:${utils.makeShortHash(data.accountId)} collected keys: ${utils.stringifyReduce(Object.keys(queueEntry.collectedFinalData))}`)
}
// if (queueEntry.state === 'syncing') {
// /* prettier-ignore */ if (logFlags.playback) this.logger.playbackLogNote('shrd_sync_gotBroadcastfinalstate', `${queueEntry.acceptedTx.txId}`, ` qId: ${queueEntry.entryID} data:${data.accountId}`)
// }
}
if (saveSomething) {
const nodesToSendTo: Set<Node> = new Set()
for (const data of req.stateList) {
if (data == null) {
continue
}
const storageNodes = this.stateManager.transactionQueue.getStorageGroupForAccount(data.accountId)
for (const node of storageNodes) {
nodesToSendTo.add(node)
}
}
if (nodesToSendTo.size > 0) {
Comms.sendGossip(
'gossip-final-state',
req,
null,
null,
Array.from(nodesToSendTo),
false,
4,
queueEntry.acceptedTx.txId
)
nestedCountersInstance.countEvent(`processing`, `forwarded final data to storage nodes`)
}
}
} catch (e) {
nestedCountersInstance.countEvent('internal', `${route}-exception`)
this.mainLogger.error(`${route}: Exception executing request: ${errorToStringFull(e)}`)
} finally {
profilerInstance.scopedProfileSectionEnd(route, payload.length)
}
},
}
this.p2p.registerInternalBinary(broadcastFinalStateRoute.name, broadcastFinalStateRoute.handler)
this.p2p.registerInternal(
'spread_tx_to_group_syncing',
async (payload: Shardus.AcceptedTx, _respondWrapped: unknown, sender: Node) => {
profilerInstance.scopedProfileSectionStart('spread_tx_to_group_syncing')
try {
//handleSharedTX will also validate fields
this.handleSharedTX(payload.data, payload.appData, sender)
} finally {
profilerInstance.scopedProfileSectionEnd('spread_tx_to_group_syncing')
}
}
)
const spreadTxToGroupSyncingBinaryHandler: P2PTypes.P2PTypes.Route<InternalBinaryHandler<Buffer>> = {
name: InternalRouteEnum.binary_spread_tx_to_group_syncing,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
handler: async (payload, respond, header, sign) => {
const route = InternalRouteEnum.binary_spread_tx_to_group_syncing
nestedCountersInstance.countEvent('internal', route)
this.profiler.scopedProfileSectionStart(route, false, payload.length)
const errorHandler = (
errorType: RequestErrorEnum,
opts?: { customErrorLog?: string; customCounterSuffix?: string }
): void => requestErrorHandler(route, errorType, header, opts)
try {
const requestStream = getStreamWithTypeCheck(payload, TypeIdentifierEnum.cSpreadTxToGroupSyncingReq)
if (!requestStream) {
return errorHandler(RequestErrorEnum.InvalidRequest)
}
const req: SpreadTxToGroupSyncingReq = deserializeSpreadTxToGroupSyncingReq(requestStream)
const ajvErrors = verifyPayload('SpreadTxToGroupSyncingReq', req)
if (ajvErrors && ajvErrors.length > 0) {
this.mainLogger.error(`${route}: request validation errors: ${ajvErrors}`)
return errorHandler(RequestErrorEnum.InvalidPayload)
}
const node = this.p2p.state.getNode(header.sender_id)
this.handleSharedTX(req.data, req.appData, node)
} catch (e) {
nestedCountersInstance.countEvent('internal', `${route}-exception`)
this.mainLogger.error(`${route}: Exception executing request: ${errorToStringFull(e)}`)
} finally {
this.profiler.scopedProfileSectionEnd(route)
}
},
}
this.p2p.registerInternalBinary(
spreadTxToGroupSyncingBinaryHandler.name,
spreadTxToGroupSyncingBinaryHandler.handler
)
this.p2p.registerGossipHandler(
'spread_tx_to_group',
async (
payload: { data: Shardus.TimestampedTx; appData: unknown },
sender: Node,
tracker: string,
msgSize: number
) => {
profilerInstance.scopedProfileSectionStart('spread_tx_to_group', false, msgSize)
let respondSize = cUninitializedSize
try {
// Place tx in queue (if younger than m)
// gossip 'spread_tx_to_group' to transaction group
//handleSharedTX will also validate fields. payload is an AcceptedTX so must pass in the .data as the rawTX
const queueEntry = this.handleSharedTX(payload.data, payload.appData, sender)
if (queueEntry == null) {
return
}
// get transaction group
const transactionGroup = this.queueEntryGetTransactionGroup(queueEntry)
if (queueEntry.ourNodeInTransactionGroup === false) {
return
}
if (transactionGroup.length > 1) {
this.stateManager.debugNodeGroup(
queueEntry.acceptedTx.txId,
queueEntry.acceptedTx.timestamp,
`spread_tx_to_group transactionGroup:`,
transactionGroup
)
respondSize = await this.p2p.sendGossipIn(
'spread_tx_to_group',
payload,
tracker,
sender,
transactionGroup,
false,
-1,
queueEntry.acceptedTx.txId
)
/* prettier-ignore */ if (logFlags.verbose) console.log( 'queueEntry.isInExecutionHome', queueEntry.acceptedTx.txId, queueEntry.isInExecutionHome )
// If our node is in the execution group, forward this raw tx to the subscribed archivers
if (queueEntry.isInExecutionHome === true) {
this.addOriginalTxDataToForward(queueEntry)
}
}
} finally {
profilerInstance.scopedProfileSectionEnd('spread_tx_to_group', respondSize)
}
}
)
this.p2p.registerGossipHandler(
'gossip-final-state',
async (
payload: { txid: string; stateList: Shardus.WrappedResponse[] },
sender: Node,
tracker: string,
msgSize: number
) => {
profilerInstance.scopedProfileSectionStart('gossip-final-state', false, msgSize)
const respondSize = cUninitializedSize
try {
// make sure we have it
const queueEntry = this.getQueueEntrySafe(payload.txid) // , payload.timestamp)
//It is okay to ignore this transaction if the txId is not found in the queue.
if (queueEntry == null) {
//In the past we would enqueue the TX, expecially if syncing but that has been removed.
//The normal mechanism of sharing TXs is good enough.
nestedCountersInstance.countEvent('processing', 'gossip-final-state_noQueueEntry')
return
}
if (logFlags.debug)
this.mainLogger.debug(`gossip-final-state ${queueEntry.logID}, ${Utils.safeStringify(payload.stateList)}`)
// add the data in
let saveSomething = false
for (const data of payload.stateList) {
//let wrappedResponse = data as Shardus.WrappedResponse
//this.queueEntryAddData(queueEntry, data)
if (data == null) {
/* prettier-ignore */ if (logFlags.error && logFlags.verbose) this.mainLogger.error(`broadcast_finalstate data == null`)
continue
}
if (queueEntry.collectedFinalData[data.accountId] == null) {
queueEntry.collectedFinalData[data.accountId] = data
saveSomething = true
/* prettier-ignore */ if (logFlags.playback && logFlags.verbose) this.logger.playbackLogNote('broadcast_finalstate', `${queueEntry.logID}`, `broadcast_finalstate addFinalData qId: ${queueEntry.entryID} data:${utils.makeShortHash(data.accountId)} collected keys: ${utils.stringifyReduce(Object.keys(queueEntry.collectedFinalData))}`)
}
// if (queueEntry.state === 'syncing') {
// /* prettier-ignore */ if (logFlags.playback) this.logger.playbackLogNote('shrd_sync_gotBroadcastfinalstate', `${queueEntry.acceptedTx.txId}`, ` qId: ${queueEntry.entryID} data:${data.accountId}`)
// }
}
if (saveSomething) {
const nodesToSendTo: Set<Node> = new Set()
for (const data of payload.stateList) {
if (data == null) {
continue
}
const storageNodes = this.stateManager.transactionQueue.getStorageGroupForAccount(data.accountId)
for (const node of storageNodes) {
nodesToSendTo.add(node)
}
}
if (nodesToSendTo.size > 0) {
Comms.sendGossip(
'gossip-final-state',
payload,
undefined,
undefined,
Array.from(nodesToSendTo),
false,
4,
queueEntry.acceptedTx.txId
)
nestedCountersInstance.countEvent(`processing`, `forwarded final data to storage nodes`)
}
}
} finally {
profilerInstance.scopedProfileSectionEnd('gossip-final-state', respondSize)
}
}
)
/**
* request_state_for_tx
* used by the transaction queue when a queue entry needs to ask for missing state
*/
this.p2p.registerInternal(
'request_state_for_tx',
async (payload: RequestStateForTxReq, respond: (arg0: RequestStateForTxResp) => unknown) => {
profilerInstance.scopedProfileSectionStart('request_state_for_tx')
try {
const response: RequestStateForTxResp = {
stateList: [],
beforeHashes: {},
note: '',
success: false,
}
// app.getRelevantData(accountId, tx) -> wrappedAccountState for local accounts
let queueEntry = this.getQueueEntrySafe(payload.txid) // , payload.timestamp)
if (queueEntry == null) {
queueEntry = this.getQueueEntryArchived(payload.txid, 'request_state_for_tx') // , payload.timestamp)
}
if (queueEntry == null) {
response.note = `failed to find queue entry: ${utils.stringifyReduce(payload.txid)} ${
payload.timestamp
} dbg:${this.stateManager.debugTXHistory[utils.stringifyReduce(payload.txid)]}`
await respond(response)
// if a node cant get data it will have to get repaired by the patcher since we can only keep stuff en the archive queue for so long
// due to memory concerns
return
}
for (const key of payload.keys) {
// eslint-disable-next-line security/detect-object-injection
const data = queueEntry.originalData[key] // collectedData
if (data) {
//response.stateList.push(JSON.parse(data))
response.stateList.push(data)
}
}
response.success = true
await respond(response)
} finally {
profilerInstance.scopedProfileSectionEnd('request_state_for_tx')
}
}
)
const requestStateForTxRoute: P2PTypes.P2PTypes.Route<InternalBinaryHandler<Buffer>> = {
name: InternalRouteEnum.binary_request_state_for_tx,
handler: (payload, respond) => {
const route = InternalRouteEnum.binary_request_state_for_tx
profilerInstance.scopedProfileSectionStart(route)
nestedCountersInstance.countEvent('internal', route)
const response: RequestStateForTxRespSerialized = {
stateList: [],
beforeHashes: {},
note: '',
success: false,
}
try {
const responseStream = getStreamWithTypeCheck(payload, TypeIdentifierEnum.cRequestStateForTxReq)
if (!responseStream) {
this.mainLogger.error(`${route}: Invalid request`)
respond(response, serializeRequestStateForTxResp)
return
}
const req = deserializeRequestStateForTxReq(responseStream)
if (req.txid == null) {
throw new Error('Txid is null')
}
let queueEntry = this.getQueueEntrySafe(req.txid)
if (queueEntry == null) {
queueEntry = this.getQueueEntryArchived(req.txid, InternalRouteEnum.binary_request_state_for_tx)
}
if (queueEntry == null) {
response.note = `failed to find queue entry: ${utils.stringifyReduce(req.txid)} ${
req.timestamp
} dbg:${this.stateManager.debugTXHistory[utils.stringifyReduce(req.txid)]}`
respond(response, serializeRequestStateForTxResp)
// if a node cant get data it will have to get repaired by the patcher since we can only keep stuff en the archive queue for so long
// due to memory concerns
return
}
for (const key of req.keys) {
// eslint-disable-next-line security/detect-object-injection
const data = queueEntry.originalData[key] // collectedData
if (data) {
response.stateList.push(data)
}
}
response.success = true
respond(response, serializeRequestStateForTxResp)
} catch (e) {
this.mainLogger.error(
`${
InternalRouteEnum.binary_request_state_for_tx
}: Exception executing request: ${errorToStringFull(e)}`
)
nestedCountersInstance.countEvent('internal', `${route}-exception`)
respond(response, serializeRequestStateForTxResp)
} finally {
profilerInstance.scopedProfileSectionEnd(InternalRouteEnum.binary_request_state_for_tx)
}
},
}
this.p2p.registerInternalBinary(requestStateForTxRoute.name, requestStateForTxRoute.handler)
networkContext.registerExternalPost('get-tx-receipt', async (req, res) => {
let result: { success: boolean; receipt?: ArchiverReceipt | AppliedReceipt2; reason?: string }
try {
let error = utils.validateTypes(req.body, {
txId: 's',
timestamp: 'n',
full_receipt: 'b',
sign: 'o',
})
if (error) return res.send((result = { success: false, reason: error }))
error = utils.validateTypes(req.body.sign, {
owner: 's',
sig: 's',
})
if (error) return res.send((result = { success: false, reason: error }))
const { txId, timestamp, full_receipt, sign } = req.body
const isReqFromArchiver = Archivers.archivers.has(sign.owner)
if (!isReqFromArchiver) {
result = { success: false, reason: 'Request not from Archiver.' }
} else {
const isValidSignature = this.crypto.verify(req.body, sign.owner)
if (isValidSignature) {
let queueEntry: QueueEntry
if (
this.archivedQueueEntriesByID.has(txId) &&
this.archivedQueueEntriesByID.get(txId)?.acceptedTx?.timestamp === timestamp
) {
if (logFlags.verbose) console.log('get-tx-receipt: ', txId, timestamp, 'archived')
queueEntry = this.archivedQueueEntriesByID.get(txId)
} else if (
this._transactionQueueByID.has(txId) &&
this._transactionQueueByID.get(txId)?.state === 'commiting' &&
this._transactionQueueByID.get(txId)?.acceptedTx?.timestamp === timestamp
) {
if (logFlags.verbose) console.log('get-tx-receipt: ', txId, timestamp, 'commiting')
queueEntry = this._transactionQueueByID.get(txId)
}
if (!queueEntry) return res.status(400).json({ success: false, reason: 'Receipt Not Found.' })
if (full_receipt) {
const fullReceipt: ArchiverReceipt = this.getArchiverReceiptFromQueueEntry(queueEntry)
if (fullReceipt === null) return res.status(400).json({ success: false, reason: 'Receipt Not Found.' })
result = Utils.safeJsonParse(Utils.safeStringify({ success: true, receipt: fullReceipt }))
} else {
result = { success: true, receipt: this.stateManager.getReceipt2(queueEntry) }
}
} else {
result = { success: false, reason: 'Invalid Signature.' }
}
}
res.send(result)
} catch (e) {
console.log('Error caught in /get-tx-receipt: ', e)
res.send((result = { success: false, reason: e }))
}
})
}
isTxInPendingNonceQueue(accountId: string, txId: string): boolean {
this.mainLogger.debug(`isTxInPendingNonceQueue ${accountId} ${txId}`, this.nonceQueue)
const queue = this.nonceQueue.get(accountId)
if (queue == null) {
return false
}
for (const item of queue) {
if (item.txId === txId) {
return true
}
}
return false
}
getPendingCountInNonceQueue(): { totalQueued: number; totalAccounts: number; avgQueueLength: number} {
let totalQueued = 0
let totalAccounts = 0
for (const queue of this.nonceQueue.values()) {
totalQueued += queue.length
totalAccounts++
}
const avgQueueLength = totalQueued / totalAccounts
return { totalQueued, totalAccounts, avgQueueLength }
}
addTransactionToNonceQueue(nonceQueueEntry: NonceQueueItem): {success: boolean; reason?: string} {
try {
let queue = this.nonceQueue.get(nonceQueueEntry.accountId)
if (queue == null || (Array.isArray(queue) && queue.length === 0)) {
queue = [nonceQueueEntry]
this.nonceQueue.set(nonceQueueEntry.accountId, queue)
if (logFlags.debug) this.mainLogger.debug(`adding new nonce tx: ${nonceQueueEntry.txId} ${nonceQueueEntry.accountId} with nonce ${nonceQueueEntry.nonce}`)
} else if (queue && queue.length > 0) {
let index = utils.binarySearch(queue, nonceQueueEntry, (a, b) => Number(a.nonce) - Number(b.nonce))
if (index != -1) {
// there is existing item with the same nonce. replace it with the new one
queue[index] = nonceQueueEntry
this.nonceQueue.set(nonceQueueEntry.accountId, queue)
nestedCountersInstance.countEvent('processing', 'replaceExistingNonceTx')
if (logFlags.debug) this.mainLogger.debug(`replace existing nonce tx ${nonceQueueEntry.accountId} with nonce ${nonceQueueEntry.nonce}, txId: ${nonceQueueEntry.txId}`)
return { success: true, reason: 'Replace existing pending nonce tx' }
}
// add new item to the queue
utils.insertSorted(queue, nonceQueueEntry, (a, b) => Number(a.nonce) - Number(b.nonce));
this.nonceQueue.set(nonceQueueEntry.accountId, queue)