-
Notifications
You must be signed in to change notification settings - Fork 182
/
execution.go
739 lines (629 loc) · 22.9 KB
/
execution.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
package state
import (
"fmt"
"github.com/okex/exchain/libs/system/trace"
"strconv"
"time"
abci "github.com/okex/exchain/libs/tendermint/abci/types"
cfg "github.com/okex/exchain/libs/tendermint/config"
"github.com/okex/exchain/libs/tendermint/global"
"github.com/okex/exchain/libs/tendermint/libs/automation"
"github.com/okex/exchain/libs/tendermint/libs/fail"
"github.com/okex/exchain/libs/tendermint/libs/log"
mempl "github.com/okex/exchain/libs/tendermint/mempool"
"github.com/okex/exchain/libs/tendermint/proxy"
"github.com/okex/exchain/libs/tendermint/types"
dbm "github.com/okex/exchain/libs/tm-db"
"github.com/tendermint/go-amino"
)
//-----------------------------------------------------------------------------
type (
// Enum mode for executing [deliverTx, ...]
DeliverTxsExecMode int
)
const (
DeliverTxsExecModeSerial DeliverTxsExecMode = iota // execute [deliverTx,...] sequentially
DeliverTxsExecModePartConcurrent // execute [deliverTx,...] partially-concurrent
DeliverTxsExecModeParallel // execute [deliverTx,...] parallel
// There are three modes.
// 0: execute [deliverTx,...] sequentially (default)
// 1: execute [deliverTx,...] partially-concurrent
// 2: execute [deliverTx,...] parallel
FlagDeliverTxsExecMode = "deliver-txs-mode"
FlagDeliverTxsConcurrentNum = "deliver-txs-concurrent-num"
)
// BlockExecutor handles block execution and state updates.
// It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
// then commits and updates the mempool atomically, then saves state.
// BlockExecutor provides the context and accessories for properly executing a block.
type BlockExecutor struct {
// save state, validators, consensus params, abci responses here
db dbm.DB
// execute the app against this
proxyApp proxy.AppConnConsensus
// events
eventBus types.BlockEventPublisher
// manage the mempool lock during commit
// and update both with block results after commit.
mempool mempl.Mempool
evpool EvidencePool
logger log.Logger
metrics *Metrics
// download or upload data to dds
deltaContext *DeltaContext
prerunCtx *prerunContext
isFastSync bool
// async save state, validators, consensus params, abci responses here
asyncDBContext
// the owner is validator
isNullIndexer bool
eventsChan chan event
}
type event struct {
block *types.Block
abciRsp *ABCIResponses
vals []*types.Validator
}
type BlockExecutorOption func(executor *BlockExecutor)
func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
return func(blockExec *BlockExecutor) {
blockExec.metrics = metrics
}
}
// NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
// Call SetEventBus to provide one.
func NewBlockExecutor(
db dbm.DB,
logger log.Logger,
proxyApp proxy.AppConnConsensus,
mempool mempl.Mempool,
evpool EvidencePool,
options ...BlockExecutorOption,
) *BlockExecutor {
res := &BlockExecutor{
db: db,
proxyApp: proxyApp,
eventBus: types.NopEventBus{},
mempool: mempool,
evpool: evpool,
logger: logger,
metrics: NopMetrics(),
prerunCtx: newPrerunContex(logger),
deltaContext: newDeltaContext(logger),
eventsChan: make(chan event, 5),
}
for _, option := range options {
option(res)
}
automation.LoadTestCase(logger)
res.deltaContext.init()
res.initAsyncDBContext()
go res.fireEventsRountine()
return res
}
func (blockExec *BlockExecutor) fireEventsRountine() {
for et := range blockExec.eventsChan {
if et.block == nil {
break
}
fireEvents(blockExec.logger, blockExec.eventBus, et.block, et.abciRsp, et.vals)
}
}
func (blockExec *BlockExecutor) DB() dbm.DB {
return blockExec.db
}
func (blockExec *BlockExecutor) SetIsFastSyncing(isSyncing bool) {
blockExec.isFastSync = isSyncing
}
func (blockExec *BlockExecutor) SetIsNullIndexer(isNullIndexer bool) {
blockExec.isNullIndexer = isNullIndexer
}
func (blockExec *BlockExecutor) Stop() {
blockExec.stopAsyncDBContext()
}
// SetEventBus - sets the event bus for publishing block related events.
// If not called, it defaults to types.NopEventBus.
func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
blockExec.eventBus = eventBus
blockExec.mempool.SetEventBus(eventBus)
}
// CreateProposalBlock calls state.MakeBlock with evidence from the evpool
// and txs from the mempool. The max bytes must be big enough to fit the commit.
// Up to 1/10th of the block space is allcoated for maximum sized evidence.
// The rest is given to txs, up to the max gas.
func (blockExec *BlockExecutor) CreateProposalBlock(
height int64,
state State, commit *types.Commit,
proposerAddr []byte,
) (*types.Block, *types.PartSet) {
maxBytes := state.ConsensusParams.Block.MaxBytes
maxGas := state.ConsensusParams.Block.MaxGas
// Fetch a limited amount of valid evidence
maxNumEvidence, _ := types.MaxEvidencePerBlock(maxBytes)
evidence := blockExec.evpool.PendingEvidence(maxNumEvidence)
// Fetch a limited amount of valid txs
maxDataBytes := types.MaxDataBytes(maxBytes, state.Validators.Size(), len(evidence))
if cfg.DynamicConfig.GetMaxGasUsedPerBlock() > -1 {
maxGas = cfg.DynamicConfig.GetMaxGasUsedPerBlock()
}
txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
return state.MakeBlock(height, txs, commit, evidence, proposerAddr)
}
// ValidateBlock validates the given block against the given state.
// If the block is invalid, it returns an error.
// Validation does not mutate state, but does require historical information from the stateDB,
// ie. to verify evidence from a validator at an old height.
func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
if IgnoreSmbCheck {
// debug only
return nil
}
return validateBlock(blockExec.evpool, blockExec.db, state, block)
}
// ApplyBlock validates the block against the state, executes it against the app,
// fires the relevant events, commits the app, and saves the new state and responses.
// It returns the new state and the block height to retain (pruning older blocks).
// It's the only function that needs to be called
// from outside this package to process and commit an entire block.
// It takes a blockID to avoid recomputing the parts hash.
func (blockExec *BlockExecutor) ApplyBlock(
state State, blockID types.BlockID, block *types.Block) (State, int64, error) {
if ApplyBlockPprofTime >= 0 {
f, t := PprofStart()
defer PprofEnd(int(block.Height), f, t)
}
trc := trace.NewTracer(trace.ApplyBlock)
trc.EnableSummary()
dc := blockExec.deltaContext
defer func() {
trace.GetElapsedInfo().AddInfo(trace.Height, strconv.FormatInt(block.Height, 10))
trace.GetElapsedInfo().AddInfo(trace.Tx, strconv.Itoa(len(block.Data.Txs)))
trace.GetElapsedInfo().AddInfo(trace.BlockSize, strconv.Itoa(block.FastSize()))
trace.GetElapsedInfo().AddInfo(trace.RunTx, trc.Format())
trace.GetElapsedInfo().SetElapsedTime(trc.GetElapsedTime())
now := time.Now().UnixNano()
blockExec.metrics.IntervalTime.Set(float64(now-blockExec.metrics.lastBlockTime) / 1e6)
blockExec.metrics.lastBlockTime = now
}()
if err := blockExec.ValidateBlock(state, block); err != nil {
return state, 0, ErrInvalidBlock(err)
}
deltaInfo := dc.prepareStateDelta(block.Height)
trc.Pin(trace.Abci)
startTime := time.Now().UnixNano()
//wait till the last block async write be saved
blockExec.tryWaitLastBlockSave(block.Height - 1)
abciResponses, err := blockExec.runAbci(block, deltaInfo)
if err != nil {
return state, 0, ErrProxyAppConn(err)
}
fail.Fail() // XXX
trc.Pin(trace.SaveResp)
// Save the results before we commit.
blockExec.trySaveABCIResponsesAsync(block.Height, abciResponses)
fail.Fail() // XXX
endTime := time.Now().UnixNano()
blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1e6)
blockExec.metrics.AbciTime.Set(float64(endTime-startTime) / 1e6)
// validate the validator updates and convert to tendermint types
abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
if err != nil {
return state, 0, fmt.Errorf("error in validator updates: %v", err)
}
validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
if err != nil {
return state, 0, err
}
if len(validatorUpdates) > 0 {
blockExec.logger.Info("Updates to validators", "updates", types.ValidatorListString(validatorUpdates))
}
// Update the state with the block and responses.
state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
if err != nil {
return state, 0, fmt.Errorf("commit failed for application: %v", err)
}
trc.Pin(trace.Persist)
startTime = time.Now().UnixNano()
// Lock mempool, commit app state, update mempoool.
commitResp, retainHeight, err := blockExec.commit(state, block, deltaInfo, abciResponses.DeliverTxs)
endTime = time.Now().UnixNano()
blockExec.metrics.CommitTime.Set(float64(endTime-startTime) / 1e6)
if err != nil {
return state, 0, fmt.Errorf("commit failed for application: %v", err)
}
global.SetGlobalHeight(block.Height)
// Update evpool with the block and state.
blockExec.evpool.Update(block, state)
fail.Fail() // XXX
trc.Pin(trace.SaveState)
// Update the app hash and save the state.
state.AppHash = commitResp.Data
blockExec.trySaveStateAsync(state)
blockExec.logger.Debug("SaveState", "state", &state)
fail.Fail() // XXX
// Events are fired after everything else.
// NOTE: if we crash between Commit and Save, events wont be fired during replay
if !blockExec.isNullIndexer {
blockExec.eventsChan <- event{
block: block,
abciRsp: abciResponses,
vals: validatorUpdates,
}
}
dc.postApplyBlock(block.Height, deltaInfo, abciResponses, commitResp.DeltaMap, blockExec.isFastSync)
return state, retainHeight, nil
}
func (blockExec *BlockExecutor) ApplyBlockWithTrace(
state State, blockID types.BlockID, block *types.Block) (State, int64, error) {
s, id, err := blockExec.ApplyBlock(state, blockID, block)
trace.GetElapsedInfo().Dump(blockExec.logger.With("module", "main"))
return s, id, err
}
func (blockExec *BlockExecutor) runAbci(block *types.Block, deltaInfo *DeltaInfo) (*ABCIResponses, error) {
var abciResponses *ABCIResponses
var err error
if deltaInfo != nil {
blockExec.logger.Info("Apply delta", "height", block.Height, "deltas-length", deltaInfo.deltaLen)
execBlockOnProxyAppWithDeltas(blockExec.proxyApp, block, blockExec.db)
abciResponses = deltaInfo.abciResponses
} else {
pc := blockExec.prerunCtx
if pc.prerunTx {
abciResponses, err = pc.getPrerunResult(block.Height, blockExec.isFastSync)
}
if abciResponses == nil {
ctx := &executionTask{
logger: blockExec.logger,
block: block,
db: blockExec.db,
proxyApp: blockExec.proxyApp,
}
mode := DeliverTxsExecMode(cfg.DynamicConfig.GetDeliverTxsExecuteMode())
switch mode {
case DeliverTxsExecModeSerial:
abciResponses, err = execBlockOnProxyApp(ctx)
case DeliverTxsExecModePartConcurrent:
abciResponses, err = execBlockOnProxyAppPartConcurrent(blockExec.logger, blockExec.proxyApp, block, blockExec.db)
case DeliverTxsExecModeParallel:
abciResponses, err = execBlockOnProxyAppAsync(blockExec.logger, blockExec.proxyApp, block, blockExec.db)
default:
abciResponses, err = execBlockOnProxyApp(ctx)
}
}
}
return abciResponses, err
}
// Commit locks the mempool, runs the ABCI Commit message, and updates the
// mempool.
// It returns the result of calling abci.Commit (the AppHash) and the height to retain (if any).
// The Mempool must be locked during commit and update because state is
// typically reset on Commit and old txs must be replayed against committed
// state before new txs are run in the mempool, lest they be invalid.
func (blockExec *BlockExecutor) commit(
state State,
block *types.Block,
deltaInfo *DeltaInfo,
deliverTxResponses []*abci.ResponseDeliverTx,
) (*abci.ResponseCommit, int64, error) {
blockExec.mempool.Lock()
defer func() {
blockExec.mempool.Unlock()
// Forced flushing mempool
if cfg.DynamicConfig.GetMempoolFlush() {
blockExec.mempool.Flush()
}
}()
// while mempool is Locked, flush to ensure all async requests have completed
// in the ABCI app before Commit.
err := blockExec.mempool.FlushAppConn()
if err != nil {
blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
return nil, 0, err
}
// Commit block, get hash back
var treeDeltaMap interface{}
if deltaInfo != nil {
treeDeltaMap = deltaInfo.treeDeltaMap
}
res, err := blockExec.proxyApp.CommitSync(abci.RequestCommit{DeltaMap: treeDeltaMap})
if err != nil {
blockExec.logger.Error(
"Client error during proxyAppConn.CommitSync",
"err", err,
)
return nil, 0, err
}
// ResponseCommit has no error code - just data
blockExec.logger.Debug(
"Committed state",
"height", block.Height,
"txs", len(block.Txs),
"appHash", amino.BytesHexStringer(res.Data),
"blockLen", amino.FuncStringer(func() string { return strconv.Itoa(block.FastSize()) }),
)
// Update mempool.
err = blockExec.mempool.Update(
block.Height,
block.Txs,
deliverTxResponses,
TxPreCheck(state),
TxPostCheck(state),
)
if !cfg.DynamicConfig.GetMempoolRecheck() && block.Height%cfg.DynamicConfig.GetMempoolForceRecheckGap() == 0 {
proxyCb := func(req *abci.Request, res *abci.Response) {
}
blockExec.proxyApp.SetResponseCallback(proxyCb)
// reset checkState
blockExec.proxyApp.SetOptionAsync(abci.RequestSetOption{
Key: "ResetCheckState",
})
}
return res, res.RetainHeight, err
}
func transTxsToBytes(txs types.Txs) [][]byte {
ret := make([][]byte, 0)
for _, v := range txs {
ret = append(ret, v)
}
return ret
}
//---------------------------------------------------------
// Helper functions for executing blocks and updating state
// Executes block's transactions on proxyAppConn.
// Returns a list of transaction results and updates to the validator set
func execBlockOnProxyApp(context *executionTask) (*ABCIResponses, error) {
block := context.block
proxyAppConn := context.proxyApp
stateDB := context.db
logger := context.logger
var validTxs, invalidTxs = 0, 0
txIndex := 0
abciResponses := NewABCIResponses(block)
// Execute transactions and get hash.
proxyCb := func(req *abci.Request, res *abci.Response) {
if r, ok := res.Value.(*abci.Response_DeliverTx); ok {
// TODO: make use of res.Log
// TODO: make use of this info
// Blocks may include invalid txs.
txRes := r.DeliverTx
if txRes.Code == abci.CodeTypeOK {
validTxs++
} else {
logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log, "index", txIndex)
invalidTxs++
}
abciResponses.DeliverTxs[txIndex] = txRes
txIndex++
}
}
proxyAppConn.SetResponseCallback(proxyCb)
// proxyAppConn.ParallelTxs(transTxsToBytes(block.Txs), true)
commitInfo, byzVals := getBeginBlockValidatorInfo(block, stateDB)
// Begin block
var err error
abciResponses.BeginBlock, err = proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
Hash: block.Hash(),
Header: types.TM2PB.Header(&block.Header),
LastCommitInfo: commitInfo,
ByzantineValidators: byzVals,
})
if err != nil {
logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
return nil, err
}
realTxCh := make(chan abci.TxEssentials, len(block.Txs))
stopedCh := make(chan struct{}, 1)
go preDeliverRoutine(proxyAppConn, block.Txs, realTxCh, stopedCh)
count := 0
for realTx := range realTxCh {
if realTx != nil {
proxyAppConn.DeliverRealTxAsync(realTx)
} else {
proxyAppConn.DeliverTxAsync(abci.RequestDeliverTx{Tx: block.Txs[count]})
}
if err = proxyAppConn.Error(); err != nil {
return nil, err
}
if context != nil && context.stopped {
stopedCh <- struct{}{}
close(stopedCh)
context.dump(fmt.Sprintf("Prerun stopped, %d/%d tx executed", count+1, len(block.Txs)))
return nil, fmt.Errorf("Prerun stopped")
}
count += 1
}
close(stopedCh)
// End block.
abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{Height: block.Height})
if err != nil {
logger.Error("Error in proxyAppConn.EndBlock", "err", err)
return nil, err
}
trace.GetElapsedInfo().AddInfo(trace.InvalidTxs, fmt.Sprintf("%d", invalidTxs))
return abciResponses, nil
}
func preDeliverRoutine(proxyAppConn proxy.AppConnConsensus, txs types.Txs, realTxCh chan<- abci.TxEssentials, stopedCh <-chan struct{}) {
for _, tx := range txs {
realTx := proxyAppConn.PreDeliverRealTxAsync(tx)
select {
case realTxCh <- realTx:
case <-stopedCh:
close(realTxCh)
return
}
}
close(realTxCh)
}
func execBlockOnProxyAppWithDeltas(
proxyAppConn proxy.AppConnConsensus,
block *types.Block,
stateDB dbm.DB,
) {
proxyCb := func(req *abci.Request, res *abci.Response) {
}
proxyAppConn.SetResponseCallback(proxyCb)
commitInfo, byzVals := getBeginBlockValidatorInfo(block, stateDB)
_, _ = proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
Hash: block.Hash(),
Header: types.TM2PB.Header(&block.Header),
LastCommitInfo: commitInfo,
ByzantineValidators: byzVals,
})
}
func getBeginBlockValidatorInfo(block *types.Block, stateDB dbm.DB) (abci.LastCommitInfo, []abci.Evidence) {
voteInfos := make([]abci.VoteInfo, block.LastCommit.Size())
// block.Height=1 -> LastCommitInfo.Votes are empty.
// Remember that the first LastCommit is intentionally empty, so it makes
// sense for LastCommitInfo.Votes to also be empty.
if block.Height > types.GetStartBlockHeight()+1 {
lastValSet, err := LoadValidators(stateDB, block.Height-1)
if err != nil {
panic(err)
}
// Sanity check that commit size matches validator set size - only applies
// after first block.
var (
commitSize = block.LastCommit.Size()
valSetLen = len(lastValSet.Validators)
)
if commitSize != valSetLen {
panic(fmt.Sprintf("commit size (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
commitSize, valSetLen, block.Height, block.LastCommit.Signatures, lastValSet.Validators))
}
for i, val := range lastValSet.Validators {
commitSig := block.LastCommit.Signatures[i]
voteInfos[i] = abci.VoteInfo{
Validator: types.TM2PB.Validator(val),
SignedLastBlock: !commitSig.Absent(),
}
}
}
byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
for i, ev := range block.Evidence.Evidence {
// We need the validator set. We already did this in validateBlock.
// TODO: Should we instead cache the valset in the evidence itself and add
// `SetValidatorSet()` and `ToABCI` methods ?
valset, err := LoadValidators(stateDB, ev.Height())
if err != nil {
panic(err)
}
byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
}
return abci.LastCommitInfo{
Round: int32(block.LastCommit.Round),
Votes: voteInfos,
}, byzVals
}
func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
params types.ValidatorParams) error {
for _, valUpdate := range abciUpdates {
if valUpdate.GetPower() < 0 {
return fmt.Errorf("voting power can't be negative %v", valUpdate)
} else if valUpdate.GetPower() == 0 {
// continue, since this is deleting the validator, and thus there is no
// pubkey to check
continue
}
// Check if validator's pubkey matches an ABCI type in the consensus params
thisKeyType := valUpdate.PubKey.Type
if !params.IsValidPubkeyType(thisKeyType) {
return fmt.Errorf("validator %v is using pubkey %s, which is unsupported for consensus",
valUpdate, thisKeyType)
}
}
return nil
}
// updateState returns a new State updated according to the header and responses.
func updateState(
state State,
blockID types.BlockID,
header *types.Header,
abciResponses *ABCIResponses,
validatorUpdates []*types.Validator,
) (State, error) {
// Copy the valset so we can apply changes from EndBlock
// and update s.LastValidators and s.Validators.
nValSet := state.NextValidators.Copy()
// Update the validator set with the latest abciResponses.
lastHeightValsChanged := state.LastHeightValidatorsChanged
if len(validatorUpdates) > 0 {
err := nValSet.UpdateWithChangeSet(validatorUpdates)
if err != nil {
return state, fmt.Errorf("error changing validator set: %v", err)
}
// Change results from this height but only applies to the next next height.
lastHeightValsChanged = header.Height + 1 + 1
}
// Update validator proposer priority and set state variables.
nValSet.IncrementProposerPriority(1)
// Update the params with the latest abciResponses.
nextParams := state.ConsensusParams
lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
if abciResponses.EndBlock.ConsensusParamUpdates != nil {
// NOTE: must not mutate s.ConsensusParams
nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
err := nextParams.Validate()
if err != nil {
return state, fmt.Errorf("error updating consensus params: %v", err)
}
// Change results from this height but only applies to the next height.
lastHeightParamsChanged = header.Height + 1
}
// TODO: allow app to upgrade version
nextVersion := state.Version
if types.HigherThanVenus1(header.Height) && !state.Version.IsUpgraded() {
nextVersion = state.Version.UpgradeToIBCVersion()
}
// NOTE: the AppHash has not been populated.
// It will be filled on state.Save.
return State{
Version: nextVersion,
ChainID: state.ChainID,
LastBlockHeight: header.Height,
LastBlockID: blockID,
LastBlockTime: header.Time,
NextValidators: nValSet,
Validators: state.NextValidators.Copy(),
LastValidators: state.Validators.Copy(),
LastHeightValidatorsChanged: lastHeightValsChanged,
ConsensusParams: nextParams,
LastHeightConsensusParamsChanged: lastHeightParamsChanged,
LastResultsHash: abciResponses.ResultsHash(),
AppHash: nil,
}, nil
}
// Fire NewBlock, NewBlockHeader.
// Fire TxEvent for every tx.
// NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
func fireEvents(
logger log.Logger,
eventBus types.BlockEventPublisher,
block *types.Block,
abciResponses *ABCIResponses,
validatorUpdates []*types.Validator,
) {
eventBus.PublishEventNewBlock(types.EventDataNewBlock{
Block: block,
ResultBeginBlock: *abciResponses.BeginBlock,
ResultEndBlock: *abciResponses.EndBlock,
})
eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{
Header: block.Header,
NumTxs: int64(len(block.Txs)),
ResultBeginBlock: *abciResponses.BeginBlock,
ResultEndBlock: *abciResponses.EndBlock,
})
for i, tx := range block.Data.Txs {
eventBus.PublishEventTx(types.EventDataTx{TxResult: types.TxResult{
Height: block.Height,
Index: uint32(i),
Tx: tx,
Result: *(abciResponses.DeliverTxs[i]),
}})
}
if len(validatorUpdates) > 0 {
eventBus.PublishEventValidatorSetUpdates(
types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates})
}
}