feat: simapp/v2 (#20412)

Co-authored-by: marbar3778 <marbar3778@yahoo.com>
Co-authored-by: Marko <marko@baricevic.me>
Co-authored-by: Likhita Polavarapu <78951027+likhita-809@users.noreply.github.com>
Co-authored-by: unknown unknown <unknown@unknown>
This commit is contained in:
Matt Kocubinski 2024-06-19 10:18:32 -05:00 committed by GitHub
parent ca195c1527
commit 2d014b26c2
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 3137 additions and 12 deletions

View File

@ -485,6 +485,30 @@ jobs:
cd simapp
go test -mod=readonly -timeout 30m -tags='app_v1 norace ledger test_ledger_mock' ./...
test-simapp-v2:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.22"
check-latest: true
cache: true
cache-dependency-path: go.sum
- uses: technote-space/get-diff-action@v6.1.2
id: git_diff
with:
PATTERNS: |
**/*.go
go.mod
go.sum
**/go.mod
**/go.sum
- name: simapp-v2-smoke-test
if: env.GIT_DIFF
run: |
./scripts/simapp-v2-init.sh
test-collections:
runs-on: ubuntu-latest
steps:

9
.vscode/launch.json vendored
View File

@ -11,6 +11,15 @@
"program": "${fileDirname}",
"args": ["-test.timeout", "30m", "-test.v"],
"buildFlags": "-tags e2e"
},
{
"name": "Start: simapp/v2",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}/simapp/v2/simdv2",
"args": ["start"],
"buildFlags": ""
}
]
}

View File

@ -35,11 +35,11 @@ func ProvideInterfaceRegistry(
SigningOptions: signingOptions,
})
if err != nil {
return nil, nil, err
return nil, nil, fmt.Errorf("failed to create interface registry: %w", err)
}
if err := interfaceRegistry.SigningContext().Validate(); err != nil {
return nil, nil, err
return nil, nil, fmt.Errorf("failed to validate signing context: %w", err)
}
return interfaceRegistry, interfaceRegistry, nil

View File

@ -24,6 +24,7 @@ COPY x/mint/go.mod x/mint/go.sum /work/x/mint/
COPY x/consensus/go.mod x/consensus/go.sum /work/x/consensus/
COPY x/accounts/go.mod x/accounts/go.sum /work/x/accounts/
COPY runtime/v2/go.mod runtime/v2/go.sum /work/runtime/v2/
COPY server/v2/go.mod server/v2/go.sum /work/server/v2/
COPY server/v2/appmanager/go.mod server/v2/appmanager/go.sum /work/server/v2/appmanager/
COPY server/v2/stf/go.mod server/v2/stf/go.sum /work/server/v2/stf/
COPY server/v2/cometbft/go.mod server/v2/cometbft/go.sum /work/server/v2/cometbft/

View File

