@@ -25,6 +25,8 @@ import (
2525 tmcmd "github.com/cometbft/cometbft/cmd/cometbft/commands"
2626 tmcfg "github.com/cometbft/cometbft/config"
2727 tmlog "github.com/cometbft/cometbft/libs/log"
28+ "github.com/cometbft/cometbft/node"
29+ tmstore "github.com/cometbft/cometbft/store"
2830 tmtypes "github.com/cometbft/cometbft/types"
2931
3032 "github.com/cosmos/cosmos-sdk/baseapp"
@@ -459,13 +461,13 @@ func DefaultBaseappOptions(appOpts types.AppOptions) []func(*baseapp.BaseApp) {
459461 homeDir := cast .ToString (appOpts .Get (flags .FlagHome ))
460462 chainID := cast .ToString (appOpts .Get (flags .FlagChainID ))
461463 if chainID == "" {
462- // fallback to genesis chain-id
463- appGenesis , err := tmtypes . GenesisDocFromFile ( filepath . Join ( homeDir , "config" , "genesis.json" ) )
464+ // read the chainID from home directory (either from comet or genesis).
465+ chainId , err := readChainIdFromHome ( homeDir )
464466 if err != nil {
465467 panic (err )
466468 }
467469
468- chainID = appGenesis . ChainID
470+ chainID = chainId
469471 }
470472
471473 snapshotStore , err := GetSnapshotStore (appOpts )
@@ -500,6 +502,38 @@ func DefaultBaseappOptions(appOpts types.AppOptions) []func(*baseapp.BaseApp) {
500502 }
501503}
502504
505+ // readChainIdFromHome reads chain id from home directory.
506+ func readChainIdFromHome (homeDir string ) (string , error ) {
507+ cfg := tmcfg .DefaultConfig ()
508+ cfg .SetRoot (homeDir )
509+
510+ // if the node's current height is not zero then try to read the chainID from comet db.
511+ db , err := node .DefaultDBProvider (& node.DBContext {ID : "blockstore" , Config : cfg })
512+ if err != nil {
513+ return "" , err
514+ }
515+
516+ blockStore := tmstore .NewBlockStore (db )
517+ defer func () {
518+ if err := blockStore .Close (); err != nil {
519+ panic (err )
520+ }
521+ }()
522+
523+ // if the blockStore.LoadBaseMeta() is nil (no blocks are created/synced so far), fallback to genesis chain-id.
524+ baseMeta := blockStore .LoadBaseMeta ()
525+ if baseMeta != nil {
526+ return baseMeta .Header .ChainID , nil
527+ }
528+
529+ appGenesis , err := tmtypes .GenesisDocFromFile (filepath .Join (homeDir , "config" , "genesis.json" ))
530+ if err != nil {
531+ return "" , err
532+ }
533+
534+ return appGenesis .ChainID , nil
535+ }
536+
503537func GetSnapshotStore (appOpts types.AppOptions ) (* snapshots.Store , error ) {
504538 homeDir := cast .ToString (appOpts .Get (flags .FlagHome ))
505539 snapshotDir := filepath .Join (homeDir , "data" , "snapshots" )
0 commit comments