Skip to content

Commit 2a01cbe

Browse files
authored
Merge pull request #6303 from oasisprotocol/peternose/trivial/refactor-code
go/consensus/cometbft: Refactor code and improve consistency
2 parents d681f4c + 5d1c3ea commit 2a01cbe

39 files changed

Lines changed: 370 additions & 313 deletions

File tree

.changelog/6303.trivial.md

Whitespace-only changes.

go/consensus/cometbft/abci/mux.go

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ type ApplicationConfig struct {
7575
ReadOnlyStorage bool
7676

7777
// InitialHeight is the height of the initial block.
78-
InitialHeight uint64
78+
InitialHeight int64
7979

8080
// ChainContext is the chain context for the network.
8181
ChainContext string
@@ -273,7 +273,7 @@ func (mux *abciMux) registerHaltHook(hook api.HaltHook) {
273273
func (mux *abciMux) Info(types.RequestInfo) types.ResponseInfo {
274274
return types.ResponseInfo{
275275
AppVersion: version.CometBFTAppVersion,
276-
LastBlockHeight: mux.state.BlockHeight(),
276+
LastBlockHeight: mux.state.LastHeight(),
277277
LastBlockAppHash: mux.state.StateRootHash(),
278278
}
279279
}
@@ -298,7 +298,7 @@ func (mux *abciMux) InitChain(req types.RequestInitChain) types.ResponseInitChai
298298
})
299299
mux.state.blockLock.Unlock()
300300

301-
if st.Height != req.InitialHeight || uint64(st.Height) != mux.state.initialHeight {
301+
if st.Height != req.InitialHeight || st.Height != mux.state.initialHeight {
302302
panic(fmt.Errorf("mux: inconsistent initial height (genesis: %d abci: %d state: %d)", st.Height, req.InitialHeight, mux.state.initialHeight))
303303
}
304304

@@ -570,12 +570,12 @@ func (mux *abciMux) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginB
570570
return *mux.state.proposal.resultsBeginBlock
571571
}
572572

573-
blockHeight := mux.state.BlockHeight()
573+
lastHeight := mux.state.LastHeight()
574574

575575
mux.logger.Debug("BeginBlock",
576576
"req", req,
577577
"hash", hex.EncodeToString(req.Hash),
578-
"block_height", blockHeight,
578+
"height", lastHeight,
579579
)
580580

581581
params := mux.state.ConsensusParameters()
@@ -607,20 +607,20 @@ func (mux *abciMux) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginB
607607
// checks must run on each block to make sure that any pending upgrade descriptors are cleared
608608
// after consensus upgrade is performed.
609609
if upgrader := mux.state.Upgrader(); upgrader != nil {
610-
switch err := upgrader.ConsensusUpgrade(ctx, currentEpoch, blockHeight); err {
610+
switch err := upgrader.ConsensusUpgrade(ctx, currentEpoch, lastHeight); err {
611611
case nil:
612612
// Everything ok.
613613
case upgrade.ErrStopForUpgrade:
614614
// Signal graceful stop for upgrade.
615-
mux.haltForUpgrade(blockHeight, currentEpoch, true)
615+
mux.haltForUpgrade(lastHeight, currentEpoch, true)
616616
default:
617617
panic(fmt.Errorf("mux: error while trying to perform consensus upgrade: %w", err))
618618
}
619619
}
620620

621621
// Check if we need to halt based on local configuration.
622-
if mux.state.shouldLocalHalt(blockHeight+1, currentEpoch) {
623-
mux.haltForUpgrade(blockHeight, currentEpoch, true)
622+
if mux.state.shouldLocalHalt(lastHeight+1, currentEpoch) {
623+
mux.haltForUpgrade(lastHeight, currentEpoch, true)
624624
}
625625

626626
// Dispatch BeginBlock to all applications.
@@ -632,7 +632,7 @@ func (mux *abciMux) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginB
632632
)
633633

634634
if errors.Is(err, upgrade.ErrStopForUpgrade) {
635-
mux.haltForUpgrade(blockHeight, currentEpoch, true)
635+
mux.haltForUpgrade(lastHeight, currentEpoch, true)
636636
}
637637
panic(fmt.Errorf("mux: BeginBlock: fatal error in application: '%s': %w", app.Name(), err))
638638
}
@@ -642,7 +642,7 @@ func (mux *abciMux) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginB
642642