@ -33,6 +33,10 @@ func (i *Info) Bytes() ([]byte, error) {
binary.LittleEndian.PutUint64(heightBytes, uint64(i.Height))
buf = append(buf, heightBytes...)
// TODO; permit empty hash OK for genesis block?
if len(i.Hash) == 0 {
i.Hash = make([]byte, hashSize)
}
// Encode Hash
if len(i.Hash) != hashSize {
return nil, errors.New("invalid hash size")
@ -44,6 +48,9 @@ func (i *Info) Bytes() ([]byte, error) {
binary.LittleEndian.PutUint64(timeBytes, uint64(i.Time.Unix()))
buf = append(buf, timeBytes...)
if len(i.AppHash) == 0 {
i.AppHash = make([]byte, hashSize)
}
// Encode AppHash
if len(i.Hash) != hashSize {
return nil, errors.New("invalid hash size")

View File

@ -101,6 +101,7 @@ func init() {
ProvideModuleManager,
ProvideGenesisTxHandler,
ProvideCometService,
ProvideAppVersionModifier,
),
appconfig.Invoke(SetupAppBuilder),
)

52
scripts/simapp-v2-init.sh Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -x
ROOT=$PWD
SIMAPP_DIR="$ROOT/simapp/v2"
SIMD="$ROOT/build/simdv2"
CONFIG="${CONFIG:-$HOME/.simappv2/config}"
cd "$SIMAPP_DIR"
go build -o "$ROOT/build/simdv2" simdv2/main.go
$SIMD init simapp-v2-node --chain-id simapp-v2-chain
cd "$CONFIG"
# to enable the api server
$SIMD config set app api.enable true
# to change the voting_period
jq '.app_state.gov.voting_params.voting_period = "600s"' genesis.json > temp.json && mv temp.json genesis.json
# to change the inflation
jq '.app_state.mint.minter.inflation = "0.300000000000000000"' genesis.json > temp.json && mv temp.json genesis.json
# change the initial height to 2 to work around store/v2 and iavl limitations with a genesis block
jq '.initial_height = 2' genesis.json > temp.json && mv temp.json genesis.json
$SIMD keys add test_validator --indiscreet
VALIDATOR_ADDRESS=$($SIMD keys show test_validator -a --keyring-backend test)
$SIMD genesis add-genesis-account "$VALIDATOR_ADDRESS" 1000000000stake
$SIMD genesis gentx test_validator 1000000000stake --keyring-backend test
$SIMD genesis collect-gentxs
$SIMD start &
SIMD_PID=$!
cnt=0
while ! $SIMD query block --type=height 5; do
cnt=$((cnt + 1))
if [ $cnt -gt 30 ]; then
kill -9 "$SIMD_PID"
exit 1
fi
sleep 1
done
kill -9 "$SIMD_PID"

View File

@ -9,6 +9,7 @@ replace (
cosmossdk.io/depinject => ../../../depinject
cosmossdk.io/server/v2 => ../
cosmossdk.io/server/v2/appmanager => ../appmanager
cosmossdk.io/store => ../../../store
cosmossdk.io/store/v2 => ../../../store/v2
cosmossdk.io/x/accounts => ../../../x/accounts
cosmossdk.io/x/auth => ../../../x/auth

View File

@ -12,8 +12,6 @@ cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI=
cosmossdk.io/log v1.3.1/go.mod h1:2/dIomt8mKdk6vl3OWJcPk2be3pGOS8OQaLUM/3/tCM=
cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE=
cosmossdk.io/math v1.3.0/go.mod h1:vnRTxewy+M7BtXBNFybkuhSH4WfedVAAnERHgVFhp3k=
cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc h1:R9O9d75e0qZYUsVV0zzi+D7cNLnX2JrUOQNoIPaF0Bg=
cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc/go.mod h1:amTTatOUV3u1PsKmNb87z6/galCxrRbz9kRdJkL0DyU=
cosmossdk.io/x/accounts/defaults/lockup v0.0.0-20240417181816-5e7aae0db1f5 h1:eb0kcGyaYHSS0do7+MIWg7UKlskSH01biRNENbm/zDA=
cosmossdk.io/x/accounts/defaults/lockup v0.0.0-20240417181816-5e7aae0db1f5/go.mod h1:drzY4oVisyWvSgpsM7ccQ7IX3efMuVIvd9Eij1Gm/6o=
cosmossdk.io/x/tx v0.13.3 h1:Ha4mNaHmxBc6RMun9aKuqul8yHiL78EKJQ8g23Zf73g=

View File

@ -1,6 +1,6 @@
package streaming
import "cosmossdk.io/log"
import "cosmossdk.io/core/log"
// Context is an interface used by an App to pass context information
// needed to process store streaming requests.

View File

@ -12,7 +12,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"cosmossdk.io/log"
"cosmossdk.io/core/log"
)
type PluginTestSuite struct {

8
simapp/v2/README.md Normal file
View File

@ -0,0 +1,8 @@
---
sidebar_position: 1
---
# `SimApp/v2`
SimApp is an application built using the Cosmos SDK for testing and educational purposes.
`SimApp/v2` demonstrate a runtime/v2, server/v2 and store/v2 wiring.

272
simapp/v2/app_config.go Normal file
View File

@ -0,0 +1,272 @@
//nolint:unused,nolintlint // ignore unused code linting and directive `//nolint:unused // ignore unused code linting` is unused for linter "unused"
package simapp
import (
"time"
"google.golang.org/protobuf/types/known/durationpb"
accountsmodulev1 "cosmossdk.io/api/cosmos/accounts/module/v1"
runtimev2 "cosmossdk.io/api/cosmos/app/runtime/v2"
appv1alpha1 "cosmossdk.io/api/cosmos/app/v1alpha1"
authmodulev1 "cosmossdk.io/api/cosmos/auth/module/v1"
authzmodulev1 "cosmossdk.io/api/cosmos/authz/module/v1"
bankmodulev1 "cosmossdk.io/api/cosmos/bank/module/v1"
circuitmodulev1 "cosmossdk.io/api/cosmos/circuit/module/v1"
consensusmodulev1 "cosmossdk.io/api/cosmos/consensus/module/v1"
distrmodulev1 "cosmossdk.io/api/cosmos/distribution/module/v1"
evidencemodulev1 "cosmossdk.io/api/cosmos/evidence/module/v1"
feegrantmodulev1 "cosmossdk.io/api/cosmos/feegrant/module/v1"
genutilmodulev1 "cosmossdk.io/api/cosmos/genutil/module/v1"
govmodulev1 "cosmossdk.io/api/cosmos/gov/module/v1"
groupmodulev1 "cosmossdk.io/api/cosmos/group/module/v1"
mintmodulev1 "cosmossdk.io/api/cosmos/mint/module/v1"
nftmodulev1 "cosmossdk.io/api/cosmos/nft/module/v1"
poolmodulev1 "cosmossdk.io/api/cosmos/protocolpool/module/v1"
slashingmodulev1 "cosmossdk.io/api/cosmos/slashing/module/v1"
stakingmodulev1 "cosmossdk.io/api/cosmos/staking/module/v1"
txconfigv1 "cosmossdk.io/api/cosmos/tx/config/v1"
upgrademodulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1"
vestingmodulev1 "cosmossdk.io/api/cosmos/vesting/module/v1"
"cosmossdk.io/depinject/appconfig"
"cosmossdk.io/x/accounts"
_ "cosmossdk.io/x/auth" // import for side-effects
_ "cosmossdk.io/x/auth/tx/config" // import for side-effects
authtypes "cosmossdk.io/x/auth/types"
_ "cosmossdk.io/x/auth/vesting" // import for side-effects
vestingtypes "cosmossdk.io/x/auth/vesting/types"
"cosmossdk.io/x/authz"
_ "cosmossdk.io/x/authz/module" // import for side-effects
_ "cosmossdk.io/x/bank" // import for side-effects
banktypes "cosmossdk.io/x/bank/types"
_ "cosmossdk.io/x/circuit" // import for side-effects
circuittypes "cosmossdk.io/x/circuit/types"
_ "cosmossdk.io/x/consensus" // import for side-effects
consensustypes "cosmossdk.io/x/consensus/types"
_ "cosmossdk.io/x/distribution" // import for side-effects
distrtypes "cosmossdk.io/x/distribution/types"
_ "cosmossdk.io/x/evidence" // import for side-effects
evidencetypes "cosmossdk.io/x/evidence/types"
"cosmossdk.io/x/feegrant"
_ "cosmossdk.io/x/feegrant/module" // import for side-effects
_ "cosmossdk.io/x/gov" // import for side-effects
govtypes "cosmossdk.io/x/gov/types"
"cosmossdk.io/x/group"
_ "cosmossdk.io/x/group/module" // import for side-effects
_ "cosmossdk.io/x/mint" // import for side-effects
minttypes "cosmossdk.io/x/mint/types"
"cosmossdk.io/x/nft"
_ "cosmossdk.io/x/nft/module" // import for side-effects
_ "cosmossdk.io/x/protocolpool" // import for side-effects
pooltypes "cosmossdk.io/x/protocolpool/types"
_ "cosmossdk.io/x/slashing" // import for side-effects
slashingtypes "cosmossdk.io/x/slashing/types"
_ "cosmossdk.io/x/staking" // import for side-effects
stakingtypes "cosmossdk.io/x/staking/types"
_ "cosmossdk.io/x/upgrade" // import for side-effects
upgradetypes "cosmossdk.io/x/upgrade/types"
"github.com/cosmos/cosmos-sdk/runtime"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
)
var (
// module account permissions
moduleAccPerms = []*authmodulev1.ModuleAccountPermission{
{Account: authtypes.FeeCollectorName},
{Account: distrtypes.ModuleName},
{Account: pooltypes.ModuleName},
{Account: pooltypes.StreamAccount},
{Account: minttypes.ModuleName, Permissions: []string{authtypes.Minter}},
{Account: stakingtypes.BondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: stakingtypes.NotBondedPoolName, Permissions: []string{authtypes.Burner, stakingtypes.ModuleName}},
{Account: govtypes.ModuleName, Permissions: []string{authtypes.Burner}},
{Account: nft.ModuleName},
}
// blocked account addresses
blockAccAddrs = []string{
authtypes.FeeCollectorName,
distrtypes.ModuleName,
minttypes.ModuleName,
stakingtypes.BondedPoolName,
stakingtypes.NotBondedPoolName,
nft.ModuleName,
// We allow the following module accounts to receive funds:
// govtypes.ModuleName
// pooltypes.ModuleName
}
// application configuration (used by depinject)
appConfig = appconfig.Compose(&appv1alpha1.Config{
Modules: []*appv1alpha1.ModuleConfig{
{
Name: runtime.ModuleName,
Config: appconfig.WrapAny(&runtimev2.Module{
AppName: "SimAppV2",
// NOTE: upgrade module is required to be prioritized
PreBlockers: []string{
upgradetypes.ModuleName,
},
// During begin block slashing happens after distr.BeginBlocker so that
// there is nothing left over in the validator fee pool, so as to keep the
// CanWithdrawInvariant invariant.
// NOTE: staking module is required if HistoricalEntries param > 0
BeginBlockers: []string{
minttypes.ModuleName,
distrtypes.ModuleName,
slashingtypes.ModuleName,
evidencetypes.ModuleName,
stakingtypes.ModuleName,
authz.ModuleName,
},
EndBlockers: []string{
govtypes.ModuleName,
stakingtypes.ModuleName,
feegrant.ModuleName,
group.ModuleName,
pooltypes.ModuleName,
},
OverrideStoreKeys: []*runtimev2.StoreKeyConfig{
{
ModuleName: authtypes.ModuleName,
KvStoreKey: "acc",
},
},
// NOTE: The genutils module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: The genutils module must also occur after auth so that it can access the params from auth.
InitGenesis: []string{
accounts.ModuleName,
authtypes.ModuleName,
banktypes.ModuleName,
distrtypes.ModuleName,
stakingtypes.ModuleName,
slashingtypes.ModuleName,
govtypes.ModuleName,
minttypes.ModuleName,
genutiltypes.ModuleName,
evidencetypes.ModuleName,
authz.ModuleName,
feegrant.ModuleName,
nft.ModuleName,
group.ModuleName,
upgradetypes.ModuleName,
vestingtypes.ModuleName,
circuittypes.ModuleName,
pooltypes.ModuleName,
},
// When ExportGenesis is not specified, the export genesis module order
// is equal to the init genesis order
// ExportGenesis: []string{},
// Uncomment if you want to set a custom migration order here.
// OrderMigrations: []string{},
// TODO GasConfig was added to the config in runtimev2. Where/how was it set in v1?
GasConfig: &runtimev2.GasConfig{
ValidateTxGasLimit: 100_000,
QueryGasLimit: 100_000,
SimulationGasLimit: 100_000,
},
}),
},
{
Name: authtypes.ModuleName,
Config: appconfig.WrapAny(&authmodulev1.Module{
Bech32Prefix: "cosmos",
ModuleAccountPermissions: moduleAccPerms,
// By default modules authority is the governance module. This is configurable with the following:
// Authority: "group", // A custom module authority can be set using a module name
// Authority: "cosmos1cwwv22j5ca08ggdv9c2uky355k908694z577tv", // or a specific address
}),
},
{
Name: vestingtypes.ModuleName,
Config: appconfig.WrapAny(&vestingmodulev1.Module{}),
},
{
Name: banktypes.ModuleName,
Config: appconfig.WrapAny(&bankmodulev1.Module{
BlockedModuleAccountsOverride: blockAccAddrs,
}),
},
{
Name: stakingtypes.ModuleName,
Config: appconfig.WrapAny(&stakingmodulev1.Module{
// NOTE: specifying a prefix is only necessary when using bech32 addresses
// If not specified, the auth Bech32Prefix appended with "valoper" and "valcons" is used by default
Bech32PrefixValidator: "cosmosvaloper",
Bech32PrefixConsensus: "cosmosvalcons",
}),
},
{
Name: slashingtypes.ModuleName,
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
},
{
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{}),
},
{
Name: genutiltypes.ModuleName,
Config: appconfig.WrapAny(&genutilmodulev1.Module{}),
},
{
Name: authz.ModuleName,
Config: appconfig.WrapAny(&authzmodulev1.Module{}),
},
{
Name: upgradetypes.ModuleName,
Config: appconfig.WrapAny(&upgrademodulev1.Module{}),
},
{
Name: distrtypes.ModuleName,
Config: appconfig.WrapAny(&distrmodulev1.Module{}),
},
{
Name: evidencetypes.ModuleName,
Config: appconfig.WrapAny(&evidencemodulev1.Module{}),
},
{
Name: minttypes.ModuleName,
Config: appconfig.WrapAny(&mintmodulev1.Module{}),
},
{
Name: group.ModuleName,
Config: appconfig.WrapAny(&groupmodulev1.Module{
MaxExecutionPeriod: durationpb.New(time.Second * 1209600),
MaxMetadataLen: 255,
}),
},
{
Name: nft.ModuleName,
Config: appconfig.WrapAny(&nftmodulev1.Module{}),
},
{
Name: feegrant.ModuleName,
Config: appconfig.WrapAny(&feegrantmodulev1.Module{}),
},
{
Name: govtypes.ModuleName,
Config: appconfig.WrapAny(&govmodulev1.Module{}),
},
{
Name: consensustypes.ModuleName,
Config: appconfig.WrapAny(&consensusmodulev1.Module{
Authority: "consensus",
}),
},
{
Name: accounts.ModuleName,
Config: appconfig.WrapAny(&accountsmodulev1.Module{}),
},
{
Name: circuittypes.ModuleName,
Config: appconfig.WrapAny(&circuitmodulev1.Module{}),
},
{
Name: pooltypes.ModuleName,
Config: appconfig.WrapAny(&poolmodulev1.Module{}),
},
},
})
)

248
simapp/v2/app_di.go Normal file
View File

@ -0,0 +1,248 @@
package simapp
import (
_ "embed"
"os"
"path/filepath"
"cosmossdk.io/core/legacy"
"cosmossdk.io/core/log"
"cosmossdk.io/depinject"
"cosmossdk.io/runtime/v2"
"cosmossdk.io/store/v2"
"cosmossdk.io/store/v2/commitment/iavl"
"cosmossdk.io/store/v2/db"
"cosmossdk.io/store/v2/root"
"cosmossdk.io/x/accounts"
authkeeper "cosmossdk.io/x/auth/keeper"
authzkeeper "cosmossdk.io/x/authz/keeper"
bankkeeper "cosmossdk.io/x/bank/keeper"
circuitkeeper "cosmossdk.io/x/circuit/keeper"
consensuskeeper "cosmossdk.io/x/consensus/keeper"
distrkeeper "cosmossdk.io/x/distribution/keeper"
evidencekeeper "cosmossdk.io/x/evidence/keeper"
feegrantkeeper "cosmossdk.io/x/feegrant/keeper"
govkeeper "cosmossdk.io/x/gov/keeper"
groupkeeper "cosmossdk.io/x/group/keeper"
mintkeeper "cosmossdk.io/x/mint/keeper"
nftkeeper "cosmossdk.io/x/nft/keeper"
_ "cosmossdk.io/x/protocolpool"
poolkeeper "cosmossdk.io/x/protocolpool/keeper"
slashingkeeper "cosmossdk.io/x/slashing/keeper"
stakingkeeper "cosmossdk.io/x/staking/keeper"
upgradekeeper "cosmossdk.io/x/upgrade/keeper"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/std"
)
// DefaultNodeHome default home directories for the application daemon
var DefaultNodeHome string
// SimApp extends an ABCI application, but with most of its parameters exported.
// They are exported for convenience in creating helper functions, as object
// capabilities aren't needed for testing.
type SimApp struct {
*runtime.App
legacyAmino legacy.Amino
appCodec codec.Codec
txConfig client.TxConfig
interfaceRegistry codectypes.InterfaceRegistry
// keepers
AccountsKeeper accounts.Keeper
AuthKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
StakingKeeper *stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
MintKeeper mintkeeper.Keeper
DistrKeeper distrkeeper.Keeper
GovKeeper *govkeeper.Keeper
UpgradeKeeper *upgradekeeper.Keeper
AuthzKeeper authzkeeper.Keeper
EvidenceKeeper evidencekeeper.Keeper
FeeGrantKeeper feegrantkeeper.Keeper
GroupKeeper groupkeeper.Keeper
NFTKeeper nftkeeper.Keeper
ConsensusParamsKeeper consensuskeeper.Keeper
CircuitBreakerKeeper circuitkeeper.Keeper
PoolKeeper poolkeeper.Keeper
}
func init() {
userHomeDir, err := os.UserHomeDir()
if err != nil {
panic(err)
}
DefaultNodeHome = filepath.Join(userHomeDir, ".simappv2")
}
// AppConfig returns the default app config.
func AppConfig() depinject.Config {
return depinject.Configs(
appConfig, // Alternatively use appconfig.LoadYAML(AppConfigYAML)
)
}
// NewSimApp returns a reference to an initialized SimApp.
func NewSimApp(
logger log.Logger,
appOpts servertypes.AppOptions,
) *SimApp {
homeDir := appOpts.Get("home").(string) // TODO
scRawDb, err := db.NewGoLevelDB("application", filepath.Join(homeDir, "data"), nil)
if err != nil {
panic(err)
}
var (
app = &SimApp{}
appBuilder *runtime.AppBuilder
// merge the AppConfig and other configuration in one config
appConfig = depinject.Configs(
AppConfig(),
depinject.Supply(
logger,
&root.FactoryOptions{
Logger: logger,
RootDir: homeDir,
SSType: 0,
SCType: 0,
SCPruneOptions: &store.PruneOptions{
KeepRecent: 0,
Interval: 0,
},
IavlConfig: &iavl.Config{
CacheSize: 100_000,
SkipFastStorageUpgrade: true,
},
SCRawDB: scRawDb,
},
// appOpts,
// ADVANCED CONFIGURATION
//
// AUTH
//
// For providing a custom function required in auth to generate custom account types
// add it below. By default the auth module uses simulation.RandomGenesisAccounts.
//
// authtypes.RandomGenesisAccountsFn(simulation.RandomGenesisAccounts),
//
// For providing a custom a base account type add it below.
// By default the auth module uses authtypes.ProtoBaseAccount().
//
// func() sdk.AccountI { return authtypes.ProtoBaseAccount() },
//
// For providing a different address codec, add it below.
// By default the auth module uses a Bech32 address codec,
// with the prefix defined in the auth module configuration.
//
// func() address.Codec { return <- custom address codec type -> }
//
// STAKING
//
// For provinding a different validator and consensus address codec, add it below.
// By default the staking module uses the bech32 prefix provided in the auth config,
// and appends "valoper" and "valcons" for validator and consensus addresses respectively.
// When providing a custom address codec in auth, custom address codecs must be provided here as well.
//
// func() runtime.ValidatorAddressCodec { return <- custom validator address codec type -> }
// func() runtime.ConsensusAddressCodec { return <- custom consensus address codec type -> }
//
// MINT
//
// For providing a custom inflation function for x/mint add here your
// custom function that implements the minttypes.InflationCalculationFn
// interface.
),
depinject.Provide(
codec.ProvideInterfaceRegistry,
codec.ProvideAddressCodec,
codec.ProvideProtoCodec,
codec.ProvideLegacyAmino,
),
depinject.Invoke(
std.RegisterInterfaces,
std.RegisterLegacyAminoCodec,
),
)
)
if err := depinject.Inject(appConfig,
&appBuilder,
&app.appCodec,
&app.legacyAmino,
&app.txConfig,
&app.interfaceRegistry,
&app.AuthKeeper,
&app.BankKeeper,
&app.StakingKeeper,
&app.SlashingKeeper,
&app.MintKeeper,
&app.DistrKeeper,
&app.GovKeeper,
&app.UpgradeKeeper,
&app.AuthzKeeper,
&app.EvidenceKeeper,
&app.FeeGrantKeeper,
&app.GroupKeeper,
&app.NFTKeeper,
&app.ConsensusParamsKeeper,
&app.CircuitBreakerKeeper,
&app.PoolKeeper,
); err != nil {
panic(err)
}
app.App, err = appBuilder.Build()
if err != nil {
panic(err)
}
/**** Module Options ****/
// RegisterUpgradeHandlers is used for registering any on-chain upgrades.
app.RegisterUpgradeHandlers()
// TODO (here or in runtime/v2)
// wire simulation manager
// wire snapshot manager
// wire unordered tx manager
if err := app.LoadLatest(); err != nil {
panic(err)
}
return app
}
// AppCodec returns SimApp's app codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
func (app *SimApp) AppCodec() codec.Codec {
return app.appCodec
}
// InterfaceRegistry returns SimApp's InterfaceRegistry.
func (app *SimApp) InterfaceRegistry() codectypes.InterfaceRegistry {
return app.interfaceRegistry
}
// TxConfig returns SimApp's TxConfig
func (app *SimApp) TxConfig() client.TxConfig {
return app.txConfig
}
func (app *SimApp) GetConsensusAuthority() string {
return app.ConsensusParamsKeeper.GetAuthority()
}

46
simapp/v2/default.nix Normal file
View File

@ -0,0 +1,46 @@
{ lib
, buildGoApplication
, rocksdb
, stdenv
, static ? stdenv.hostPlatform.isStatic
, rev ? "dev"
}:
let
pname = "simd";
version = "v0.0.1";
tags = [ "ledger" "netgo" "rocksdb" "grocksdb_no_link" ];
ldflags = lib.concatStringsSep "\n" ([
"-X github.com/cosmos/cosmos-sdk/version.Name=${pname}"
"-X github.com/cosmos/cosmos-sdk/version.AppName=${pname}"
"-X github.com/cosmos/cosmos-sdk/version.Version=${version}"
"-X github.com/cosmos/cosmos-sdk/version.BuildTags=${lib.concatStringsSep "," tags}"
"-X github.com/cosmos/cosmos-sdk/version.Commit=${rev}"
]);
in
buildGoApplication rec {
inherit pname version ldflags tags;
src = ./.;
pwd = src;
modules = ./gomod2nix.toml;
subPackages = [ "simd" ];
doCheck = false;
buildInputs = [ rocksdb ];
CGO_ENABLED = "1";
CGO_LDFLAGS =
if static then "-lrocksdb -pthread -lstdc++ -ldl -lzstd -lsnappy -llz4 -lbz2 -lz"
else if stdenv.hostPlatform.isWindows then "-lrocksdb-shared"
else "-lrocksdb -pthread -lstdc++ -ldl";
postFixup = lib.optionalString stdenv.isDarwin ''
${stdenv.cc.targetPrefix}install_name_tool -change "@rpath/librocksdb.8.dylib" "${rocksdb}/lib/librocksdb.dylib" $out/bin/${pname}
'';
meta = with lib; {
description = "example chain binary in cosmos-sdk repo";
homepage = "https://github.com/cosmos/cosmos-sdk";
license = licenses.asl20;
mainProgram = pname + stdenv.hostPlatform.extensions.executable;
platforms = platforms.all;
};
}

10
simapp/v2/export.go Normal file
View File

@ -0,0 +1,10 @@
package simapp
import (
servertypes "github.com/cosmos/cosmos-sdk/server/types"
)
// ExportAppStateAndValidators exports the state of the application for a genesis file.
func (app *SimApp) ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (servertypes.ExportedApp, error) {
panic("not implemented")
}

View File

@ -0,0 +1,48 @@
package simapp
import (
"errors"
authtypes "cosmossdk.io/x/auth/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)
var _ authtypes.GenesisAccount = (*SimGenesisAccount)(nil)
// SimGenesisAccount defines a type that implements the GenesisAccount interface
// to be used for simulation accounts in the genesis state.
type SimGenesisAccount struct {
*authtypes.BaseAccount
// vesting account fields
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"` // total vesting coins upon initialization
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"` // delegated vested coins at time of delegation
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"` // delegated vesting coins at time of delegation
StartTime int64 `json:"start_time" yaml:"start_time"` // vesting start time (UNIX Epoch time)
EndTime int64 `json:"end_time" yaml:"end_time"` // vesting end time (UNIX Epoch time)
// module account fields
ModuleName string `json:"module_name" yaml:"module_name"` // name of the module account
ModulePermissions []string `json:"module_permissions" yaml:"module_permissions"` // permissions of module account
}
// Validate checks for errors on the vesting and module account parameters
func (sga SimGenesisAccount) Validate() error {
if !sga.OriginalVesting.IsZero() {
if sga.StartTime >= sga.EndTime {
return errors.New("vesting start-time cannot be before end-time")
}
}
if sga.ModuleName != "" {
ma := authtypes.ModuleAccount{
BaseAccount: sga.BaseAccount, Name: sga.ModuleName, Permissions: sga.ModulePermissions,
}
if err := ma.Validate(); err != nil {
return err
}
}
return sga.BaseAccount.Validate()
}

298
simapp/v2/go.mod Normal file
View File

@ -0,0 +1,298 @@
module cosmossdk.io/simapp/v2
go 1.22.2
require (
cosmossdk.io/api v0.7.5
cosmossdk.io/client/v2 v2.0.0-20230630094428-02b760776860
cosmossdk.io/collections v0.4.0 // indirect
cosmossdk.io/core v0.12.1-0.20231114100755-569e3ff6a0d7
cosmossdk.io/depinject v1.0.0-alpha.4
cosmossdk.io/log v1.3.1
cosmossdk.io/math v1.3.0 // indirect
cosmossdk.io/runtime/v2 v2.0.0-00010101000000-000000000000
cosmossdk.io/server/v2 v2.0.0-00010101000000-000000000000 // indirect
cosmossdk.io/server/v2/cometbft v0.0.0-00010101000000-000000000000
cosmossdk.io/store/v2 v2.0.0
cosmossdk.io/tools/confix v0.0.0-20230613133644-0a778132a60f
cosmossdk.io/x/accounts v0.0.0-20240226161501-23359a0b6d91
cosmossdk.io/x/auth v0.0.0-00010101000000-000000000000
cosmossdk.io/x/authz v0.0.0-00010101000000-000000000000
cosmossdk.io/x/bank v0.0.0-20240226161501-23359a0b6d91
cosmossdk.io/x/circuit v0.0.0-20230613133644-0a778132a60f
cosmossdk.io/x/consensus v0.0.0-00010101000000-000000000000
cosmossdk.io/x/distribution v0.0.0-20230925135524-a1bc045b3190
cosmossdk.io/x/evidence v0.0.0-20230613133644-0a778132a60f
cosmossdk.io/x/feegrant v0.0.0-20230613133644-0a778132a60f
cosmossdk.io/x/gov v0.0.0-20231113122742-912390d5fc4a
cosmossdk.io/x/group v0.0.0-00010101000000-000000000000
cosmossdk.io/x/mint v0.0.0-00010101000000-000000000000
cosmossdk.io/x/nft v0.0.0-20230613133644-0a778132a60f
cosmossdk.io/x/protocolpool v0.0.0-20230925135524-a1bc045b3190
cosmossdk.io/x/slashing v0.0.0-00010101000000-000000000000
cosmossdk.io/x/staking v0.0.0-00010101000000-000000000000
cosmossdk.io/x/tx v0.13.3 // indirect
cosmossdk.io/x/upgrade v0.0.0-20230613133644-0a778132a60f
github.com/cometbft/cometbft v1.0.0-alpha.2.0.20240530055211-ae27f7eb3c08
github.com/cosmos/cosmos-db v1.0.2
// this version is not used as it is always replaced by the latest Cosmos SDK version
github.com/cosmos/cosmos-sdk v0.51.0
github.com/cosmos/gogoproto v1.5.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/cobra v1.8.1
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.19.0
github.com/stretchr/testify v1.9.0
golang.org/x/sync v0.7.0
google.golang.org/protobuf v1.34.2
)
require (
buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.1-20240312114316-c0d3497e35d6.1 // indirect
buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.1-20240130113600-88ef6483f90f.1 // indirect
cloud.google.com/go v0.112.2 // indirect
cloud.google.com/go/auth v0.2.2 // indirect
cloud.google.com/go/auth/oauth2adapt v0.2.1 // indirect
cloud.google.com/go/compute/metadata v0.3.0 // indirect
cloud.google.com/go/iam v1.1.7 // indirect
cloud.google.com/go/storage v1.40.0 // indirect
cosmossdk.io/core/testing v0.0.0-00010101000000-000000000000 // indirect
cosmossdk.io/errors v1.0.1 // indirect
cosmossdk.io/server/v2/appmanager v0.0.0-00010101000000-000000000000 // indirect
cosmossdk.io/server/v2/stf v0.0.0-00010101000000-000000000000 // indirect
cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc // indirect
cosmossdk.io/x/accounts/defaults/lockup v0.0.0-20240417181816-5e7aae0db1f5 // indirect
cosmossdk.io/x/epochs v0.0.0-20240522060652-a1ae4c3e0337 // indirect
filippo.io/edwards25519 v1.1.0 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/99designs/keyring v1.2.2 // indirect
github.com/DataDog/datadog-go v4.8.3+incompatible // indirect
github.com/DataDog/zstd v1.5.5 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
github.com/aws/aws-sdk-go v1.51.25 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect
github.com/bits-and-blooms/bitset v1.10.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chzyer/readline v1.5.1 // indirect
github.com/cockroachdb/apd/v2 v2.0.2 // indirect
github.com/cockroachdb/errors v1.11.1 // indirect
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
github.com/cockroachdb/pebble v1.1.0 // indirect
github.com/cockroachdb/redact v1.1.5 // indirect
github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect
github.com/cometbft/cometbft-db v0.12.0 // indirect
github.com/cometbft/cometbft/api v1.0.0-rc.1 // indirect
github.com/cosmos/btcutil v1.0.5 // indirect
github.com/cosmos/cosmos-proto v1.0.0-beta.5 // indirect
github.com/cosmos/crypto v0.0.0-20240309083813-82ed2537802e // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
github.com/cosmos/gogogateway v1.2.0 // indirect
github.com/cosmos/iavl v1.2.0 // indirect
github.com/cosmos/ics23/go v0.10.0 // indirect
github.com/cosmos/ledger-cosmos-go v0.13.3 // indirect
github.com/creachadair/atomicfile v0.3.4 // indirect
github.com/creachadair/tomledit v0.0.26 // indirect
github.com/danieljoos/wincred v1.2.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect
github.com/dgraph-io/badger/v4 v4.2.0 // indirect
github.com/dgraph-io/ristretto v0.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/dvsekhvalnov/jose2go v1.6.0 // indirect
github.com/emicklei/dot v1.6.2 // indirect
github.com/fatih/color v1.17.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/getsentry/sentry-go v0.27.0 // indirect
github.com/go-kit/kit v0.13.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gofrs/uuid v4.4.0+incompatible // indirect
github.com/gogo/googleapis v1.4.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.2.0 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/google/flatbuffers v2.0.8+incompatible // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/orderedcode v0.0.1 // indirect
github.com/google/s2a-go v0.1.7 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
github.com/googleapis/gax-go/v2 v2.12.3 // indirect
github.com/gorilla/handlers v1.5.2 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/gorilla/websocket v1.5.1 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-getter v1.7.4 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-metrics v0.5.3 // indirect
github.com/hashicorp/go-plugin v1.6.1 // indirect
github.com/hashicorp/go-safetemp v1.0.0 // indirect
github.com/hashicorp/go-version v1.6.0 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
github.com/hdevalence/ed25519consensus v0.2.0 // indirect
github.com/huandu/skiplist v1.2.0 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmespath/go-jmespath v0.4.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/klauspost/compress v1.17.8 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/linxGnu/grocksdb v1.8.14 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/manifoldco/promptui v0.9.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/mdp/qrterminal/v3 v3.2.0 // indirect
github.com/minio/highwayhash v1.0.2 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect
github.com/oklog/run v1.1.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/petermattis/goid v0.0.0-20240327183114-c42a807a84ba // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.19.1 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.54.0 // indirect
github.com/prometheus/procfs v0.14.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/rs/cors v1.11.0 // indirect
github.com/rs/zerolog v1.33.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/supranational/blst v0.3.11 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tidwall/btree v1.7.0 // indirect
github.com/ulikunitz/xz v0.5.12 // indirect
github.com/zondax/hid v0.9.2 // indirect
github.com/zondax/ledger-go v0.14.3 // indirect
gitlab.com/yawning/secp256k1-voi v0.0.0-20230925100816-f2616030848b // indirect
gitlab.com/yawning/tuplehash v0.0.0-20230713102510-df83abbf9a02 // indirect
go.etcd.io/bbolt v1.4.0-alpha.0.0.20240404170359-43604f3112c5 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.50.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.50.0 // indirect
go.opentelemetry.io/otel v1.25.0 // indirect
go.opentelemetry.io/otel/metric v1.25.0 // indirect
go.opentelemetry.io/otel/trace v1.25.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/crypto v0.24.0 // indirect
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/oauth2 v0.19.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/term v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/api v0.175.0 // indirect
google.golang.org/genproto v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240515191416-fc5f0ca64291 // indirect
google.golang.org/grpc v1.64.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gotest.tools/v3 v3.5.1 // indirect
pgregory.net/rapid v1.1.0 // indirect
rsc.io/qr v0.2.0 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
)
// Here are the short-lived replace from the SimApp
// Replace here are pending PRs, or version to be tagged
// replace (
// <temporary replace>
// )
// SimApp on main always tests the latest extracted SDK modules importing the sdk
replace (
cosmossdk.io/client/v2 => ../../client/v2
cosmossdk.io/collections => ../../collections
cosmossdk.io/core => ../../core
cosmossdk.io/depinject => ../../depinject
cosmossdk.io/tools/confix => ../../tools/confix
cosmossdk.io/x/accounts => ../../x/accounts
cosmossdk.io/x/accounts/defaults/lockup => ../../x/accounts/defaults/lockup
cosmossdk.io/x/auth => ../../x/auth
cosmossdk.io/x/authz => ../../x/authz
cosmossdk.io/x/bank => ../../x/bank
cosmossdk.io/x/circuit => ../../x/circuit
cosmossdk.io/x/consensus => ../../x/consensus
cosmossdk.io/x/distribution => ../../x/distribution
cosmossdk.io/x/evidence => ../../x/evidence
cosmossdk.io/x/feegrant => ../../x/feegrant
cosmossdk.io/x/gov => ../../x/gov
cosmossdk.io/x/group => ../../x/group
cosmossdk.io/x/mint => ../../x/mint
cosmossdk.io/x/nft => ../../x/nft
cosmossdk.io/x/params => ../../x/params
cosmossdk.io/x/protocolpool => ../../x/protocolpool
cosmossdk.io/x/slashing => ../../x/slashing
cosmossdk.io/x/staking => ../../x/staking
cosmossdk.io/x/tx => ../../x/tx
cosmossdk.io/x/upgrade => ../../x/upgrade
)
// Below are the long-lived replace of the SimApp
replace (
// use cosmos fork of keyring
github.com/99designs/keyring => github.com/cosmos/keyring v1.2.0
// Simapp always use the latest version of the cosmos-sdk
github.com/cosmos/cosmos-sdk => ../../.
// Fix upstream GHSA-h395-qcrw-5vmq and GHSA-3vp4-m3rf-835h vulnerabilities.
// TODO Remove it: https://github.com/cosmos/cosmos-sdk/issues/10409
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.9.1
// replace broken goleveldb
github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
)
// server v2 integration
replace (
cosmossdk.io/api => ../../api
cosmossdk.io/core/testing => ../../core/testing
cosmossdk.io/log => ../../log
cosmossdk.io/runtime/v2 => ../../runtime/v2
cosmossdk.io/server/v2 => ../../server/v2
cosmossdk.io/server/v2/appmanager => ../../server/v2/appmanager
cosmossdk.io/server/v2/cometbft => ../../server/v2/cometbft
cosmossdk.io/server/v2/stf => ../../server/v2/stf
cosmossdk.io/store => ../../store
cosmossdk.io/store/v2 => ../../store/v2
)

1439
simapp/v2/go.sum Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,240 @@
package cmd
import (
"context"
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
dbm "github.com/cosmos/cosmos-db"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/sync/errgroup"
"cosmossdk.io/client/v2/offchain"
"cosmossdk.io/core/transaction"
"cosmossdk.io/log"
runtimev2 "cosmossdk.io/runtime/v2"
"cosmossdk.io/server/v2/cometbft"
"cosmossdk.io/simapp/v2"
confixcmd "cosmossdk.io/tools/confix/cmd"
authcmd "cosmossdk.io/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
// TODO migrate all server dependencies to server/v2
"github.com/cosmos/cosmos-sdk/server"
servertypes "github.com/cosmos/cosmos-sdk/server/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
)
var _ transaction.Codec[transaction.Tx] = &temporaryTxDecoder{}
type temporaryTxDecoder struct {
txConfig client.TxConfig
}
// Decode implements transaction.Codec.
func (t *temporaryTxDecoder) Decode(bz []byte) (transaction.Tx, error) {
return t.txConfig.TxDecoder()(bz)
}
// DecodeJSON implements transaction.Codec.
func (t *temporaryTxDecoder) DecodeJSON(bz []byte) (transaction.Tx, error) {
return t.txConfig.TxJSONDecoder()(bz)
}
func initRootCmd(
rootCmd *cobra.Command,
txConfig client.TxConfig,
_ codectypes.InterfaceRegistry,
_ codec.Codec,
moduleManager *runtimev2.MM,
v1moduleManager *module.Manager,
) {
cfg := sdk.GetConfig()
cfg.Seal()
rootCmd.AddCommand(
genutilcli.InitCmd(moduleManager),
debug.Cmd(),
confixcmd.ConfigCommand(),
startCommand(&temporaryTxDecoder{txConfig}),
// TODO pruning.Cmd(newApp),
// TODO snapshot.Cmd(newApp),
)
// add keybase, auxiliary RPC, query, genesis, and tx child commands
rootCmd.AddCommand(
server.StatusCommand(),
genesisCommand(txConfig, v1moduleManager, appExport),
queryCommand(),
txCommand(),
keys.Commands(),
offchain.OffChain(),
)
}
func startCommand(txCodec transaction.Codec[transaction.Tx]) *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Start the application",
RunE: func(cmd *cobra.Command, args []string) error {
serverCtx := server.GetServerContextFromCmd(cmd)
sa := simapp.NewSimApp(serverCtx.Logger, serverCtx.Viper)
am := sa.App.AppManager
serverCfg := cometbft.Config{CmtConfig: serverCtx.Config, ConsensusAuthority: sa.GetConsensusAuthority()}
cometServer := cometbft.NewCometBFTServer[transaction.Tx](
am,
sa.GetStore(),
sa.GetLogger(),
serverCfg,
txCodec,
)
ctx := cmd.Context()
ctx, cancelFn := context.WithCancel(ctx)
g, _ := errgroup.WithContext(ctx)
g.Go(func() error {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigCh
cancelFn()
cmd.Printf("caught %s signal\n", sig.String())
if err := cometServer.Stop(ctx); err != nil {
cmd.PrintErrln("failed to stop servers:", err)
}
return nil
})
if err := cometServer.Start(ctx); err != nil {
return fmt.Errorf("failed to start servers: %w", err)
}
return g.Wait()
},
}
return cmd
}
// genesisCommand builds genesis-related `simd genesis` command. Users may provide application specific commands as a parameter
func genesisCommand(
txConfig client.TxConfig,
moduleManager *module.Manager,
appExport servertypes.AppExporter,
cmds ...*cobra.Command,
) *cobra.Command {
cmd := genutilcli.Commands(txConfig, moduleManager, appExport)
for _, subCmd := range cmds {
cmd.AddCommand(subCmd)
}
return cmd
}
func queryCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "query",
Aliases: []string{"q"},
Short: "Querying subcommands",
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
rpc.QueryEventForTxCmd(),
server.QueryBlockCmd(),
authcmd.QueryTxsByEventsCmd(),
server.QueryBlocksCmd(),
authcmd.QueryTxCmd(),
server.QueryBlockResultsCmd(),
)
return cmd
}
func txCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "tx",
Short: "Transactions subcommands",
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetSignCommand(),
authcmd.GetSignBatchCommand(),
authcmd.GetMultiSignCommand(),
authcmd.GetMultiSignBatchCmd(),
authcmd.GetValidateSignaturesCommand(),
authcmd.GetBroadcastCommand(),
authcmd.GetEncodeCommand(),
authcmd.GetDecodeCommand(),
authcmd.GetSimulateCmd(),
)
return cmd
}
// appExport creates a new simapp (optionally at a given height) and exports state.
func appExport(
logger log.Logger,
_ dbm.DB,
_ io.Writer,
height int64,
forZeroHeight bool,
jailAllowedAddrs []string,
appOpts servertypes.AppOptions,
modulesToExport []string,
) (servertypes.ExportedApp, error) {
// this check is necessary as we use the flag in x/upgrade.
// we can exit more gracefully by checking the flag here.
homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" {
return servertypes.ExportedApp{}, errors.New("application home not set")
}
viperAppOpts, ok := appOpts.(*viper.Viper)
if !ok {
return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper")
}
// overwrite the FlagInvCheckPeriod
viperAppOpts.Set(server.FlagInvCheckPeriod, 1)
appOpts = viperAppOpts
var simApp *simapp.SimApp
if height != -1 {
simApp = simapp.NewSimApp(logger, appOpts)
if err := simApp.LoadHeight(uint64(height)); err != nil {
return servertypes.ExportedApp{}, err
}
} else {
simApp = simapp.NewSimApp(logger, appOpts)
}
return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport)
}
var tempDir = func() string {
dir, err := os.MkdirTemp("", "simapp")
if err != nil {
dir = simapp.DefaultNodeHome
}
defer os.RemoveAll(dir)
return dir
}

