-
Notifications
You must be signed in to change notification settings - Fork 180
/
baseapp_parallel.go
869 lines (737 loc) · 21.2 KB
/
baseapp_parallel.go
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
package baseapp
import (
"bytes"
"encoding/hex"
"runtime"
"sync"
"github.com/spf13/viper"
"github.com/okex/exchain/libs/cosmos-sdk/store/types"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
sdkerrors "github.com/okex/exchain/libs/cosmos-sdk/types/errors"
abci "github.com/okex/exchain/libs/tendermint/abci/types"
sm "github.com/okex/exchain/libs/tendermint/state"
)
var (
maxTxResultInChan = 200000
maxGoroutineNumberInParaTx = runtime.NumCPU()
multiCacheListClearInterval = int64(100)
feeAccountKeyInStore = make([]byte, 0)
)
type extraDataForTx struct {
supportPara bool
fee sdk.Coins
isEvm bool
needUpdateTXCounter bool
from string
to string
stdTx sdk.Tx
decodeErr error
}
type txWithIndex struct {
index int
txBytes []byte
}
// getExtraDataByTxs preprocessing tx : verify tx, get sender, get toAddress, get txFee
func (app *BaseApp) getExtraDataByTxs(txs [][]byte) {
para := app.parallelTxManage
var wg sync.WaitGroup
wg.Add(len(txs))
jobChan := make(chan txWithIndex, len(txs))
for groupIndex := 0; groupIndex < maxGoroutineNumberInParaTx; groupIndex++ {
go func(ch chan txWithIndex) {
for j := range ch {
index := j.index
txBytes := j.txBytes
var tx sdk.Tx
var err error
if mem := GetGlobalMempool(); mem != nil {
tx, _ = mem.ReapEssentialTx(txBytes).(sdk.Tx)
}
if tx == nil {
tx, err = app.txDecoder(txBytes)
if err != nil {
para.extraTxsInfo[index] = &extraDataForTx{
decodeErr: err,
}
wg.Done()
continue
}
}
if tx != nil {
app.blockDataCache.SetTx(txBytes, tx)
}
coin, isEvm, needUpdateTXCounter, s, toAddr, _, supportPara := app.getTxFeeAndFromHandler(app.getContextForTx(runTxModeDeliver, txBytes), tx)
para.extraTxsInfo[index] = &extraDataForTx{
supportPara: supportPara,
fee: coin,
isEvm: isEvm,
needUpdateTXCounter: needUpdateTXCounter,
from: s,
to: toAddr,
stdTx: tx,
}
wg.Done()
}
}(jobChan)
}
for index, v := range txs {
jobChan <- txWithIndex{
index: index,
txBytes: v,
}
}
close(jobChan)
wg.Wait()
}
var (
rootAddr = make(map[string]string, 0)
)
// Find father node
func Find(x string) string {
if rootAddr[x] != x {
rootAddr[x] = Find(rootAddr[x])
}
return rootAddr[x]
}
// Union from and to
func Union(x string, yString string) {
if _, ok := rootAddr[x]; !ok {
rootAddr[x] = x
}
if yString == "" {
return
}
if _, ok := rootAddr[yString]; !ok {
rootAddr[yString] = yString
}
fx := Find(x)
fy := Find(yString)
if fx != fy {
rootAddr[fy] = fx
}
}
// calGroup cal group by txs
func (app *BaseApp) calGroup() {
pm := app.parallelTxManage
rootAddr = make(map[string]string, 0)
pm.cosmosTxIndexInBlock = 0
for index, tx := range pm.extraTxsInfo {
if tx.supportPara { //evmTx & wasmTx
Union(tx.from, tx.to)
} else {
app.parallelTxManage.putResult(index, &executeResult{paraMsg: &sdk.ParaMsg{}, msIsNil: true})
}
if tx.needUpdateTXCounter {
pm.txIndexMpUpdateTXCounter[index] = true
pm.txByteMpCosmosIndex[string(pm.txs[index])] = pm.cosmosTxIndexInBlock
pm.cosmosTxIndexInBlock++
}
}
addrToID := make(map[string]int, 0)
for index, txInfo := range pm.extraTxsInfo {
if !txInfo.supportPara {
continue
}
rootAddr := Find(txInfo.from)
id, exist := addrToID[rootAddr]
if !exist {
id = len(pm.groupList)
addrToID[rootAddr] = id
}
pm.groupList[id] = append(pm.groupList[id], index)
pm.txIndexWithGroup[index] = id
}
groupSize := len(pm.groupList)
for groupIndex := 0; groupIndex < groupSize; groupIndex++ {
list := pm.groupList[groupIndex]
for index := 0; index < len(list); index++ {
if index+1 <= len(list)-1 {
app.parallelTxManage.nextTxInGroup[list[index]] = list[index+1]
}
if index-1 >= 0 {
app.parallelTxManage.preTxInGroup[list[index]] = list[index-1]
}
}
}
}
// ParallelTxs run txs
func (app *BaseApp) ParallelTxs(txs [][]byte, onlyCalSender bool) []*abci.ResponseDeliverTx {
txSize := len(txs)
if txSize == 0 {
return make([]*abci.ResponseDeliverTx, 0)
}
if len(feeAccountKeyInStore) == 0 {
_, feeAccountKeyInStore = app.getFeeCollectorInfoHandler(app.deliverState.ctx, true)
}
pm := app.parallelTxManage
pm.init(txs, app.deliverState.ctx.BlockHeight(), app.deliverState.ms)
app.getExtraDataByTxs(txs)
app.calGroup()
return app.runTxs()
}
func (app *BaseApp) fixFeeCollector() {
ctx, _ := app.cacheTxContext(app.getContextForTx(runTxModeDeliver, []byte{}), []byte{})
ctx.SetMultiStore(app.parallelTxManage.cms)
// The feesplit is only processed at the endblock
if err := app.updateFeeCollectorAccHandler(ctx, app.parallelTxManage.currTxFee, nil); err != nil {
panic(err)
}
}
func (app *BaseApp) runTxs() []*abci.ResponseDeliverTx {
maxGas := app.getMaximumBlockGas()
currentGas := uint64(0)
overFlow := func(sumGas uint64, currGas int64, maxGas uint64) bool {
if maxGas <= 0 {
return false
}
if sumGas+uint64(currGas) >= maxGas { // TODO : fix later
return true
}
return false
}
signal := make(chan int, 1)
rerunIdx := 0
pm := app.parallelTxManage
asyncCb := func(receiveTxIndex int) {
if pm.alreadyEnd {
return
}
//skip old txIndex
if receiveTxIndex < pm.upComingTxIndex || receiveTxIndex >= pm.txSize {
return
}
for true {
res := pm.getTxResult(pm.upComingTxIndex)
if res == nil {
break
}
isReRun := false
if pm.isConflict(res) || overFlow(currentGas, res.resp.GasUsed, maxGas) || pm.haveAnteErrTx {
rerunIdx++
isReRun = true
// conflict rerun tx
if !pm.extraTxsInfo[pm.upComingTxIndex].supportPara {
app.fixFeeCollector()
}
res = app.deliverTxWithCache(pm.upComingTxIndex)
}
if res.paraMsg.AnteErr != nil {
res.msIsNil = true
pm.handleAnteErrTx(pm.txIndexMpUpdateTXCounter[pm.upComingTxIndex])
}
pm.deliverTxs[pm.upComingTxIndex] = &res.resp
pm.finalResult[pm.upComingTxIndex] = res
pm.blockGasMeterMu.Lock()
// Note : don't take care of the case of ErrorGasOverflow
app.deliverState.ctx.BlockGasMeter().ConsumeGas(sdk.Gas(res.resp.GasUsed), "unexpected error")
pm.blockGasMeterMu.Unlock()
pm.SetCurrentIndexRes(pm.upComingTxIndex, res)
if !res.msIsNil {
pm.currTxFee = pm.currTxFee.Add(pm.extraTxsInfo[pm.upComingTxIndex].fee.Sub(pm.finalResult[pm.upComingTxIndex].paraMsg.RefundFee)...)
}
currentGas += uint64(res.resp.GasUsed)
if isReRun {
if pm.nextTxInGroup[pm.upComingTxIndex] != 0 {
pm.groupTasks[pm.txIndexWithGroup[pm.upComingTxIndex]].addRerun(pm.upComingTxIndex)
}
}
pm.upComingTxIndex++
if pm.upComingTxIndex == pm.txSize {
app.logger.Info("Paralleled-tx", "blockHeight", app.deliverState.ctx.BlockHeight(), "len(txs)", pm.txSize,
"Parallel run", pm.txSize-rerunIdx, "ReRun", rerunIdx, "len(group)", len(pm.groupList))
signal <- 0
return
}
}
}
pm.resultCb = asyncCb
pm.StartResultHandle()
for index := 0; index < len(pm.groupList); index++ {
pm.groupTasks = append(pm.groupTasks, newGroupTask(len(pm.groupList[index]), pm.addMultiCache, pm.nextTxInThisGroup, app.asyncDeliverTx, pm.putResult))
pm.groupTasks[index].addTask(pm.groupList[index][0])
}
if len(pm.groupList) == 0 {
pm.resultCh <- 0
}
//waiting for call back
<-signal
for _, v := range pm.groupTasks {
v.stopChan <- struct{}{}
}
pm.alreadyEnd = true
pm.stop <- struct{}{}
// update fee collector balance
app.feeCollector = app.parallelTxManage.currTxFee
// fix logs
receiptsLogs := app.endParallelTxs(pm.txSize)
ctx, _ := app.cacheTxContext(app.getContextForTx(runTxModeDeliver, []byte{}), []byte{})
ctx.SetMultiStore(app.parallelTxManage.cms)
if app.parallelTxManage.NeedUpdateTXCounter() {
app.updateCosmosTxCount(ctx, app.parallelTxManage.cosmosTxIndexInBlock-1)
}
for index, v := range receiptsLogs {
if len(v) != 0 { // only update evm tx result
pm.deliverTxs[index].Data = v
}
}
pm.cms.Write()
return pm.deliverTxs
}
func (pm *parallelTxManager) nextTxInThisGroup(txindex int) (int, bool) {
if pm.alreadyEnd {
return 0, false
}
data, ok := pm.nextTxInGroup[txindex]
return data, ok
}
func (app *BaseApp) endParallelTxs(txSize int) [][]byte {
// handle receipt's logs
logIndex := make([]int, txSize)
errs := make([]error, txSize)
hasEnterEvmTx := make([]bool, txSize)
resp := make([]abci.ResponseDeliverTx, txSize)
watchers := make([]sdk.IWatcher, txSize)
txs := make([]sdk.Tx, txSize)
app.FeeSplitCollector = make([]*sdk.FeeSplitInfo, 0)
for index := 0; index < txSize; index++ {
txRes := app.parallelTxManage.finalResult[index]
logIndex[index] = txRes.paraMsg.LogIndex
errs[index] = txRes.paraMsg.AnteErr
hasEnterEvmTx[index] = txRes.paraMsg.HasRunEvmTx
resp[index] = txRes.resp
watchers[index] = txRes.watcher
txs[index] = app.parallelTxManage.extraTxsInfo[index].stdTx
if txRes.FeeSpiltInfo.HasFee {
app.FeeSplitCollector = append(app.FeeSplitCollector, txRes.FeeSpiltInfo)
}
}
app.watcherCollector(watchers...)
app.parallelTxManage.clear()
return app.logFix(txs, logIndex, hasEnterEvmTx, errs, resp)
}
// we reuse the nonce that changed by the last async call
// if last ante handler has been failed, we need rerun it ? or not?
func (app *BaseApp) deliverTxWithCache(txIndex int) *executeResult {
app.parallelTxManage.currentRerunIndex = txIndex
defer func() {
app.parallelTxManage.currentRerunIndex = -1
}()
txStatus := app.parallelTxManage.extraTxsInfo[txIndex]
if txStatus.stdTx == nil {
asyncExe := newExecuteResult(sdkerrors.ResponseDeliverTx(txStatus.decodeErr,
0, 0, app.trace), nil, uint32(txIndex), nil, 0, sdk.EmptyWatcher{}, nil, app.parallelTxManage, nil)
return asyncExe
}
var (
resp abci.ResponseDeliverTx
mode runTxMode
)
mode = runTxModeDeliverInAsync
info, errM := app.runTxWithIndex(txIndex, mode, app.parallelTxManage.txs[txIndex], txStatus.stdTx, LatestSimulateTxHeight)
if errM != nil {
resp = sdkerrors.ResponseDeliverTx(errM, info.gInfo.GasWanted, info.gInfo.GasUsed, app.trace)
} else {
resp = abci.ResponseDeliverTx{
GasWanted: int64(info.gInfo.GasWanted), // TODO: Should type accept unsigned ints?
GasUsed: int64(info.gInfo.GasUsed), // TODO: Should type accept unsigned ints?
Log: info.result.Log,
Data: info.result.Data,
Events: info.result.Events.ToABCIEvents(),
}
}
asyncExe := newExecuteResult(resp, info.msCacheAnte, uint32(txIndex), info.ctx.ParaMsg(),
0, info.runMsgCtx.GetWatcher(), info.tx.GetMsgs(), app.parallelTxManage, info.ctx.GetFeeSplitInfo())
app.parallelTxManage.addMultiCache(info.msCacheAnte, info.msCache)
return asyncExe
}
type executeResult struct {
resp abci.ResponseDeliverTx
ms sdk.CacheMultiStore
msIsNil bool // TODO delete it
counter uint32
paraMsg *sdk.ParaMsg
blockHeight int64
watcher sdk.IWatcher
msgs []sdk.Msg
FeeSpiltInfo *sdk.FeeSplitInfo
rwSet types.MsRWSet
}
func newExecuteResult(r abci.ResponseDeliverTx, ms sdk.CacheMultiStore, counter uint32,
paraMsg *sdk.ParaMsg, height int64, watcher sdk.IWatcher, msgs []sdk.Msg, para *parallelTxManager, feeSpiltInfo *sdk.FeeSplitInfo) *executeResult {
rwSet := para.chainMpCache.GetRWSet()
if ms != nil {
ms.GetRWSet(rwSet)
}
para.blockMpCache.PutRwSet(rwSet)
if feeSpiltInfo == nil {
feeSpiltInfo = &sdk.FeeSplitInfo{}
}
ans := &executeResult{
resp: r,
ms: ms,
msIsNil: ms == nil,
counter: counter,
paraMsg: paraMsg,
blockHeight: height,
watcher: watcher,
msgs: msgs,
rwSet: rwSet,
FeeSpiltInfo: feeSpiltInfo,
}
if paraMsg == nil {
ans.paraMsg = &sdk.ParaMsg{}
}
return ans
}
type parallelTxManager struct {
blockHeight int64
groupTasks []*groupTask
blockGasMeterMu sync.Mutex
isAsyncDeliverTx bool
txs [][]byte
txSize int
alreadyEnd bool
cosmosTxIndexInBlock int
txByteMpCMIndexLock sync.RWMutex
txByteMpCosmosIndex map[string]int
txIndexMpUpdateTXCounter []bool
haveAnteErrTx bool
resultCh chan int
resultCb func(data int)
stop chan struct{}
groupList map[int][]int
nextTxInGroup map[int]int
preTxInGroup map[int]int
txIndexWithGroup map[int]int
currentRerunIndex int
upComingTxIndex int
currTxFee sdk.Coins
cms sdk.CacheMultiStore
conflictCheck types.MsRWSet
blockMpCache *cacheRWSetList
chainMpCache *cacheRWSetList
blockMultiStores *cacheMultiStoreList
chainMultiStores *cacheMultiStoreList
extraTxsInfo []*extraDataForTx
txReps []*executeResult
finalResult []*executeResult
deliverTxs []*abci.ResponseDeliverTx
}
func (pm *parallelTxManager) putResult(txIndex int, res *executeResult) {
if pm.alreadyEnd {
return
}
pm.txReps[txIndex] = res
if res != nil {
pm.resultCh <- txIndex
}
}
func (pm *parallelTxManager) getTxResult(txIndex int) *executeResult {
if pm.alreadyEnd {
return nil
}
return pm.txReps[txIndex]
}
func (pm *parallelTxManager) StartResultHandle() {
go func() {
for {
select {
case exec := <-pm.resultCh:
pm.resultCb(exec)
case <-pm.stop:
return
}
}
}()
}
type groupTask struct {
addMultiCache func(msAnte types.CacheMultiStore, msCache types.CacheMultiStore)
mu sync.Mutex
groupIndex map[int]int
nextTx func(int) (int, bool)
taskRun func(int) *executeResult
putResult func(index int, txResult *executeResult)
txChan chan int
reRunChan chan int
stopChan chan struct{}
ms sdk.CacheMultiStore
}
func newGroupTask(txSizeInGroup int, addMultiCache func(msAnte types.CacheMultiStore, msCache types.CacheMultiStore), nextTx func(int2 int) (int, bool), task func(int2 int) *executeResult, putResult func(index int, txResult *executeResult)) *groupTask {
g := &groupTask{
addMultiCache: addMultiCache,
mu: sync.Mutex{},
nextTx: nextTx,
taskRun: task,
txChan: make(chan int, txSizeInGroup),
reRunChan: make(chan int, 1000),
stopChan: make(chan struct{}, 1),
putResult: putResult,
}
go g.run()
return g
}
func (g *groupTask) addTask(txIndex int) {
g.txChan <- txIndex
}
func (g *groupTask) addRerun(txIndex int) {
g.mu.Lock()
defer g.mu.Unlock()
g.clearResultChan(txIndex)
g.reRunChan <- txIndex
}
func (g *groupTask) clearResultChan(rerunIndex int) {
for true {
next, ok := g.nextTx(rerunIndex) // TODO add currIndex
if ok {
g.putResult(next, nil)
} else {
return
}
rerunIndex = next
}
}
func (g *groupTask) run() {
for true {
select {
case txIndex := <-g.txChan:
g.mu.Lock()
res := g.taskRun(txIndex)
if res.paraMsg.UseCurrentState {
g.addMultiCache(g.ms, nil)
g.ms = res.ms.CacheMultiStore()
} else {
if res.ms != nil {
res.ms.Write()
}
}
if len(g.reRunChan) == 0 {
g.putResult(int(res.counter), res)
if n, ok := g.nextTx(txIndex); ok {
g.addTask(n)
}
}
g.mu.Unlock()
case rerunIndex := <-g.reRunChan:
g.clearResultChan(rerunIndex)
g.addMultiCache(g.ms, nil)
g.ms = nil
size := len(g.txChan)
for index := 0; index < size; index++ {
<-g.txChan
}
if n, ok := g.nextTx(rerunIndex); ok {
g.addTask(n)
}
case <-g.stopChan:
return
}
}
}
func newParallelTxManager() *parallelTxManager {
isAsync := sm.DeliverTxsExecMode(viper.GetInt(sm.FlagDeliverTxsExecMode)) == sm.DeliverTxsExecModeParallel
para := ¶llelTxManager{
blockGasMeterMu: sync.Mutex{},
isAsyncDeliverTx: isAsync,
stop: make(chan struct{}, 1),
conflictCheck: make(types.MsRWSet),
groupList: make(map[int][]int),
nextTxInGroup: make(map[int]int),
preTxInGroup: make(map[int]int),
txIndexWithGroup: make(map[int]int),
resultCh: make(chan int, maxTxResultInChan),
txByteMpCMIndexLock: sync.RWMutex{},
blockMpCache: newCacheRWSetList(),
chainMpCache: newCacheRWSetList(),
blockMultiStores: newCacheMultiStoreList(),
chainMultiStores: newCacheMultiStoreList(),
}
return para
}
func (pm *parallelTxManager) addMultiCache(ms1 types.CacheMultiStore, ms2 types.CacheMultiStore) {
if ms1 != nil {
pm.blockMultiStores.PushStore(ms1)
}
if ms2 != nil {
pm.blockMultiStores.PushStore(ms2)
}
}
func shouldCleanChainCache(height int64) bool {
return height%multiCacheListClearInterval == 0
}
func (pm *parallelTxManager) addMpCacheToChainCache() {
if shouldCleanChainCache(pm.blockHeight) {
pm.chainMpCache.Clear()
} else {
jobChan := make(chan types.MsRWSet, pm.blockMpCache.Len())
go func() {
for index := 0; index < maxGoroutineNumberInParaTx; index++ {
go func(ch chan types.MsRWSet) {
for j := range ch {
types.ClearMsRWSet(j)
pm.chainMpCache.PutRwSet(j)
}
}(jobChan)
}
}()
pm.blockMpCache.Range(func(c types.MsRWSet) {
jobChan <- c
})
close(jobChan)
}
pm.blockMpCache.Clear()
}
func (pm *parallelTxManager) addBlockCacheToChainCache() {
if shouldCleanChainCache(pm.blockHeight) {
pm.chainMultiStores.Clear()
} else {
jobChan := make(chan types.CacheMultiStore, pm.blockMultiStores.Len())
go func() {
for index := 0; index < maxGoroutineNumberInParaTx; index++ {
go func(ch chan types.CacheMultiStore) {
for j := range ch {
j.Clear()
pm.chainMultiStores.PushStore(j)
}
}(jobChan)
}
}()
pm.blockMultiStores.Range(func(c types.CacheMultiStore) {
jobChan <- c
})
close(jobChan)
}
pm.blockMultiStores.Clear()
}
var (
wasmTxCountKey, _ = hex.DecodeString("08")
)
func (pm *parallelTxManager) isConflict(e *executeResult) bool {
if e.msIsNil {
return true //TODO fix later
}
if e.paraMsg.InvalidExecute {
return true
}
for storeKey, rw := range e.rwSet {
delete(rw.Read, string(feeAccountKeyInStore))
delete(rw.Read, string(wasmTxCountKey))
for key, value := range rw.Read {
if data, ok := pm.conflictCheck[storeKey].Write[key]; ok {
if !bytes.Equal(data.Value, value) {
return true
}
}
}
}
return false
}
func (pm *parallelTxManager) clear() {
pm.addBlockCacheToChainCache()
pm.addMpCacheToChainCache()
for key := range pm.groupList {
delete(pm.groupList, key)
}
for key := range pm.preTxInGroup {
delete(pm.preTxInGroup, key)
}
for key := range pm.txIndexWithGroup {
delete(pm.txIndexWithGroup, key)
}
for _, v := range pm.conflictCheck {
for k := range v.Read {
delete(v.Read, k)
}
for k := range v.Write {
delete(v.Write, k)
}
}
}
func (pm *parallelTxManager) init(txs [][]byte, blockHeight int64, deliverStateMs sdk.CacheMultiStore) {
txSize := len(txs)
pm.blockHeight = blockHeight
pm.groupTasks = make([]*groupTask, 0)
pm.isAsyncDeliverTx = true
pm.txs = txs
pm.txSize = txSize
pm.alreadyEnd = false
pm.currentRerunIndex = -1
pm.upComingTxIndex = 0
pm.currTxFee = sdk.Coins{}
pm.cms = deliverStateMs.CacheMultiStore()
pm.cms.DisableCacheReadList()
deliverStateMs.DisableCacheReadList()
if txSize > cap(pm.resultCh) {
pm.resultCh = make(chan int, txSize)
}
// clear resultCh when init a new block
for len(pm.resultCh) > 0 {
<-pm.resultCh
}
pm.txByteMpCosmosIndex = make(map[string]int, 0)
pm.nextTxInGroup = make(map[int]int)
pm.haveAnteErrTx = false
pm.txIndexMpUpdateTXCounter = make([]bool, txSize)
pm.extraTxsInfo = make([]*extraDataForTx, txSize)
pm.txReps = make([]*executeResult, txSize)
pm.finalResult = make([]*executeResult, txSize)
pm.deliverTxs = make([]*abci.ResponseDeliverTx, txSize)
}
func (pm *parallelTxManager) getParentMsByTxIndex(txIndex int) (sdk.CacheMultiStore, bool) {
if txIndex <= pm.upComingTxIndex-1 {
return nil, false
}
useCurrent := false
var ms types.CacheMultiStore
if pm.currentRerunIndex != txIndex && pm.preTxInGroup[txIndex] > pm.upComingTxIndex-1 {
if groupMs := pm.groupTasks[pm.txIndexWithGroup[txIndex]].ms; groupMs != nil {
ms = pm.chainMultiStores.GetStoreWithParent(groupMs)
}
}
if ms == nil {
useCurrent = true
ms = pm.chainMultiStores.GetStoreWithParent(pm.cms)
}
return ms, useCurrent
}
func (pm *parallelTxManager) SetCurrentIndexRes(txIndex int, res *executeResult) {
if res.msIsNil {
return
}
for storeKey, rw := range res.rwSet {
if _, ok := pm.conflictCheck[storeKey]; !ok {
pm.conflictCheck[storeKey] = types.NewCacheKvRWSet()
}
ms := pm.cms.GetKVStore(storeKey)
for key, value := range rw.Write {
if value.Deleted {
ms.Delete([]byte(key))
} else {
ms.Set([]byte(key), value.Value)
}
pm.conflictCheck[storeKey].Write[key] = value
}
}
}
func (pm *parallelTxManager) NeedUpdateTXCounter() bool {
res := false
for _, v := range pm.txIndexMpUpdateTXCounter {
res = res || v
}
return res
}
// When an AnteErr tx is encountered, this tx will be discarded,
// and the cosmosIndex of the remaining tx needs to be corrected.
func (pm *parallelTxManager) handleAnteErrTx(curTxNeedUpdateTXCounter bool) {
pm.haveAnteErrTx = true
pm.txIndexMpUpdateTXCounter[pm.upComingTxIndex] = false
if curTxNeedUpdateTXCounter {
pm.cosmosTxIndexInBlock--
pm.txByteMpCMIndexLock.Lock()
for index, tx := range pm.txs {
if _, ok := pm.txByteMpCosmosIndex[string(tx)]; ok && index > pm.upComingTxIndex {
pm.txByteMpCosmosIndex[string(tx)]--
}
}
pm.txByteMpCMIndexLock.Unlock()
}
}