643643
// During the first block, also collect and prepend application events generated during
644644
// InitChain to BeginBlock events.
645-
if mux.state.BlockHeight() == 0 {
645+
if mux.state.LastHeight() == 0 {
646646
response.Events = append(response.Events, mux.state.initEvents...)
647647
}
648648

@@ -761,7 +761,7 @@ func (mux *abciMux) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
761761

762762
mux.logger.Debug("EndBlock",
763763
"req", req,
764-
"block_height", mux.state.BlockHeight(),
764+
"height", mux.state.LastHeight(),
765765
)
766766

767767
ctx := mux.state.NewContext(api.ContextEndBlock)
@@ -790,7 +790,7 @@ func (mux *abciMux) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
790790
panic(fmt.Errorf("mux: can't get current epoch in BeginBlock: %w", err))
791791
}
792792

793-
err = upgrader.ConsensusUpgrade(ctx, currentEpoch, ctx.BlockHeight())
793+
err = upgrader.ConsensusUpgrade(ctx, currentEpoch, ctx.LastHeight())
794794
// This should never fail as all the checks were already performed in BeginBlock.
795795
if err != nil {
796796
panic(fmt.Errorf("mux: error while trying to perform consensus upgrade: %w", err))
@@ -829,7 +829,7 @@ func (mux *abciMux) Commit() types.ResponseCommit {
829829
}
830830

831831
mux.logger.Debug("Commit",
832-
"block_height", mux.state.BlockHeight(),
832+
"height", mux.state.LastHeight(),
833833
"state_root_hash", hex.EncodeToString(mux.state.StateRootHash()),
834834
"last_retained_version", lastRetainedVersion,
835835
)
@@ -936,7 +936,7 @@ func (mux *abciMux) checkDependencies() error {
936936
}
937937

938938
func (mux *abciMux) finishInitialization() error {
939-
if mux.state.BlockHeight() >= mux.state.InitialHeight() {
939+
if mux.state.LastHeight() >= mux.state.InitialHeight() {
940940
mux.state.resetProposal()
941941
defer mux.state.closeProposal()
942942

@@ -996,7 +996,7 @@ func newABCIMux(ctx context.Context, upgrader upgrade.Backend, cfg *ApplicationC
996996
mux.md.Subscribe(api.MessageExecuteSubcall, mux)
997997

998998
mux.logger.Debug("ABCI multiplexer initialized",
999-
"block_height", state.BlockHeight(),
999+
"height", state.LastHeight(),
10001000
"state_root_hash", hex.EncodeToString(state.StateRootHash()),
10011001
)
10021002

go/consensus/cometbft/abci/state.go

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ type applicationState struct {
129129
ctx context.Context
130130
cancelCtx context.CancelFunc
131131

132-
initialHeight uint64
132+
initialHeight int64
133133

134134
stateRoot storage.Root
135135
storage storage.LocalBackend
@@ -183,7 +183,7 @@ func (s *applicationState) NewContext(mode api.ContextMode) *api.Context {
183183
blockCtx *api.BlockContext
184184
state mkvs.OverlayTree
185185
)
186-
blockHeight := int64(s.stateRoot.Version)
186+
lastHeight := int64(s.stateRoot.Version)
187187
now := s.blockTime
188188
switch mode {
189189
case api.ContextInitChain:
@@ -193,7 +193,7 @@ func (s *applicationState) NewContext(mode api.ContextMode) *api.Context {
193193
s.initState = mkvs.NewOverlay(mkvs.New(nil, nil, storage.RootTypeState, mkvs.WithoutWriteLog()))
194194
state = s.initState
195195
// Configure block height so that current height will be correctly computed.
196-
blockHeight = int64(s.initialHeight) - 1
196+
lastHeight = s.initialHeight - 1
197197
case api.ContextCheckTx:
198198
state = mkvs.NewOverlayWrapper(s.checkState)
199199
case api.ContextDeliverTx, api.ContextBeginBlock, api.ContextEndBlock:
@@ -215,9 +215,9 @@ func (s *applicationState) NewContext(mode api.ContextMode) *api.Context {
215215
api.NewNopGasAccountant(),
216216
s,
217217
state,
218-
blockHeight,
219218
blockCtx,
220-
int64(s.initialHeight),
219+
lastHeight,
220+
s.initialHeight,
221221
)
222222
}
223223

@@ -234,25 +234,26 @@ func (s *applicationState) Checkpointer() checkpoint.Checkpointer {
234234
}
235235

236236
func (s *applicationState) InitialHeight() int64 {
237-
return int64(s.initialHeight)
237+
return s.initialHeight
238238
}
239239

240-
func (s *applicationState) BlockHeight() int64 {
240+
func (s *applicationState) LastHeight() int64 {
241241
s.blockLock.RLock()
242242
defer s.blockLock.RUnlock()
243243

244-
height := s.stateRoot.Version
244+
height := int64(s.stateRoot.Version)
245245
if height < s.initialHeight {
246246
height = 0
247247
}
248-
return int64(height)
248+
return height
249249
}
250250

251251
func (s *applicationState) StateRootHash() []byte {
252252
s.blockLock.RLock()
253253
defer s.blockLock.RUnlock()
254254

255-
if s.stateRoot.Version < s.initialHeight {
255+
height := int64(s.stateRoot.Version)
256+
if height < s.initialHeight {
256257
// CometBFT expects a nil hash when there is no state otherwise it will panic.
257258
return nil
258259
}
@@ -279,12 +280,12 @@ func (s *applicationState) GetEpoch(ctx context.Context, blockHeight int64) (bea
279280
}
280281

281282
func (s *applicationState) GetCurrentEpoch(ctx context.Context) (beacon.EpochTime, error) {
282-
blockHeight := s.BlockHeight()
283-
if blockHeight == 0 {
283+
lastHeight := s.LastHeight()
284+
if lastHeight == 0 {
284285
return beacon.EpochInvalid, nil
285286
}
286287

287-
latestHeight := blockHeight
288+
latestHeight := lastHeight
288289
if abciCtx := api.FromCtx(ctx); abciCtx != nil {
289290
// If request was made from an ABCI application context, then use blockHeight + 1, to fetch
290291
// the epoch at current (future) height. See cometbft/api.NewImmutableState for details.
@@ -297,23 +298,23 @@ func (s *applicationState) GetCurrentEpoch(ctx context.Context) (beacon.EpochTim
297298
if err != nil {
298299
return beacon.EpochInvalid, fmt.Errorf("failed to get future epoch for height %d: %w", latestHeight, err)
299300
}
300-
if future != nil && future.Height == blockHeight+1 {
301+
if future != nil && future.Height == lastHeight+1 {
301302
return future.Epoch, nil
302303
}
303304

304305
currentEpoch, err := s.timeSource.GetEpoch(ctx, latestHeight)
305306
if err != nil {
306-
return beacon.EpochInvalid, fmt.Errorf("failed to get epoch for height %d: %w", blockHeight+1, err)
307+
return beacon.EpochInvalid, fmt.Errorf("failed to get epoch for height %d: %w", lastHeight+1, err)
307308
}
308309
return currentEpoch, nil
309310
}
310311

311312
func (s *applicationState) EpochChanged(ctx *api.Context) (bool, beacon.EpochTime) {
312-
blockHeight := s.BlockHeight()
313-
if blockHeight == 0 {
313+
lastHeight := s.LastHeight()
314+
if lastHeight == 0 {
314315
return false, beacon.EpochInvalid
315316
}
316-
latestHeight := blockHeight
317+
latestHeight := lastHeight
317318
if abciCtx := api.FromCtx(ctx); abciCtx != nil {
318319
// If request was made from an ABCI application context, then use blockHeight + 1, to fetch
319320
// the epoch at current (future) height. See cometbft/api.NewImmutableState for details.
@@ -328,7 +329,7 @@ func (s *applicationState) EpochChanged(ctx *api.Context) (bool, beacon.EpochTim
328329
return false, beacon.EpochInvalid
329330
}
330331

331-
if uint64(blockHeight) == s.initialHeight {
332+
if lastHeight == s.initialHeight {
332333
// There is no block before the first block. For historic reasons, this is defined as not
333334
// having had a transition.
334335
return false, currentEpoch
@@ -380,13 +381,14 @@ func (s *applicationState) doInitChain() error {
380381

381382
// We use the height before the initial height for the state before the first block. Note that
382383
// this tree is not persisted, we only need it to compute the root hash.
383-
_, stateRootHash, err := s.canonicalState.Commit(s.ctx, s.stateRoot.Namespace, s.initialHeight-1, mkvs.NoPersist())
384+
version := uint64(s.initialHeight - 1)
385+
_, stateRootHash, err := s.canonicalState.Commit(s.ctx, s.stateRoot.Namespace, version, mkvs.NoPersist())
384386
if err != nil {
385387
return fmt.Errorf("failed to commit: %w", err)
386388
}
387389

388390
s.stateRoot.Hash = stateRootHash
389-
s.stateRoot.Version = s.initialHeight - 1
391+
s.stateRoot.Version = version
390392

391393
return s.doCommitOrInitChainLocked()
392394
}
@@ -622,7 +624,7 @@ func (s *applicationState) pruneWorker() {
622624
if err := s.statePruner.Prune(version); err != nil {
623625
s.logger.Warn("failed to prune state",
624626
"err", err,
625-
"block_height", version,
627+
"height", version,
626628
)
627629
}
628630
}
@@ -756,7 +758,8 @@ func newApplicationState(ctx context.Context, upgrader upgrade.Backend, cfg *App
756758
}
757759

758760
// Refresh consensus parameters when loading state if we are past genesis.
759-
if latestVersion >= s.initialHeight {
761+
initialVersion := uint64(s.initialHeight)
762+
if latestVersion >= initialVersion {
760763
if err = s.doCommitOrInitChainLocked(); err != nil {
761764
return nil, fmt.Errorf("state: failed to run initial state commit hook: %w", err)
762765
}
@@ -774,7 +777,7 @@ func newApplicationState(ctx context.Context, upgrader upgrade.Backend, cfg *App
774777
Interval: params.StateCheckpointInterval,
775778
NumKept: params.StateCheckpointNumKept,
776779
ChunkSize: params.StateCheckpointChunkSize,
777-
InitialVersion: cfg.InitialHeight,
780+
InitialVersion: initialVersion,
778781
ChunkerThreads: cfg.ChunkerThreads,
779782
}, nil
780783
},

go/consensus/cometbft/abci/transaction.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ func (mux *abciMux) executeTx(ctx *api.Context, rawTx []byte) error {
137137
// If we are in CheckTx mode and there is a pending upgrade in this block, make sure to reject
138138
// any transactions before processing as they may potentially query incompatible state.
139139
if upgrader := mux.state.Upgrader(); upgrader != nil && ctx.IsCheckOnly() {
140-
hasUpgrade, err := upgrader.HasPendingUpgradeAt(ctx.BlockHeight() + 1)
140+
hasUpgrade, err := upgrader.HasPendingUpgradeAt(ctx.CurrentHeight())
141141
if err != nil {
142142
return fmt.Errorf("failed to check for pending upgrades: %w", err)
143143
}
@@ -156,7 +156,7 @@ func (mux *abciMux) EstimateGas(caller signature.PublicKey, tx *transaction.Tran
156156

157157
// Certain modules, in particular the beacon require InitChain or BeginBlock
158158
// to have completed before initialization is complete.
159-
if mux.state.BlockHeight() == 0 {
159+
if mux.state.LastHeight() == 0 {
160160
return 0, consensus.ErrNoCommittedBlocks
161161
}
162162

go/consensus/cometbft/abci/upgrade.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ func (mux *abciMux) maybeHaltForUpgrade() {
2424
)
2525
return
2626
}
27-
height := mux.state.BlockHeight()
27+
height := mux.state.LastHeight()
2828

2929
// Check if we need to halt for an upgrade -- but do not actually run the upgrade.
3030
switch err := upgrader.ConsensusUpgrade(nil, epoch, height); err {

go/consensus/cometbft/api/context.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,8 @@ type Context struct {
7979

8080
appState ApplicationState
8181
state mkvs.KeyValueTree
82-
blockHeight int64
8382
blockCtx *BlockContext
83+
lastHeight int64
8484
initialHeight int64
8585

8686
logger *logging.Logger
@@ -101,8 +101,8 @@ func NewContext(
101101
gasAccountant GasAccountant,
102102
appState ApplicationState,
103103
state mkvs.KeyValueTree,
104-
blockHeight int64,
105104
blockCtx *BlockContext,
105+
lastHeight int64,
106106
initialHeight int64,
107107
) *Context {
108108
c := &Context{
@@ -112,8 +112,8 @@ func NewContext(
112112
priority: 0,
113113
appState: appState,
114114
state: state,
115-
blockHeight: blockHeight,
116115
blockCtx: blockCtx,
116+
lastHeight: lastHeight,
117117
initialHeight: initialHeight,
118118
logger: logging.GetLogger("consensus/cometbft/abci").With("mode", mode),
119119
}
@@ -229,7 +229,7 @@ func (c *Context) NewChild() *Context {
229229
callerAddress: c.callerAddress,
230230
appState: c.appState,
231231
state: c.state,
232-
blockHeight: c.blockHeight,
232+
lastHeight: c.lastHeight,
233233
blockCtx: c.blockCtx,
234234
initialHeight: c.initialHeight,
235235
logger: c.logger,
@@ -421,9 +421,14 @@ func (c *Context) InitialHeight() int64 {
421421
return c.initialHeight
422422
}
423423

424-
// BlockHeight returns the current block height.
425-
func (c *Context) BlockHeight() int64 {
426-
return c.blockHeight
424+
// LastHeight returns the last committed block height.
425+
func (c *Context) LastHeight() int64 {
426+
return c.lastHeight
427+
}
428+
429+
// CurrentHeight returns the height of the block being built.
430+
func (c *Context) CurrentHeight() int64 {
431+
return c.lastHeight + 1
427432
}
428433

429434
// LastStateRootHash returns the last state root hash.

go/consensus/cometbft/api/context_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func TestChildContext(t *testing.T) {
6363
require.EqualValues(ctx.State(), child.State(), "child.State should correspond to parent.State")
6464
require.EqualValues(ctx.AppState(), child.AppState(), "child.Mode should correspond to parent.Mode")
6565
require.EqualValues(ctx.InitialHeight(), child.InitialHeight(), "child.InitialHeight should correspond to parent.InitialHeight")
66-
require.EqualValues(ctx.BlockHeight(), child.BlockHeight(), "child.BlockHeight should correspond to parent.BlockHeight")
66+
require.EqualValues(ctx.LastHeight(), child.LastHeight(), "child.LastHeight should correspond to parent.LastHeight")
6767
require.EqualValues(ctx.BlockContext(), child.BlockContext(), "child.BlockContext should correspond to parent.BlockContext")
6868
require.EqualValues(1, child.CallDepth(), "child.CallDepth should be correct")
6969

0 commit comments

Comments
 (0)