View File

@ -0,0 +1,126 @@
package cmd
import (
"strings"
cmtcfg "github.com/cometbft/cometbft/config"
clientconfig "github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
serverconfig "github.com/cosmos/cosmos-sdk/server/config"
)
// initCometBFTConfig helps to override default CometBFT Config values.
// return cmtcfg.DefaultConfig if no custom configuration is required for the application.
func initCometBFTConfig() *cmtcfg.Config {
cfg := cmtcfg.DefaultConfig()
// only display only error logs by default except for p2p and state
cfg.LogLevel = "*:error,p2p:info,state:info"
// these values put a higher strain on node memory
// cfg.P2P.MaxNumInboundPeers = 100
// cfg.P2P.MaxNumOutboundPeers = 40
return cfg
}
// initAppConfig helps to override default client config template and configs.
// return "", nil if no custom configuration is required for the application.
func initClientConfig() (string, interface{}) {
type GasConfig struct {
GasAdjustment float64 `mapstructure:"gas-adjustment"`
}
type CustomClientConfig struct {
clientconfig.Config `mapstructure:",squash"`
GasConfig GasConfig `mapstructure:"gas"`
}
// Optionally allow the chain developer to overwrite the SDK's default client config.
clientCfg := clientconfig.DefaultConfig()
// The SDK's default keyring backend is set to "os".
// This is more secure than "test" and is the recommended value.
//
// In simapp, we set the default keyring backend to test, as SimApp is meant
// to be an example and testing application.
clientCfg.KeyringBackend = keyring.BackendTest
// Now we set the custom config default values.
customClientConfig := CustomClientConfig{
Config: *clientCfg,
GasConfig: GasConfig{
GasAdjustment: 1.5,
},
}
// The default SDK app template is defined in serverconfig.DefaultConfigTemplate.
// We append the custom config template to the default one.
// And we set the default config to the custom app template.
customClientConfigTemplate := clientconfig.DefaultClientConfigTemplate + strings.TrimSpace(`
# This is default the gas adjustment factor used in tx commands.
# It can be overwritten by the --gas-adjustment flag in each tx command.
gas-adjustment = {{ .GasConfig.GasAdjustment }}
`)
return customClientConfigTemplate, customClientConfig
}
// initAppConfig helps to override default appConfig template and configs.
// return "", nil if no custom configuration is required for the application.
func initAppConfig() (string, interface{}) {
// The following code snippet is just for reference.
// CustomConfig defines an arbitrary custom config to extend app.toml.
// If you don't need it, you can remove it.
// If you wish to add fields that correspond to flags that aren't in the SDK server config,
// this custom config can as well help.
type CustomConfig struct {
CustomField string `mapstructure:"custom-field"`
}
type CustomAppConfig struct {
serverconfig.Config `mapstructure:",squash"`
Custom CustomConfig `mapstructure:"custom"`
}
// Optionally allow the chain developer to overwrite the SDK's default
// server config.
srvCfg := serverconfig.DefaultConfig()
// The SDK's default minimum gas price is set to "" (empty value) inside
// app.toml. If left empty by validators, the node will halt on startup.
// However, the chain developer can set a default app.toml value for their
// validators here.
//
// In summary:
// - if you leave srvCfg.MinGasPrices = "", all validators MUST tweak their
// own app.toml config,
// - if you set srvCfg.MinGasPrices non-empty, validators CAN tweak their
// own app.toml to override, or use this default value.
//
// In simapp, we set the min gas prices to 0.
srvCfg.MinGasPrices = "0stake"
// srvCfg.BaseConfig.IAVLDisableFastNode = true // disable fastnode by default
// Now we set the custom config default values.
customAppConfig := CustomAppConfig{
Config: *srvCfg,
Custom: CustomConfig{
CustomField: "anything",
},
}
// The default SDK app template is defined in serverconfig.DefaultConfigTemplate.
// We append the custom config template to the default one.
// And we set the default config to the custom app template.
customAppTemplate := serverconfig.DefaultConfigTemplate + `
[custom]
# That field will be parsed by server.InterceptConfigsPreRunHandler and held by viper.
# Do not forget to add quotes around the value if it is a string.
custom-field = "{{ .Custom.CustomField }}"`
return customAppTemplate, customAppConfig
}

