Skip to content

Commit 5622115

Browse files
authored
feat!: add protection against accidental downgrades (#10407)
## Description Closes: #10318 --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
1 parent 95e65fe commit 5622115

File tree

5 files changed

+153
-0
lines changed

5 files changed

+153
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
5757
* [\#10311](https://github.com/cosmos/cosmos-sdk/pull/10311) Adds cli to use tips transactions. It adds an `--aux` flag to all CLI tx commands to generate the aux signer data (with optional tip), and a new `tx aux-to-fee` subcommand to let the fee payer gather aux signer data and broadcast the tx
5858
* [\#10430](https://github.com/cosmos/cosmos-sdk/pull/10430) ADR-040: Add store/v2 `MultiStore` implementation
5959
* [\#10947](https://github.com/cosmos/cosmos-sdk/pull/10947) Add `AllowancesByGranter` query to the feegrant module
60+
* [\#10407](https://github.com/cosmos/cosmos-sdk/pull/10407) Add validation to `x/upgrade` module's `BeginBlock` to check accidental binary downgrades
6061

6162
### API Breaking Changes
6263

x/upgrade/abci.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,24 @@ import (
2222
// skipUpgradeHeightArray is a set of block heights for which the upgrade must be skipped
2323
func BeginBlocker(k keeper.Keeper, ctx sdk.Context, _ abci.RequestBeginBlock) {
2424
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker)
25+
2526
plan, found := k.GetUpgradePlan(ctx)
27+
28+
if !k.DowngradeVerified() {
29+
k.SetDowngradeVerified(true)
30+
lastAppliedPlan, _ := k.GetLastCompletedUpgrade(ctx)
31+
// This check will make sure that we are using a valid binary.
32+
// It'll panic in these cases if there is no upgrade handler registered for the last applied upgrade.
33+
// 1. If there is no scheduled upgrade.
34+
// 2. If the plan is not ready.
35+
// 3. If the plan is ready and skip upgrade height is set for current height.
36+
if !found || !plan.ShouldExecute(ctx) || (plan.ShouldExecute(ctx) && k.IsSkipHeight(ctx.BlockHeight())) {
37+
if lastAppliedPlan != "" && !k.HasHandler(lastAppliedPlan) {
38+
panic(fmt.Sprintf("Wrong app version %d, upgrade handler is missing for %s upgrade plan", ctx.ConsensusParams().Version.AppVersion, lastAppliedPlan))
39+
}
40+
}
41+
}
42+
2643
if !found {
2744
return
2845
}

x/upgrade/abci_test.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,3 +410,70 @@ func TestDumpUpgradeInfoToFile(t *testing.T) {
410410
err = os.Remove(upgradeInfoFilePath)
411411
require.Nil(err)
412412
}
413+
414+
// TODO: add testcase to for `no upgrade handler is present for last applied upgrade`.
415+
func TestBinaryVersion(t *testing.T) {
416+
var skipHeight int64 = 15
417+
s := setupTest(t, 10, map[int64]bool{skipHeight: true})
418+
419+
testCases := []struct {
420+
name string
421+
preRun func() (sdk.Context, abci.RequestBeginBlock)
422+
expectPanic bool
423+
}{
424+
{
425+
"test not panic: no scheduled upgrade or applied upgrade is present",
426+
func() (sdk.Context, abci.RequestBeginBlock) {
427+
req := abci.RequestBeginBlock{Header: s.ctx.BlockHeader()}
428+
return s.ctx, req
429+
},
430+
false,
431+
},
432+
{
433+
"test not panic: upgrade handler is present for last applied upgrade",
434+
func() (sdk.Context, abci.RequestBeginBlock) {
435+
s.keeper.SetUpgradeHandler("test0", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) {
436+
return vm, nil
437+
})
438+
439+
err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "Upgrade test", Plan: types.Plan{Name: "test0", Height: s.ctx.BlockHeight() + 2}})
440+
require.Nil(t, err)
441+
442+
newCtx := s.ctx.WithBlockHeight(12)
443+
s.keeper.ApplyUpgrade(newCtx, types.Plan{
444+
Name: "test0",
445+
Height: 12,
446+
})
447+
448+
req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()}
449+
return newCtx, req
450+
},
451+
false,
452+
},
453+
{
454+
"test panic: upgrade needed",
455+
func() (sdk.Context, abci.RequestBeginBlock) {
456+
err := s.handler(s.ctx, &types.SoftwareUpgradeProposal{Title: "Upgrade test", Plan: types.Plan{Name: "test2", Height: 13}})
457+
require.Nil(t, err)
458+
459+
newCtx := s.ctx.WithBlockHeight(13)
460+
req := abci.RequestBeginBlock{Header: newCtx.BlockHeader()}
461+
return newCtx, req
462+
},
463+
true,
464+
},
465+
}
466+
467+
for _, tc := range testCases {
468+
ctx, req := tc.preRun()
469+
if tc.expectPanic {
470+
require.Panics(t, func() {
471+
s.module.BeginBlock(ctx, req)
472+
})
473+
} else {
474+
require.NotPanics(t, func() {
475+
s.module.BeginBlock(ctx, req)
476+
})
477+
}
478+
}
479+
}

x/upgrade/keeper/keeper.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"github.com/cosmos/cosmos-sdk/store/prefix"
1818
sdk "github.com/cosmos/cosmos-sdk/types"
1919
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
20+
"github.com/cosmos/cosmos-sdk/types/kv"
2021
"github.com/cosmos/cosmos-sdk/types/module"
2122
xp "github.com/cosmos/cosmos-sdk/x/upgrade/exported"
2223
"github.com/cosmos/cosmos-sdk/x/upgrade/types"
@@ -33,6 +34,7 @@ type Keeper struct {
3334
cdc codec.BinaryCodec // App-wide binary codec
3435
upgradeHandlers map[string]types.UpgradeHandler // map of plan name to upgrade handler
3536
versionSetter xp.ProtocolVersionSetter // implements setting the protocol version field on BaseApp
37+
downgradeVerified bool // tells if we've already sanity checked that this binary version isn't being used against an old state.
3638
}
3739

3840
// NewKeeper constructs an upgrade Keeper which requires the following arguments:
@@ -228,6 +230,23 @@ func (k Keeper) GetUpgradedConsensusState(ctx sdk.Context, lastHeight int64) ([]
228230
return bz, true
229231
}
230232

233+
// GetLastCompletedUpgrade returns the last applied upgrade name and height.
234+
func (k Keeper) GetLastCompletedUpgrade(ctx sdk.Context) (string, int64) {
235+
iter := sdk.KVStoreReversePrefixIterator(ctx.KVStore(k.storeKey), []byte{types.DoneByte})
236+
defer iter.Close()
237+
if iter.Valid() {
238+
return parseDoneKey(iter.Key()), int64(binary.BigEndian.Uint64(iter.Value()))
239+
}
240+
241+
return "", 0
242+
}
243+
244+
// parseDoneKey - split upgrade name from the done key
245+
func parseDoneKey(key []byte) string {
246+
kv.AssertKeyAtLeastLength(key, 2)
247+
return string(key[1:])
248+
}
249+
231250
// GetDoneHeight returns the height at which the given upgrade was executed
232251
func (k Keeper) GetDoneHeight(ctx sdk.Context, name string) int64 {
233252
store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte{types.DoneByte})
@@ -389,3 +408,13 @@ func (k Keeper) ReadUpgradeInfoFromDisk() (types.Plan, error) {
389408

390409
return upgradeInfo, nil
391410
}
411+
412+
// SetDowngradeVerified updates downgradeVerified.
413+
func (k *Keeper) SetDowngradeVerified(v bool) {
414+
k.downgradeVerified = v
415+
}
416+
417+
// DowngradeVerified returns downgradeVerified.
418+
func (k Keeper) DowngradeVerified() bool {
419+
return k.downgradeVerified
420+
}

x/upgrade/keeper/keeper_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,45 @@ func (s *KeeperTestSuite) TestMigrations() {
232232
s.Require().Equal(vmBefore["bank"]+1, vm["bank"])
233233
}
234234

235+
func (s *KeeperTestSuite) TestLastCompletedUpgrade() {
236+
keeper := s.app.UpgradeKeeper
237+
require := s.Require()
238+
239+
s.T().Log("verify empty name if applied upgrades are empty")
240+
name, height := keeper.GetLastCompletedUpgrade(s.ctx)
241+
require.Equal("", name)
242+
require.Equal(int64(0), height)
243+
244+
keeper.SetUpgradeHandler("test0", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) {
245+
return vm, nil
246+
})
247+
248+
keeper.ApplyUpgrade(s.ctx, types.Plan{
249+
Name: "test0",
250+
Height: 10,
251+
})
252+
253+
s.T().Log("verify valid upgrade name and height")
254+
name, height = keeper.GetLastCompletedUpgrade(s.ctx)
255+
require.Equal("test0", name)
256+
require.Equal(int64(10), height)
257+
258+
keeper.SetUpgradeHandler("test1", func(_ sdk.Context, _ types.Plan, vm module.VersionMap) (module.VersionMap, error) {
259+
return vm, nil
260+
})
261+
262+
newCtx := s.ctx.WithBlockHeight(15)
263+
keeper.ApplyUpgrade(newCtx, types.Plan{
264+
Name: "test1",
265+
Height: 15,
266+
})
267+
268+
s.T().Log("verify valid upgrade name and height with multiple upgrades")
269+
name, height = keeper.GetLastCompletedUpgrade(newCtx)
270+
require.Equal("test1", name)
271+
require.Equal(int64(15), height)
272+
}
273+
235274
func TestKeeperTestSuite(t *testing.T) {
236275
suite.Run(t, new(KeeperTestSuite))
237276
}

0 commit comments

Comments
 (0)