
节点客户端
守护进程或全节点客户端,是基于Cosmos SDK的区块链的核心进程。网络中的参与者运行这个进程来初始化他们的状态机,与其他全节点连接,并在新区块进入时更新他们的状态机。
^ +-------------------------------+ ^
| | | |
| | State-machine = Application | |
| | | | Built with Cosmos SDK
| | ^ + | |
| +----------- | ABCI | ----------+ v
| | + v | ^
| | | |
Blockchain Node | | Consensus | |
| | | |
| +-------------------------------+ | Tendermint Core
| | | |
| | Networking | |
| | | |
v +-------------------------------+ v
区块链全节点以二进制文件的形式出现,一般以-d作为“守护进程”的后缀(如appd表示应用程序或gaiad表示gaia)。这个二进制文件是通过运行放置在./cmd/appd/的简单main.go函数来构建的。这个操作通常是通过Makefile进行的。
侯建主二进制文件后,就可以通过运行start命令来启动节点。这个命令函数主要做三件事:
- 创建app.go中定义的状态机实例。
- 用最新的已知状态初始化state-machine,这些状态是从存储在~/.app/data文件夹中的db中提取的。此时,状态机的高度为appBlockHeight。
创建并启动一个新的Tendermint实例。除其他外,该节点将与它的对等点进行握手。它将从他们那里获得最新的blockHeight,如果它大于本地的appBlockHeight,就重放块来同步到这个高度。如果appBlockHeight为0,则节点从genesis开始,Tendermint通过ABCI向应用程序发送一个InitChain消息,从而触发InitChainer。
核心应用文件
一般来说,状态机的核心被定义在一个叫做app.go的文件中。它主要包含应用程序的类型定义以及创建和初始化应用程序的函数。
应用程序的类型定义
app.go中定义的第一件事是应用程序的类型,它通常由以下部分组成:
- 对baseapp的引用:app.go中定义的自定义应用程序是baseapp的扩展。当一个交易被Tendermint转发到应用程序时,应用程序使用baseapp的方法将其路由到适当的模块。baseapp实现了应用程序的大部分核心逻辑,包括所有ABCI方法和路由逻辑。
- 存储键的列表:包含整个状态的存储,在Cosmos SDK中被实现为一个多存储(即存储的存储)。每个模块使用多存储中的一个或多个存储来保存他们的状态部分。这些存储可以通过应用类型中声明的特定键来访问。这些密钥和保持器是Cosmos SDK的对象能力模型的核心。
- 模块的保持器列表:每个模块都定义了一个叫做keeper的抽象,它处理这个模块的存储的读写。一个模块的keeper方法可以从其他模块中调用(如果授权的话),这就是为什么它们被声明在应用程序的类型中,并作为接口导出到其他模块,以便后者只能访问授权功能。
- 对appCodec的引用:应用程序的appCodec被用来序列化和反序列化数据结构,以便存储它们,因为存储只能持久化[]字节。默认的编解码器是协议缓冲器。
- 对legacyAmino编解码器的引用:Cosmos SDK的某些部分还没有被迁移到使用上面的appCodec,仍然被硬编码的使用Amino。其他部分则明确地使用Amino以实现向后兼容。由于这些原因,应用程序仍然持有对传统的Amino编解码器的引用。请注意,Amino编解码器将在即将发布的SDK中被删除。
- 对模块管理器和基本模块管理器的引用:模块管理器是一个包含应用程序的模块列表的对象。它有助于与这些模块相关的操作,比如注册它们的Msg服务和gRPC查询服务,或者为InitChainer、BeginBlocker和EndBlocker等各种函数设置模块间的执行顺序。
查看simapp的应用类型定义的例子,Cosmos SDK自己的应用用于演示和测试目的:
// 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 {
*baseapp.BaseApp
legacyAmino *codec.LegacyAmino
appCodec codec.Codec
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
// keys to access the substores
keys map[string]*storetypes.KVStoreKey
tkeys map[string]*storetypes.TransientStoreKey
memKeys map[string]*storetypes.MemoryStoreKey
// keepers
AccountKeeper authkeeper.AccountKeeper
BankKeeper bankkeeper.Keeper
CapabilityKeeper *capabilitykeeper.Keeper
StakingKeeper stakingkeeper.Keeper
SlashingKeeper slashingkeeper.Keeper
MintKeeper mintkeeper.Keeper
DistrKeeper distrkeeper.Keeper
GovKeeper govkeeper.Keeper
CrisisKeeper crisiskeeper.Keeper
UpgradeKeeper upgradekeeper.Keeper
ParamsKeeper paramskeeper.Keeper
AuthzKeeper authzkeeper.Keeper
EvidenceKeeper evidencekeeper.Keeper
FeeGrantKeeper feegrantkeeper.Keeper
GroupKeeper groupkeeper.Keeper
NFTKeeper nftkeeper.Keeper
// the module manager
mm *module.Manager
// simulation manager
sm *module.SimulationManager
// module configurator
configurator module.Configurator
}
构造函数
该函数构造一个新应用程序,该应用程序具有上一节中定义的类型。 它必须满足AppCreator签名才能在应用程序守护程序命令的启动命令中使用。
// AppCreator is a function that allows us to lazily initialize an // application using various configurations. AppCreator func(log.Logger, dbm.DB, io.Writer, AppOptions) Application
下面是这个函数执行的主要操作:
- 实例化新的编解码器,并使用基本管理器初始化应用程序的每个模块的编解码器
- 实例化新的应用程序,带着对baseapp实例的引用、一个编解码器和所有适当的存储键。
- 使用应用程序的每个模块的NewKeeper函数,实例化应用程序类型中定义的所有keeper。注意,保持器必须以正确的顺序进行实例化,因为一个模块的NewKeeper可能需要对另一个模块的keeper进行引用。
- 使用应用程序的每个模块的AppModule对象实例化应用程序的模块管理器。
- 使用模块管理器,初始化应用程序的Msg服务、gRPC查询服务、传统的Msg路由和legacy查询路由。当Tendermint通过ABCI将事务转发到应用程序时,它被路由到适当的模块的Msg服务,使用这里定义的路由。同样,当应用程序收到一个gRPC查询请求时,它被路由到相应模块的gRPC查询服务,使用这里定义的gRPC路由。Cosmos SDK仍然支持传统的Msgs和传统的Tendermint查询,它们分别使用传统的Msg路由和传统的查询路由进行路由。
- 使用模块管理器,注册应用程序的模块的不变量。不变量是变量(例如,呆逼的总供应量),在每个区块结束时被评估。检查不变量的过程是通过一个叫做InvariantsRegistry的特殊模块完成的。不变量的值应该等于该模块中定义的预测值。如果该值与预测值不同,将触发不变式注册表中定义的特殊逻辑(通常链被停止)。这对于确保没有关键的错误不被注意并产生难以修复的长期影响非常有用。
- 使用模块管理器,设置应用程序的每个模块的InitGenesis、BeginBlocker和EndBlocker函数之间的执行顺序。注意,不是所有的模块都实现了这些函数。
- 设置应用程序的其余参数:
InitChainer:用于在第一次启动时初始化应用程序。
BeginBlocker, EndBlocker:在每个区块的开始和结束时调用)。
anteHandler:用于处理费用和签名验证。
- 安装商店。
- 返回申请。
请注意,这个函数只创建应用程序的实例,而实际的状态是在节点重新启动时从~/.app/data文件夹中携带过来的,或者在节点首次启动时从创世文件中生成。
查看simapp中的应用程序构造函数示例:Collapse Copy
// NewSimApp returns a reference to an initialized SimApp.
func NewSimApp(
logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool,
homePath string, invCheckPeriod uint, encodingConfig simappparams.EncodingConfig,
appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp),
) *SimApp {
appCodec := encodingConfig.Codec
legacyAmino := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
keys := sdk.NewKVStoreKeys(
authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey,
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey,
evidencetypes.StoreKey, capabilitytypes.StoreKey,
authzkeeper.StoreKey, nftkeeper.StoreKey, group.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
// NOTE: The testingkey is just mounted for testing purposes. Actual applications should
// not include this key.
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey, "testingkey")
// configure state listening capabilities using AppOptions
// we are doing nothing with the returned streamingServices and waitGroup in this case
if _, _, err := streaming.LoadStreamingServices(bApp, appOpts, appCodec, keys); err != nil {
tmos.Exit(err.Error())
}
app := &SimApp{
BaseApp: bApp,
legacyAmino: legacyAmino,
appCodec: appCodec,
interfaceRegistry: interfaceRegistry,
invCheckPeriod: invCheckPeriod,
keys: keys,
tkeys: tkeys,
memKeys: memKeys,
}
app.ParamsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
// set the BaseApp's parameter store
bApp.SetParamStore(app.ParamsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramstypes.ConsensusParamsKeyTable()))
app.CapabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])
// Applications that wish to enforce statically created ScopedKeepers should call `Seal` after creating
// their scoped modules in `NewApp` with `ScopeToModule`
app.CapabilityKeeper.Seal()
// add keepers
app.AccountKeeper = authkeeper.NewAccountKeeper(
appCodec, keys[authtypes.StoreKey], app.GetSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, sdk.Bech32MainPrefix,
)
app.BankKeeper = bankkeeper.NewBaseKeeper(
appCodec, keys[banktypes.StoreKey], app.AccountKeeper, app.GetSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(),
)
stakingKeeper := stakingkeeper.NewKeeper(
appCodec, keys[stakingtypes.StoreKey], app.AccountKeeper, app.BankKeeper, app.GetSubspace(stakingtypes.ModuleName),
)
app.MintKeeper = mintkeeper.NewKeeper(
appCodec, keys[minttypes.StoreKey], app.GetSubspace(minttypes.ModuleName), &stakingKeeper,
app.AccountKeeper, app.BankKeeper, authtypes.FeeCollectorName,
)
app.DistrKeeper = distrkeeper.NewKeeper(
appCodec, keys[distrtypes.StoreKey], app.GetSubspace(distrtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, authtypes.FeeCollectorName,
)
app.SlashingKeeper = slashingkeeper.NewKeeper(
appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.GetSubspace(slashingtypes.ModuleName),
)
app.CrisisKeeper = crisiskeeper.NewKeeper(
app.GetSubspace(crisistypes.ModuleName), invCheckPeriod, app.BankKeeper, authtypes.FeeCollectorName,
)
app.FeeGrantKeeper = feegrantkeeper.NewKeeper(appCodec, keys[feegrant.StoreKey], app.AccountKeeper)
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
app.StakingKeeper = *stakingKeeper.SetHooks(
stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()),
)
app.AuthzKeeper = authzkeeper.NewKeeper(keys[authzkeeper.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper)
groupConfig := group.DefaultConfig()
/*
Example of setting group params:
groupConfig.MaxMetadataLen = 1000
*/
app.GroupKeeper = groupkeeper.NewKeeper(keys[group.StoreKey], appCodec, app.MsgServiceRouter(), app.AccountKeeper, groupConfig)
// register the proposal types
govRouter := govv1beta1.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper))
govConfig := govtypes.DefaultConfig()
/*
Example of setting gov params:
govConfig.MaxMetadataLen = 10000
*/
govKeeper := govkeeper.NewKeeper(
appCodec, keys[govtypes.StoreKey], app.GetSubspace(govtypes.ModuleName), app.AccountKeeper, app.BankKeeper,
&stakingKeeper, govRouter, app.MsgServiceRouter(), govConfig,
)
app.GovKeeper = *govKeeper.SetHooks(
govtypes.NewMultiGovHooks(
// register the governance hooks
),
)
// set the governance module account as the authority for conducting upgrades
app.UpgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath, app.BaseApp, authtypes.NewModuleAddress(govtypes.ModuleName).String())
// RegisterUpgradeHandlers is used for registering any on-chain upgrades
app.RegisterUpgradeHandlers()
app.NFTKeeper = nftkeeper.NewKeeper(keys[nftkeeper.StoreKey], appCodec, app.AccountKeeper, app.BankKeeper)
// create evidence keeper with router
evidenceKeeper := evidencekeeper.NewKeeper(
appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, app.SlashingKeeper,
)
// If evidence needs to be handled for the app, set routes in router here and seal
app.EvidenceKeeper = *evidenceKeeper
/**** Module Options ****/
// NOTE: we may consider parsing `appOpts` inside module constructors. For the moment
// we prefer to be more strict in what arguments the modules expect.
skipGenesisInvariants := cast.ToBool(appOpts.Get(crisis.FlagSkipGenesisInvariants))
// NOTE: Any module instantiated in the module manager that is later modified
// must be passed by reference here.
app.mm = module.NewManager(
genutil.NewAppModule(
app.AccountKeeper, app.StakingKeeper, app.BaseApp.DeliverTx,
encodingConfig.TxConfig,
),
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts),
vesting.NewAppModule(app.AccountKeeper, app.BankKeeper),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
crisis.NewAppModule(&app.CrisisKeeper, skipGenesisInvariants),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
upgrade.NewAppModule(app.UpgradeKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
params.NewAppModule(app.ParamsKeeper),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
)
// 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
// NOTE: capability module's beginblocker must come before any modules using capabilities (e.g. IBC)
app.mm.SetOrderBeginBlockers(
upgradetypes.ModuleName, capabilitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName,
evidencetypes.ModuleName, stakingtypes.ModuleName,
authtypes.ModuleName, banktypes.ModuleName, govtypes.ModuleName, crisistypes.ModuleName, genutiltypes.ModuleName,
authz.ModuleName, feegrant.ModuleName, nft.ModuleName, group.ModuleName,
paramstypes.ModuleName, vestingtypes.ModuleName,
)
app.mm.SetOrderEndBlockers(
crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName,
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName,
slashingtypes.ModuleName, minttypes.ModuleName,
genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName,
feegrant.ModuleName, nft.ModuleName, group.ModuleName,
paramstypes.ModuleName, upgradetypes.ModuleName, vestingtypes.ModuleName,
)
// 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.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
// can do so safely.
app.mm.SetOrderInitGenesis(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName,
slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
genutiltypes.ModuleName, evidencetypes.ModuleName, authz.ModuleName,
feegrant.ModuleName, nft.ModuleName, group.ModuleName,
paramstypes.ModuleName, upgradetypes.ModuleName, vestingtypes.ModuleName,
)
// Uncomment if you want to set a custom migration order here.
// app.mm.SetOrderMigrations(custom order)
app.mm.RegisterInvariants(&app.CrisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
// add test gRPC service for testing gRPC queries in isolation
testdata_pulsar.RegisterQueryServer(app.GRPCQueryRouter(), testdata_pulsar.QueryImpl{})
// create the simulation manager and define the order of the modules for deterministic simulations
//
// NOTE: this is not required apps that don't use the simulator for fuzz testing
// transactions
app.sm = module.NewSimulationManager(
auth.NewAppModule(appCodec, app.AccountKeeper, authsims.RandomGenesisAccounts),
bank.NewAppModule(appCodec, app.BankKeeper, app.AccountKeeper),
capability.NewAppModule(appCodec, *app.CapabilityKeeper),
feegrantmodule.NewAppModule(appCodec, app.AccountKeeper, app.BankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.GovKeeper, app.AccountKeeper, app.BankKeeper),
mint.NewAppModule(appCodec, app.MintKeeper, app.AccountKeeper, nil),
staking.NewAppModule(appCodec, app.StakingKeeper, app.AccountKeeper, app.BankKeeper),
distr.NewAppModule(appCodec, app.DistrKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
slashing.NewAppModule(appCodec, app.SlashingKeeper, app.AccountKeeper, app.BankKeeper, app.StakingKeeper),
params.NewAppModule(app.ParamsKeeper),
evidence.NewAppModule(app.EvidenceKeeper),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
groupmodule.NewAppModule(appCodec, app.GroupKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
nftmodule.NewAppModule(appCodec, app.NFTKeeper, app.AccountKeeper, app.BankKeeper, app.interfaceRegistry),
)
app.sm.RegisterStoreDecoders()
// initialize stores
app.MountKVStores(keys)
app.MountTransientStores(tkeys)
app.MountMemoryStores(memKeys)
// initialize BaseApp
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetEndBlocker(app.EndBlocker)
app.setAnteHandler(encodingConfig.TxConfig, cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents)))
// In v0.46, the SDK introduces _postHandlers_. PostHandlers are like
// antehandlers, but are run _after_ the `runMsgs` execution. They are also
// defined as a chain, and have the same signature as antehandlers.
//
// In baseapp, postHandlers are run in the same store branch as `runMsgs`,
// meaning that both `runMsgs` and `postHandler` state will be committed if
// both are successful, and both will be reverted if any of the two fails.
//
// The SDK exposes a default postHandlers chain, which comprises of only
// one decorator: the Transaction Tips decorator. However, some chains do
// not need it by default, so feel free to comment the next line if you do
// not need tips.
// To read more about tips:
// https://docs.cosmos.network/main/core/tips.html
//
// Please note that changing any of the anteHandler or postHandler chain is
// likely to be a state-machine breaking change, which needs a coordinated
// upgrade.
app.setPostHandler()
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
}
}
return app
}
InitChainer
- InitChainer是一个函数,它从个genesis文件中初始化应用程序的状态(即genesis账户的代币余额)。当应用程序收到来自Tendermint引擎的InitChain消息时,它会被调用,这发生在节点在appBlockHeight == 0时启动(即在genesis)。应用程序必须在其构造函数中通过SetInitChainer方法设置InitChainer。
- 一般来说,InitChainer主要由应用程序的每个模块的InitGenesis函数组成。这是通过调用模块管理器的InitGenesis函数完成的,而模块管理器又会调用它所包含的每个模块的InitGenesis函数。请注意,必须使用模块管理器的SetOrderInitGenesis方法在模块管理器中设置调用模块的InitGenesis函数的顺序。这是在应用程序的构造函数中完成的,SetOrderInitGenesis必须在SetInitChainer之前调用。
请参阅simapp的InitChainer示例:
// InitChainer application update at chain initialization
func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
if err := json.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
BeginBlocker和EndBlocker
Cosmos SDK为开发者提供了实现自动执行代码的可能性,作为他们应用程序的一部分。这是通过两个称为BeginBlocker和EndBlocker的函数实现的。当应用程序分别从Tendermint引擎收到BeginBlock和EndBlock消息时,它们被调用,这发生在每个块的开始和结束。应用程序必须通过SetBeginBlocker和SetEndBlocker方法在其构造函数中设置BeginBlocker和EndBlocker。
一般来说,BeginBlocker和EndBlocker函数大多由应用程序的每个模块的BeginBlock和EndBlock函数组成。这是通过调用模块管理器的BeginBlock和EndBlock函数完成的,而模块管理器又会调用它所包含的每个模块的BeginBlock和EndBlock函数。请注意,模块的BeginBlock和EndBlock函数的调用顺序必须在模块管理器中分别使用SetOrderBeginBlockers和SetOrderEndBlockers方法设置。这是在应用程序的构造函数中通过模块管理器完成的,SetOrderBeginBlockers和SetOrderEndBlockers方法必须在SetBeginBlocker和SetEndBlocker函数之前调用。
作为附带说明,重要的是要记住特定与应用程序的区块链是确定性的。开发者必须注意不要在BeginBlocker或EndBlocker中引入非确定性,还必须注意不要让它们的计算成本太高,因为gas并不限制BeginBlocker和EndBlocker的执行成本。
查看simapp Copy 中的BeginBlocker和EndBlocker 函数示例
// BeginBlocker application updates every begin block
func (app *SimApp) BeginBlocker(ctx sdk.Context, req abci.RequestBeginBlock) abci.ResponseBeginBlock {
return app.mm.BeginBlock(ctx, req)
}
// EndBlocker application updates every end block
func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.ResponseEndBlock {
return app.mm.EndBlock(ctx, req)
}
注册编解码器
EncodingConfig 结构是 app.go 文件的最后一个重要部分。 此结构的目标是定义将在整个应用程序中使用的编解码器。
// EncodingConfig specifies the concrete encoding types to use for a given app.
// This is provided for compatibility between protobuf and amino implementations.
type EncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Codec codec.Codec
TxConfig client.TxConfig
Amino *codec.LegacyAmino
}
下面是对四个字段各自含义的描述:
- InterfaceRegistry。InterfaceRegistry被Protobuf编解码器用来处理使用google.protobuf.Any进行编码和解码(我们也说“解包”)的接口。Any可以被认为是一个包含type_url(实现接口的具体类型名称)和value(其编码字节)的结构。InterfaceRegistry提供了一种注册接口和实现的机制,可以安全地从Any中解包。应用程序的每个模块都实现了RegisterInterfaces方法,该方法可以用来注册模块自己的接口和实现。
可以在ADR-19中阅读更多关于Any的内容。
为了更详细地了解细节,Cosmos SDK使用了Protobuf规范的实现,称为gogoprotobuf。默认情况下,gogo protobuf实现的Any使用全局类型注册将Any中的值解码成具体的Go类型。这引入了一个漏洞,依赖树中的任何恶意模块都可以在全局protobuf注册表中注册一个类型,并导致它被一个在type_url字段中引用的事务加载和解密。
- 编解码器:整个Cosmos SDK使用的默认编解码器。它由用于编码和解码状态的BinaryCodec和用于向用户输出数据的JSONCodec组成(例如在CLI中)。默认情况下,SDK使用Protobuf作为编解码器。
- TxConfig:TxConfig定义了客户端可以利用它来生成一个应用程序定义的具体事务类型的接口。目前,SDK处理两种交易类型:SIGN_MODE_DIRECT(使用Protobuf二进制作为线上编码)和SIGN_MODE_LEGACY_AMINO_JSON(依赖于Amino)。
- Amino:Cosmos SDK的一些遗留部分仍然使用Amino以实现向后兼容。每个模块都公开了一个RegisterLegacyAmino方法来在Amino中注册模块的特定类型。这个Amino编解码器不应该再被应用开发者使用,并将在未来的版本中被移除。
- Cosmos SDK公开了一个MakeTestEncodingConfig函数,用于为应用程序构造函数(NewApp)创建EncodingConfig。它使用Protobuf作为默认的编解码器
注意:这个函数已经废弃了,应该只用于创建一个应用程序或在测试中使用。
请参阅simapp中的MakeTestEncodingConfig示例:
// MakeTestEncodingConfig creates an EncodingConfig for testing. This function
// should be used only in tests or when creating a new app instance (NewApp*()).
// App user shouldn't create new codecs - use the app.AppCodec instead.
// [DEPRECATED]
func MakeTestEncodingConfig() simappparams.EncodingConfig {
encodingConfig := simappparams.MakeTestEncodingConfig()
std.RegisterLegacyAminoCodec(encodingConfig.Amino)
std.RegisterInterfaces(encodingConfig.InterfaceRegistry)
ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino)
ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry)
return encodingConfig
}
模块
模块是Cosmos SDK应用程序的核心和灵魂。它们可以被认为是嵌套在状态机中的状态机。当交易通过ABCI从底层的Tendermint引擎中转到应用程序时,它被baseapp路由到适当的模块以进行处理。这种模式使开发者能够轻松地建立复杂的状态机,因为他们需要的大部分模块往往已经存在。对于开发者来说,构建Cosmos SDK应用的大部分工作都是围绕着构建他们的应用所需要的、尚不存在的自定义模块,并将它们与已经存在的模块整合成一个连贯的应用程序中。在应用程序目录中,标准的做法是将模块存储在x/文件夹中(不要与Cosmos SDK的x/文件夹混淆,其中包含已经构建好的模块)。
应用程序模块接口
模块必须实现Cosmos SDK中定义的接口,AppModuleBasic和AppModule。前者实现了模块的基本非依赖性元素,如编解码器,而后者则处理大部分的模块方法(包括需要引用其他模块的保持器的方法)。按照惯例,AppModule和AppModuleBasic类型都被定义在一个叫做module.go的文件中。
AppModule在模块上公开了一系列有用的方法,便于将模块组合成一个连贯的应用程序。这些方法从模块管理器中调用,模块管理器管理着应用程序的模块集合。
Msg服务
每个模块都定义了两个Protobuf服务:一个Msg服务来处理消息,一个gRPC查询服务来处理查询。如果把模块看作是一个状态机,那么Msg服务就是一组状态转换的RPC方法。每个Protobuf Msg服务方法都与一个Protobuf请求类型1:1相关,该请求类型必须实现sdk.Msg接口。注意,sdk.Msgs被捆绑在事务中,每个事务包含一个或多个消息。
当全节点收到一个有效的事务块时,Tendermint通过DeliverTx将每个事务转发给应用程序。然后,应用程序处理该事务:
- 收到交易后,应用程序首先将其从[]byte中解压。
- 然后,在提取交易中包含的Msg之前,它验证了一些关于交易的事情,如费用支付和签名。
- sdk.Msgs是用Protobuf Anys编码的。通过分析每个Any的type_url,baseapp的msgServiceRouter将sdk.Msg导向相应模块的Msg服务。
- 如果消息被成功处理,状态就会被更新。
模块开发者在构建自己的模块时创建了自定义的Msg服务。一般的做法是在tx.proto文件中定义Msg Protobuf服务。例如,x/bank模块定义了一个服务,有两种方法来转移代币:
// Msg defines the bank Msg service.
service Msg {
// Send defines a method for sending coins from one account to another account.
rpc Send(MsgSend) returns (MsgSendResponse);
// MultiSend defines a method for sending coins from some accounts to other accounts.
rpc MultiSend(MsgMultiSend) returns (MsgMultiSendResponse);
}
服务方法使用keeper来更新模块的状态。
每个模块还应该实现RegisterServices方法作为AppModule接口的一部分。这个方法应该调用由生成的Protobuf代码提供的RegisterMsgServer函数。
gRPC查询服务
gRPC查询服务允许用户使用gRPC查询状态。它们默认是启用的,可以在app.toml里面的grpc.enable和grpc.address字段下进行配置。
gRPC查询服务被定义在模块的Protobuf定义文件中,特别是在query.proto里面。query.proto定义文件公开了一个单一的查询Protobuf服务。每个gRPC查询端点都对应着一个服务方法,以rpc关键字开头,在查询服务中。
Protobuf为每个模块生成一个QueryServer接口,包含所有的服务方法。然后,一个模块的守护者需要通过提供每个服务方法的具体实现来实现这个QueryServer接口。这个具体实现就是相应的gRPC查询终端的处理程序。
最后,每个模块还应该实现作为AppModule接口一部分的RegisterServices方法。这个方法应该调用由生成的Protobuf代码提供的RegisterQueryServer函数。
Keeper
Keeper是其模块存储的守门人。要在一个模块的存储空间中读或写,必须通过它的keeper的方法。这是由Cosmos SDK的对象能力模型保证的。只有持有存储空间钥匙的对象才能访问它,而且只有模块的keeper才能持有模块存储空间的钥匙。
keeper通常被定义在一个叫做keeper.go的文件中。它包含keeper的类型定义和方法。
keeper的类型定义通常包括:
- 多存储中模块存储的密钥。
- 对其他模块keeper的引用。只有当keeper需要访问其他模块的存储空间(从它们的读/写)时才需要。
- 对应用程序的编解码器的引用。keeper需要它在存储结构之前对其进行marshal,或者在检索结构时对其进行unmarshal,因为商店只接受[]byte作为值。
除了类型定义,keeper.go 文件的下一个重要组成部分是 keeper 的构造函数 NewKeeper。这个函数实例化了一个上面定义的类型的新的keeper,该函数使用编解码器、存储密钥和对其他模块的保持器的潜在引用作为参数实例化一个上面定义的类型的新保持器。文件的其余部分定义了keeper的方法,主要是getter和setter。
命令行、gRPC服务和REST接口
每个模块都定义了命令行命令、gRPC服务和REST路由,通过应用程序的接口公开给终端用户。这使得终端用户能够创建模块中定义的信息类型,或查询模块管理的状态子集。
CLI
通常,与模块相关的命令被定义在模块文件夹中一个名为client/cli的文件夹中。CLI将命令分为两类:事务和查询,分别定义在client/cli/tx.go和client/cli/query.go。这两个命令都是建立在Cobra库之上的。
- 事务命令让用户生成新的事务,以便它们可以被包含在一个区块中并最终更新状态。应该为模块中定义的每个消息类型创建一个命令。该命令用终端用户提供的参数调用消息的构造器,并将其包装成一个事务。Cosmos SDK处理签名和其他交易元数据的添加。
- 查询让用户查询由模块定义的状态子集。查询命令将查询转发到应用程序的查询路由器,该路由器将它们路由到所提供的queryRoute参数的适当查询器。
gRPC
gRPC是一个现代开源的高性能RPC框架,支持多种语言。它是外部客户端(如钱包、浏览器和其他后端服务)与节点互动的推荐方式。
每个模块都可以公开gRPC端点,称为服务方法,在模块的Protobuf query.proto文件中定义。服务方法由其名称、输入参数和输出响应来定义。然后该模块需要:
- 在AppModuleBasic上定义RegisterGRPCGatewayRoutes方法,将客户端的gRPC请求连接到模块内的正确处理程序。
- 对于每个服务方法,定义一个相应的处理程序。处理程序实现了为gRPC请求提供服务所需的核心逻辑,它位于keeper/grpc_query.go文件中。
gRPC-gateway REST端点
一些外部客户端可能不希望使用gRPC。在这种情况下,Cosmos SDK提供了一个gRPC网关服务,它将每个gRPC服务暴露为一个对应的REST端点。
REST端点是在Protobuf文件中定义的,与gRPC服务一起,使用Protobuf注释。想要公开REST查询的模块应该在他们的rpc方法中添加google.api.http注解。默认情况下,SDK中定义的所有REST端点都有一个以/cosmos/前缀开始的URL。
Cosmos SDK还提供了一个开发端点,为这些REST端点生成Swagger定义文件。这个端点可以在app.toml配置文件中的api.swagger键下启用。
应用程序接口
接口让终端用户与全节点客户端互动。这意味着从全节点查询数据,或者创建和发送新的事务,由全节点转发并最终包含在一个区块中。
主要的接口是命令行接口。Cosmos SDK应用的CLI是通过聚合应用所使用的每个模块中定义的CLI命令而建立的。一个应用程序的CLI与守护程序(如appd)相同,并定义在一个名为appd/main.go的文件中。该文件包含:
- 一个main()函数,它被执行以建立appd接口客户端。该函数准备每条命令并在构建它们之前将它们添加到rootCmd 中。在appd的根部,该函数添加通用命令,如status、keys和config、查询命令、tx命令和rest-server。
- 查询命令是通过调用queryCmd函数添加的。该函数返回一个Cobra命令,其中包含在应用程序的每个模块中定义的查询命令(从main()函数中以sdk.ModuleClients数组的形式传递),以及一些其他较低级别的查询命令,如块或验证器查询。查询命令是通过使用CLI的appd query [query] 命令来调用的。
- 事务命令是通过调用txCmd函数添加的。与queryCmd类似,该函数返回一个Cobra命令,其中包含应用程序的每个模块中定义的tx命令,以及低级别的tx命令,如事务签名或广播。Tx命令是通过使用CLI的appd tx [tx] 命令来调用的。
查看Cosmos Hub中应用程序主命令行文件的示例:
func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
encodingConfig := gaia.MakeEncodingConfig()
initClientCtx := client.Context{}.
WithCodec(encodingConfig.Marshaler).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.AccountRetriever{}).
WithHomeDir(gaia.DefaultNodeHome).
WithViper("")
rootCmd := &cobra.Command{
Use: "gaiad",
Short: "Stargate Cosmos Hub App",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags())
if err != nil {
return err
}
initClientCtx, err = config.ReadFromClientConfig(initClientCtx)
if err != nil {
return err
}
if err = client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
return err
}
customTemplate, customGaiaConfig := initAppConfig()
return server.InterceptConfigsPreRunHandler(cmd, customTemplate, customGaiaConfig)
},
}
initRootCmd(rootCmd, encodingConfig)
return rootCmd, encodingConfig
}
依赖项和Makefile
go-grpc v1.34.0中引入的一个补丁使得gRPC与gogoproto库不兼容,使得一些gRPC查询出现恐慌。因此,Cosmos SDK要求在go.mod中安装go-grpc <=v1.33.2。
为了确保gRPC的正常工作,强烈建议在应用程序的go.mod中添加以下一行:
replace google.golang.org/grpc => google.golang.org/grpc v1.33.2
这一部分是可选的,因为开发者可以自由选择他们的依赖管理器和项目构建方法。也就是说,目前最常用的版本控制框架是go.mod。它确保整个应用程序中使用的每个库都以正确的版本导入。
下面以Cosmos Hub的go.mod为例进行说明:
module github.com/cosmos/gaia/v7 go 1.17 require ( github.com/cosmos/cosmos-sdk v0.45.1 github.com/cosmos/go-bip39 v1.0.0 github.com/cosmos/ibc-go/v3 v3.0.0 github.com/gorilla/mux v1.8.0 github.com/gravity-devs/liquidity v1.5.0 github.com/ory/dockertest/v3 v3.8.1 github.com/rakyll/statik v0.1.7 github.com/spf13/cast v1.4.1 github.com/spf13/cobra v1.3.0 github.com/spf13/viper v1.10.1 github.com/strangelove-ventures/packet-forward-middleware/v2 v2.1.1 github.com/stretchr/testify v1.7.0 github.com/tendermint/tendermint v0.34.14 github.com/tendermint/tm-db v0.6.4 )
为了构建应用程序,通常使用Makefile。Makefile主要确保go.mod在构建应用程序的两个入口点appd和appd之前运行。
原文链接:https://docs.cosmos.network/main/basics/app-anatomy.html
---煤油灯科技victorlamp.com翻译整理---