View File

@ -0,0 +1,174 @@
package cmd
import (
"os"
"github.com/spf13/cobra"
"cosmossdk.io/client/v2/autocli"
clientv2keyring "cosmossdk.io/client/v2/autocli/keyring"
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule/v2"
"cosmossdk.io/core/legacy"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
"cosmossdk.io/runtime/v2"
"cosmossdk.io/simapp/v2"
"cosmossdk.io/x/auth/tx"
authtxconfig "cosmossdk.io/x/auth/tx/config"
"cosmossdk.io/x/auth/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server" // TODO: remove me: https://github.com/cosmos/cosmos-sdk/pull/20412/files#r1622878528
"github.com/cosmos/cosmos-sdk/std"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
"github.com/cosmos/cosmos-sdk/types/module"
)
// NewRootCmd creates a new root command for simd. It is called once in the main function.
func NewRootCmd() *cobra.Command {
var (
autoCliOpts autocli.AppOptions
moduleManager *runtime.MM
v1ModuleManager *module.Manager
clientCtx client.Context
)
if err := depinject.Inject(
depinject.Configs(
simapp.AppConfig(),
depinject.Supply(
log.NewNopLogger(),
simtestutil.NewAppOptionsWithFlagHome(tempDir()),
),
depinject.Provide(
codec.ProvideInterfaceRegistry,
codec.ProvideAddressCodec,
codec.ProvideProtoCodec,
codec.ProvideLegacyAmino,
ProvideClientContext,
ProvideKeyring,
ProvideV1ModuleManager,
),
depinject.Invoke(
std.RegisterInterfaces,
std.RegisterLegacyAminoCodec,
),
),
&autoCliOpts,
&moduleManager,
&v1ModuleManager,
&clientCtx,
); err != nil {
panic(err)
}
rootCmd := &cobra.Command{
Use: "simd",
Short: "simulation app",
SilenceErrors: true,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// set the default command outputs
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
clientCtx = clientCtx.WithCmdContext(cmd.Context()).WithViper("")
clientCtx, err := client.ReadPersistentCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
customClientTemplate, customClientConfig := initClientConfig()
clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig)
if err != nil {
return err
}
if err := client.SetCmdClientContextHandler(clientCtx, cmd); err != nil {
return err
}
customAppTemplate, customAppConfig := initAppConfig()
customCMTConfig := initCometBFTConfig()
return server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customCMTConfig)
},
}
initRootCmd(
rootCmd,
clientCtx.TxConfig,
clientCtx.InterfaceRegistry,
clientCtx.Codec,
moduleManager,
v1ModuleManager)
if err := autoCliOpts.EnhanceRootCommand(rootCmd); err != nil {
panic(err)
}
return rootCmd
}
func ProvideClientContext(
appCodec codec.Codec,
interfaceRegistry codectypes.InterfaceRegistry,
txConfigOpts tx.ConfigOptions,
legacyAmino legacy.Amino,
addressCodec address.Codec,
validatorAddressCodec address.ValidatorAddressCodec,
consensusAddressCodec address.ConsensusAddressCodec,
) client.Context {
var err error
amino, ok := legacyAmino.(*codec.LegacyAmino)
if !ok {
panic("legacy.Amino must be an *codec.LegacyAmino instance for legacy ClientContext")
}
clientCtx := client.Context{}.
WithCodec(appCodec).
WithInterfaceRegistry(interfaceRegistry).
WithLegacyAmino(amino).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithAddressCodec(addressCodec).
WithValidatorAddressCodec(validatorAddressCodec).
WithConsensusAddressCodec(consensusAddressCodec).
WithHomeDir(simapp.DefaultNodeHome).
WithViper("") // uses by default the binary name as prefix
// Read the config to overwrite the default values with the values from the config file
customClientTemplate, customClientConfig := initClientConfig()
clientCtx, err = config.ReadDefaultValuesFromDefaultClientConfig(clientCtx, customClientTemplate, customClientConfig)
if err != nil {
panic(err)
}
// textual is enabled by default, we need to re-create the tx config grpc instead of bank keeper.
txConfigOpts.TextualCoinMetadataQueryFn = authtxconfig.NewGRPCCoinMetadataQueryFn(clientCtx)
txConfig, err := tx.NewTxConfigWithOptions(clientCtx.Codec, txConfigOpts)
if err != nil {
panic(err)
}
clientCtx = clientCtx.WithTxConfig(txConfig)
return clientCtx
}
func ProvideKeyring(clientCtx client.Context, addressCodec address.Codec) (clientv2keyring.Keyring, error) {
kb, err := client.NewKeyringFromBackend(clientCtx, clientCtx.Keyring.Backend())
if err != nil {
return nil, err
}
return keyring.NewAutoCLIKeyring(kb)
}
func ProvideV1ModuleManager(modules map[string]appmodule.AppModule) *module.Manager {
return module.NewManagerFromMap(modules)
}

View File

@ -0,0 +1,43 @@
package cmd_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
"cosmossdk.io/simapp/v2"
"cosmossdk.io/simapp/v2/simdv2/cmd"
"github.com/cosmos/cosmos-sdk/client/flags"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
)
func TestInitCmd(t *testing.T) {
rootCmd := cmd.NewRootCmd()
rootCmd.SetArgs([]string{
"init", // Test the init cmd
"simapp-test", // Moniker
fmt.Sprintf("--%s=%s", cli.FlagOverwrite, "true"), // Overwrite genesis.json, in case it already exists
})
require.NoError(t, svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome))
}
func TestHomeFlagRegistration(t *testing.T) {
homeDir := "/tmp/foo"
rootCmd := cmd.NewRootCmd()
rootCmd.SetArgs([]string{
"query",
fmt.Sprintf("--%s", flags.FlagHome),
homeDir,
})
require.NoError(t, svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome))
result, err := rootCmd.Flags().GetString(flags.FlagHome)
require.NoError(t, err)
require.Equal(t, result, homeDir)
}

19
simapp/v2/simdv2/main.go Normal file
View File

@ -0,0 +1,19 @@
package main
import (
"fmt"
"os"
"cosmossdk.io/simapp/v2"
"cosmossdk.io/simapp/v2/simdv2/cmd"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
)
func main() {
rootCmd := cmd.NewRootCmd()
if err := svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome); err != nil {
fmt.Fprintln(rootCmd.OutOrStderr(), err)
os.Exit(1)
}
}

51
simapp/v2/upgrades.go Normal file
View File

@ -0,0 +1,51 @@
package simapp
import (
"context"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/core/store"
"cosmossdk.io/x/accounts"
protocolpooltypes "cosmossdk.io/x/protocolpool/types"
upgradetypes "cosmossdk.io/x/upgrade/types"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
)
// UpgradeName defines the on-chain upgrade name for the sample SimApp upgrade
// from v0.50.x to v0.51.x
//
// NOTE: This upgrade defines a reference implementation of what an upgrade
// could look like when an application is migrating from Cosmos SDK version
// v0.50.x to v0.51.x.
const UpgradeName = "v050-to-v051"
func (app *SimApp) RegisterUpgradeHandlers() {
app.UpgradeKeeper.SetUpgradeHandler(
UpgradeName,
func(ctx context.Context, _ upgradetypes.Plan, fromVM appmodule.VersionMap) (appmodule.VersionMap, error) {
return app.ModuleManager().RunMigrations(ctx, fromVM)
},
)
upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk()
if err != nil {
panic(err)
}
if upgradeInfo.Name == UpgradeName && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo.Height) {
storeUpgrades := store.StoreUpgrades{
Added: []string{
accounts.ModuleName,
protocolpooltypes.ModuleName,
},
Deleted: []string{
crisistypes.ModuleName, // The SDK discontinued the crisis module in v0.51.0
},
}
// configure store loader that checks if version == upgradeHeight and applies store upgrades
_ = storeUpgrades
// app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades))
}
}

View File

@ -3,6 +3,7 @@ package keeper
import (
"bytes"
"context"
"errors"
"fmt"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
@ -76,10 +77,17 @@ func (k Keeper) UpdateParams(ctx context.Context, msg *types.MsgUpdateParams) (*
}
paramsProto, err := k.ParamsStore.Get(ctx)
var params cmttypes.ConsensusParams
if err != nil {
return nil, err
if errors.Is(err, collections.ErrNotFound) {
params = cmttypes.ConsensusParams{}
} else {
return nil, err
}
} else {
params = cmttypes.ConsensusParamsFromProto(paramsProto)
}
params := cmttypes.ConsensusParamsFromProto(paramsProto)
nextParams := params.Update(&consensusParams)

View File

@ -167,8 +167,7 @@ func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion }
// BeginBlock returns the begin blocker for the distribution module.
func (am AppModule) BeginBlock(ctx context.Context) error {
c := sdk.UnwrapSDKContext(ctx) // TODO: remove and use context.Context after including the comet service
return am.keeper.BeginBlocker(c)
return am.keeper.BeginBlocker(ctx)
}
// AppModuleSimulation functions

View File

@ -21,7 +21,6 @@ import (
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
@ -70,9 +69,13 @@ func displayInfo(dst io.Writer, info printInfo) error {
return err
}
type hasDefaultGenesis interface {
DefaultGenesis() map[string]json.RawMessage
}
// InitCmd returns a command that initializes all files needed for Tendermint
// and the respective application.
func InitCmd(mm *module.Manager) *cobra.Command {
func InitCmd(mm hasDefaultGenesis) *cobra.Command {
cmd := &cobra.Command{
Use: "init [moniker]",
Short: "Initialize private validator, p2p, genesis, and application configuration files",