剖析Cosmos SDK(六):核心概念(Transactions、Context、Node Client)

煤油灯科技2022-07-15 09:00

交易

交易是由context保存的元数据和sdk.Msgs组成,这些元数据通过模块的Protobuf Msg服务触发模块中的状态变化。

当用户想与应用程序互动并进行状态改变(例如发送硬币)时,他们会创建交易。每个交易的sdk.Msg必须使用与相应账户相关的私钥进行签名,然后再将交易广播到网络上。然后,交易必须包含在一个区块中,经过验证并由网络通过共识程序批准。

类型定义

交易对象是实现Tx接口的Cosmos SDK类型。

// Tx defines the interface a transaction must fulfill.
	Tx interface {
		// Gets the all the transaction's messages.
		GetMsgs() []Msg

		// ValidateBasic does a simple and lightweight validation check that doesn't
		// require access to any other information.
		ValidateBasic() error
	}

它包含以下方法:

  • GetMsgs: 解包交易,并返回包含sdk.Msgs的列表——一个交易可能有一个或多个消息,这些消息由模块开发者定义
  • ValidateBasic:由ABCI消息CheckTx和DeliverTx使用轻量级的、无状态的检查,以确保交易不是无效的。例如,Auth模块的ValidateBasic函数检查其交易是否由正确数量的签名者签署,以及费用是否超过用户的最高限额。请注意,这个函数要区别于sdk.Msg ValidateBasic方法,后者只对消息进行基本的有效性检查。当runTx检查从auth模块创建的交易时,它首先对每个消息运行ValidateBasic,然后运行auth模块AnteHandler,该模块对交易本身调用ValidateBasic。

作为一个开发者,应该很少直接操作Tx,因为Tx实际上是一个用于生成交易的中间类型。相反,开发者应该倾向于使用TxBuilder接口。

签署交易

交易中的每个消息都必须由其GetSigners指定的地址签名。Cosmos SDK目前允许以两种不同的方式签署交易。

SIGN_MODE_DIRECT (首选)

Tx接口最常用的实现是Protobuf Tx消息,它被用于SIGN_MODE_DIRECT:

// Tx is the standard type used for broadcasting transactions.
message Tx {
  // body is the processable content of the transaction
  TxBody body = 1;

  // auth_info is the authorization related content of the transaction,
  // specifically signers, signer modes and fee
  AuthInfo auth_info = 2;

  // signatures is a list of signatures that matches the length and order of
  // AuthInfo's signer_infos to allow connecting signature meta information like
  // public key and signing mode by position.
  repeated bytes signatures = 3;
}

因为Protobuf序列化不是确定性的,所以Cosmos SDK使用一个额外的TxRaw类型来表示一个交易被签名的固定字节。任何用户都可以为交易生成有效的正文和auth_info,并使用Protobuf序列化这两条消息。然后,TxRaw将用户精确的 body 和 auth_info二进制表示固定,分别称为body_bytes和auth_info_bytes。 由交易的所有签名者签名的文档是SignDoc(使用ADR-027 确定性序列化):

// SignDoc is the type used for generating sign bytes for SIGN_MODE_DIRECT.
message SignDoc {
  // body_bytes is protobuf serialization of a TxBody that matches the
  // representation in TxRaw.
  bytes body_bytes = 1;

  // auth_info_bytes is a protobuf serialization of an AuthInfo that matches the
  // representation in TxRaw.
  bytes auth_info_bytes = 2;

  // chain_id is the unique identifier of the chain this transaction targets.
  // It prevents signed transactions from being used on another chain by an
  // attacker
  string chain_id = 3;

  // account_number is the account number of the account in state
  uint64 account_number = 4;
}

一旦被所有签名者签名,body_bytes、auth_info_bytes和签名将被收集到TxRaw中,其序列化字节通过网络广播。

SIGN_MODE_LEGACY_AMINO_JSON

Tx接口的传统实现是来自x/auth的StdTx结构:

// StdTx is the legacy transaction format for wrapping a Msg with Fee and Signatures.
// It only works with Amino, please prefer the new protobuf Tx in types/tx.
// NOTE: the first signature is the fee payer (Signatures must not be nil).
// Deprecated
type StdTx struct {
	Msgs          []sdk.Msg      `json:"msg" yaml:"msg"`
	Fee           StdFee         `json:"fee" yaml:"fee"`
	Signatures    []StdSignature `json:"signatures" yaml:"signatures"`
	Memo          string         `json:"memo" yaml:"memo"`
	TimeoutHeight uint64         `json:"timeout_height" yaml:"timeout_height"`
}

所有签名者签署的文件是StdSignDoc:

// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
// and the Sequence numbers for each signature (prevent
// inchain replay and enforce tx ordering per account).
type StdSignDoc struct {
	AccountNumber uint64            `json:"account_number" yaml:"account_number"`
	Sequence      uint64            `json:"sequence" yaml:"sequence"`
	TimeoutHeight uint64            `json:"timeout_height,omitempty" yaml:"timeout_height"`
	ChainID       string            `json:"chain_id" yaml:"chain_id"`
	Memo          string            `json:"memo" yaml:"memo"`
	Fee           json.RawMessage   `json:"fee" yaml:"fee"`
	Msgs          []json.RawMessage `json:"msgs" yaml:"msgs"`
	Tip           *StdTip           `json:"tip,omitempty" yaml:"tip"`
}

这是用Amino JSON编码成的字节。一旦所有签名被收集到StdTx中,StdTx就会使用Amino JSON进行序列化,这些字节会在网络上广播。

其他签名模式

Cosmos SDK还为特定的使用情况提供了一些其他的签名模式。

sign_mode_direct_aux

SIGN_MODE_DIRECT_AUX是Cosmos SDK v0.46中发布的一种签名模式,针对的是有多个签名者的交易。SIGN_MODE_DIRECT希望每个签名者都签署TxBody和AuthInfo(包括所有其他签名者的签名者信息,即他们的账户序列、公钥和模式信息),而SIGN_MODE_DIRECT_AUX允许N-1签名者只在TxBody和他们自己的签名者信息上签名。此外,每个辅助签名者(即使用SIGN_MODE_DIRECT_AUX的签名者)都不需要在费用上签名。

// SignDocDirectAux is the type used for generating sign bytes for
// SIGN_MODE_DIRECT_AUX.
//
// Since: cosmos-sdk 0.46
message SignDocDirectAux {
  // body_bytes is protobuf serialization of a TxBody that matches the
  // representation in TxRaw.
  bytes body_bytes = 1;

  // public_key is the public key of the signing account.
  google.protobuf.Any public_key = 2;

  // chain_id is the identifier of the chain this transaction targets.
  // It prevents signed transactions from being used on another chain by an
  // attacker.
  string chain_id = 3;

  // account_number is the account number of the account in state.
  uint64 account_number = 4;

  // sequence is the sequence number of the signing account.
  uint64 sequence = 5;

  // Tip is the optional tip used for meta-transactions. It should be left
  // empty if the signer is not the tipper for this transaction.
  Tip tip = 6;
}

用例是一个多签名者的交易,其中一个签名者被指定收集所有签名,广播签名和支付费用,其他人只关心交易主体。这通常允许更好的多签名用户体验。如果Alice、Bob和Charlie是3个签名人交易的一部分,那么Alice和Bob都可以使用SIGN_MODE_DIRECT_AUX在TxBody和他们自己的签名人信息上签名(不需要像SIGN_MODE_DIRECT那样额外的步骤来收集其他签名人的签名),在他们的SignDoc中无需指定费用。然后Charlie可以收集Alice和Bob的签名,并通过添加费用来创建最终交易。注意,交易的费用支付者(在我们的例子中是Charlie)必须签署费用,所以必须使用SIGN_MODE_DIRECT或SIGN_MODE_LEGACY_AMINO_JSON。

在交易消费中实现了一个具体的用例:消费者可以使用SIGN_MODE_DIRECT_AUX来指定交易中的小费,而不签署实际的交易费用。然后,费用支付者在小费者想要的TxBody中添加费用,作为支付费用和广播交易的交换,收到小费者的交易提示作为付款。

sign_mode_textual

SIGN_MODE_TEXTUAL是一种新的签名模式,用于在硬件钱包上提供更好的签名体验,它目前仍在实施中。

交易过程

终端用户发送交易的过程是:

  • 决定要放入交易的信息。
  • 使用Cosmos SDK的TxBuilder生成交易。
  • 使用其中一个可用的接口来广播事务。

接下来的段落将按照这个顺序描述这些组件中的每一个。

消息模块

sdk.Msgs不能与ABCI消息混淆,后者定义了Tendermint和应用层之间的交互。

消息(或sdk.Msgs)是特定于模块的对象,在它们所属的模块范围内触发状态转换。模块开发者通过向Protobuf Msg服务添加方法来定义其模块的消息,同时也实现了相应的MsgServer。

每个sdk.Msgs都与一个Protobuf Msg服务RPC相关,定义在每个模块的tx.proto文件内。SDK应用路由器会自动将每个sdk.Msg映射到一个相应的RPC。Protobuf为每个模块的Msg服务生成一个MsgServer接口,而模块开发者需要实现这个接口。这种设计将更多的责任放在了模块开发者身上,允许应用开发者重复使用常用功能,而不必重复实现状态转换逻辑。

虽然消息包含了状态转换逻辑的信息,但一个事务的其他元数据和相关信息都存储在TxBuilder和Context中。

交易的产生

TxBuilder接口包含了与事务生成密切相关的数据,终端用户可以自由设置这些数据以生成所需的事务:

// TxBuilder defines an interface which an application-defined concrete transaction
	// type must implement. Namely, it must be able to set messages, generate
	// signatures, and provide canonical bytes to sign over. The transaction must
	// also know how to encode itself.
	TxBuilder interface {
		GetTx() signing.Tx

		SetMsgs(msgs ...sdk.Msg) error
		SetSignatures(signatures ...signingtypes.SignatureV2) error
		SetMemo(memo string)
		SetFeeAmount(amount sdk.Coins)
		SetFeePayer(feePayer sdk.AccAddress)
		SetGasLimit(limit uint64)
		SetTip(tip *tx.Tip)
		SetTimeoutHeight(height uint64)
		SetFeeGranter(feeGranter sdk.AccAddress)
		AddAuxSignerData(tx.AuxSignerData) error
	}
  • Msgs,交易中包含的信息数组。
  • GasLimit, 用户选择的选项,用于计算他们需要支付多少煤气。
  • Memo,与交易一起发送的说明或评论。
  • FeeAmount,用户愿意支付的最大费用金额。
  • TimeoutHeight, 块的高度,直到交易有效。
  • Signature,交易中所有签名者的签名数组。

由于目前有两种签署交易的签名模式,所以也有两种TxBuilder的实现。

  • wrapper用于创建SIGN_MODE_DIRECT的交易。
  • StdTxBuilder用于SIGN_MODE_LEGACY_AMINO_JSON。

但是,TxBuilder的两个实现应该对终端用户隐藏起来,因为他们应该更喜欢使用总体的TxConfig接口:

// TxConfig defines an interface a client can utilize to generate an
	// application-defined concrete transaction type. The type returned must
	// implement TxBuilder.
	TxConfig interface {
		TxEncodingConfig

		NewTxBuilder() TxBuilder
		WrapTxBuilder(sdk.Tx) (TxBuilder, error)
		SignModeHandler() signing.SignModeHandler
	}

TxConfig是一个用于管理交易的应用程序范围的配置。最重要的是,它持有关于是否用SIGN_MODE_DIRECT或SIGN_MODE_LEGACY_AMINO_JSON签署每个交易的信息。通过调用txBuilder := txConfig.NewTxBuilder(),一个新的TxBuilder将以适当的签名模式创建。

一旦TxBuilder被正确地填充了上述的设置器,TxConfig也将负责正确地对字节进行编码(同样,可以使用SIGN_MODE_DIRECT或SIGN_MODE_LEGACY_AMINO_JSON)。下面是一个如何使用TxEncoder()方法生成和编码交易的伪代码片段。

txBuilder := txConfig.NewTxBuilder()
txBuilder.SetMsgs(...) // and other setters on txBuilder

bz, err := txConfig.TxEncoder()(txBuilder.GetTx())
// bz are bytes to be broadcasted over the network

广播交易

一旦交易字节被生成,目前有三种方法广播方式。

CLI

应用程序开发人员通过创建一个命令行接口、gRPC和/或REST接口来创建应用程序的入口,这些接口通常位于应用程序的./cmd文件夹中找到。这些界面允许用户通过命令行与应用程序互动。

对于命令行界面,模块开发者创建子命令,作为子命令添加到应用程序顶级交易命令TxCmd中。CLI命令实际上将交易处理的所有步骤捆绑在一个简单的命令中:创建消息、生成事务和广播。使用CLI进行的示例如下所示:

simd tx send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake

gRPC

gRPC 是 Cosmos SDK的RPC层的主要组件。 它的主要用途是在模块查询服务的context中。但是,Cosmos SDK还公开了一些其他与模块无关的gRPC服务,其中之一是Tx服务:

syntax = "proto3";
package cosmos.tx.v1beta1;

import "google/api/annotations.proto";
import "cosmos/base/abci/v1beta1/abci.proto";
import "cosmos/tx/v1beta1/tx.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "tendermint/types/block.proto";
import "tendermint/types/types.proto";

option go_package                       = "github.com/cosmos/cosmos-sdk/types/tx";

// Service defines a gRPC service for interacting with transactions.
service Service {
  // Simulate simulates executing a transaction for estimating gas usage.
  rpc Simulate(SimulateRequest) returns (SimulateResponse) {
    option (google.api.http) = {
      post: "/cosmos/tx/v1beta1/simulate"
      body: "*"
    };
  }
  // GetTx fetches a tx by hash.
  rpc GetTx(GetTxRequest) returns (GetTxResponse) {
    option (google.api.http).get = "/cosmos/tx/v1beta1/txs/{hash}";
  }
  // BroadcastTx broadcast transaction.
  rpc BroadcastTx(BroadcastTxRequest) returns (BroadcastTxResponse) {
    option (google.api.http) = {
      post: "/cosmos/tx/v1beta1/txs"
      body: "*"
    };
  }
  // GetTxsEvent fetches txs by event.
  rpc GetTxsEvent(GetTxsEventRequest) returns (GetTxsEventResponse) {
    option (google.api.http).get = "/cosmos/tx/v1beta1/txs";
  }
  // GetBlockWithTxs fetches a block with decoded txs.
  //
  // Since: cosmos-sdk 0.45.2
  rpc GetBlockWithTxs(GetBlockWithTxsRequest) returns (GetBlockWithTxsResponse) {
    option (google.api.http).get = "/cosmos/tx/v1beta1/txs/block/{height}";
  }
}

// GetTxsEventRequest is the request type for the Service.TxsByEvents
// RPC method.
message GetTxsEventRequest {
  // events is the list of transaction event type.
  repeated string events = 1;
  // pagination defines a pagination for the request.
  cosmos.base.query.v1beta1.PageRequest pagination = 2;
  OrderBy                               order_by   = 3;
}

// OrderBy defines the sorting order
enum OrderBy {
  // ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults to ASC in this case.
  ORDER_BY_UNSPECIFIED = 0;
  // ORDER_BY_ASC defines ascending order
  ORDER_BY_ASC = 1;
  // ORDER_BY_DESC defines descending order
  ORDER_BY_DESC = 2;
}

// GetTxsEventResponse is the response type for the Service.TxsByEvents
// RPC method.
message GetTxsEventResponse {
  // txs is the list of queried transactions.
  repeated cosmos.tx.v1beta1.Tx txs = 1;
  // tx_responses is the list of queried TxResponses.
  repeated cosmos.base.abci.v1beta1.TxResponse tx_responses = 2;
  // pagination defines a pagination for the response.
  cosmos.base.query.v1beta1.PageResponse pagination = 3;
}

// BroadcastTxRequest is the request type for the Service.BroadcastTxRequest
// RPC method.
message BroadcastTxRequest {
  // tx_bytes is the raw transaction.
  bytes         tx_bytes = 1;
  BroadcastMode mode     = 2;
}

// BroadcastMode specifies the broadcast mode for the TxService.Broadcast RPC method.
enum BroadcastMode {
  // zero-value for mode ordering
  BROADCAST_MODE_UNSPECIFIED = 0;
  // BROADCAST_MODE_BLOCK defines a tx broadcasting mode where the client waits for
  // the tx to be committed in a block.
  BROADCAST_MODE_BLOCK = 1;
  // BROADCAST_MODE_SYNC defines a tx broadcasting mode where the client waits for
  // a CheckTx execution response only.
  BROADCAST_MODE_SYNC = 2;
  // BROADCAST_MODE_ASYNC defines a tx broadcasting mode where the client returns
  // immediately.
  BROADCAST_MODE_ASYNC = 3;
}

// BroadcastTxResponse is the response type for the
// Service.BroadcastTx method.
message BroadcastTxResponse {
  // tx_response is the queried TxResponses.
  cosmos.base.abci.v1beta1.TxResponse tx_response = 1;
}

// SimulateRequest is the request type for the Service.Simulate
// RPC method.
message SimulateRequest {
  // tx is the transaction to simulate.
  // Deprecated. Send raw tx bytes instead.
  cosmos.tx.v1beta1.Tx tx = 1 [deprecated = true];
  // tx_bytes is the raw transaction.
  //
  // Since: cosmos-sdk 0.43
  bytes tx_bytes = 2;
}

// SimulateResponse is the response type for the
// Service.SimulateRPC method.
message SimulateResponse {
  // gas_info is the information about gas used in the simulation.
  cosmos.base.abci.v1beta1.GasInfo gas_info = 1;
  // result is the result of the simulation.
  cosmos.base.abci.v1beta1.Result result = 2;
}

// GetTxRequest is the request type for the Service.GetTx
// RPC method.
message GetTxRequest {
  // hash is the tx hash to query, encoded as a hex string.
  string hash = 1;
}

// GetTxResponse is the response type for the Service.GetTx method.
message GetTxResponse {
  // tx is the queried transaction.
  cosmos.tx.v1beta1.Tx tx = 1;
  // tx_response is the queried TxResponses.
  cosmos.base.abci.v1beta1.TxResponse tx_response = 2;
}

// GetBlockWithTxsRequest is the request type for the Service.GetBlockWithTxs
// RPC method.
//
// Since: cosmos-sdk 0.45.2
message GetBlockWithTxsRequest {
  // height is the height of the block to query.
  int64 height = 1;
  // pagination defines a pagination for the request.
  cosmos.base.query.v1beta1.PageRequest pagination = 2;
}

// GetBlockWithTxsResponse is the response type for the Service.GetBlockWithTxs method.
//
// Since: cosmos-sdk 0.45.2
message GetBlockWithTxsResponse {
  // txs are the transactions in the block.
  repeated cosmos.tx.v1beta1.Tx txs = 1;
  .tendermint.types.BlockID block_id = 2;
  .tendermint.types.Block   block    = 3;
  // pagination defines a pagination for the response.
  cosmos.base.query.v1beta1.PageResponse pagination = 4;
}

Tx服务公开了一些实用功能,如模拟交易或查询交易,还有一种方法用于广播交易。

REST

每个gRPC方法都有其相应的REST端点,使用gRPC-gateway生成。因此,除了使用gRPC,还可以使用HTTP在POST /cosmos/tx/v1beta1/txs端点上广播相同的交易。

Tendermint RPC

上面介绍的三种方法实际上是对Tendermint RPC /broadcast_tx_{async,sync,commit}端点的高级抽象。这意味着可以直接使用Tendermint RPC端点来广播交易。


Context

Context是一个数据结构,旨在从一个函数传递到另一个函数,携带关于应用程序当前状态的信息。它提供了对分支存储的访问(整个状态的安全分支)以及有用的对象和信息,如gasMeter、区块高度、共识参数等等。

Context的定义

Cosmos SDK Context是一个自定义的数据结构,它包含Go的stdlib context作为其基础,并在其定义中拥有许多特定于Cosmos SDK的其他类型。Context对于交易处理来说是不可或缺的,因为它允许模块在多存储中轻松访问各自的存储,并检索交易性的内容,如Header和气体表。

/*
Context is an immutable object contains all information needed to
process a request.

It contains a context.Context object inside if you want to use that,
but please do not over-use it. We try to keep all data structured
and standard additions here would be better just to add to the Context struct
*/
type Context struct {
	baseCtx       context.Context
	ms            MultiStore
	header        tmproto.Header
	headerHash    tmbytes.HexBytes
	chainID       string
	txBytes       []byte
	logger        log.Logger
	voteInfo      []abci.VoteInfo
	gasMeter      GasMeter
	blockGasMeter GasMeter
	checkTx       bool
	recheckTx     bool // if recheckTx == true, then checkTx must also be true
	minGasPrice   DecCoins
	consParams    *tmproto.ConsensusParams
	eventManager  *EventManager
	priority      int64 // The tx priority, only relevant in CheckTx
}
  • 基本context:基本类型是Go Context,在下面的Go Context Package部分将进一步解释。
  • Multistore:每个应用程序的BaseApp都包含一个CommitMultiStore,它是在创建Context时提供的。调用KVStore()和TransientStore()方法允许模块使用其独特的StoreKey来获取各自的KVStore。
  • Header:是一个区块链类型。它携带关于区块链状态的重要信息,如区块高度和当前区块的提议者。
  • Header Hash:当前区块头哈希,在abci.RequestBeginBlock 期间获取。
  • 链ID:区块所属的区块链的唯一识别号。
  • Transaction Bytes:正在使用context处理的交易的[]字节表示。每个交易在其整个生命周期中被Cosmos SDK和共识引擎(例如Tendermint)的不同部分处理,其中一些对交易类型没有任何了解。因此,交易被编入通用的[]字节类型,使用某种编码格式,如Amino。
  • 记录器:来自Tendermint库的一个记录器。模块调用此方法来创建他们自己独特的模块专用记录器。
  • VoteInfo:一个ABCI类型的VoteInfo的列表,其中包括验证者的名字和表明他们是否已经签署了这个区块的布尔值。
  • Gas Meters:具体来说,就是当前正在使用context处理的交易的gasMeter和它所属的整个区块的blockGasMeter。用户指定他们希望为其交易的执行支付多少费用;这些燃气表记录了到目前为止交易或区块中使用了多少燃气。如果燃气表用完了,执行就停止了。
  • CheckTx模式:一个布尔值,表示交易应以CheckTx或DeliverTx模式处理。
  • 最小燃气价格:节点愿意接受的最低天然气价格,以便将交易纳入其区块。这个价格是每个节点单独配置的本地值,因此不应该被用于导致状态转换的序列中的任何函数。
  • 共识参数(Consensus Params):ABCI类型的共识参数,它为区块链指定了某些限制,例如区块的最大气体。
  • 事件管理器:事件管理器允许任何能够访问context的调用者发出事件。模块可以通过定义各种类型和属性来定义模块特定的事件,或者使用 types/中的通用定义。客户端可以订阅或查询这些事件。这些事件在整个DeliverTx、BeginBlock和EndBlock中被收集,并被返回给Tendermint做索引。
  • 优先级:交易的优先级,只在CheckTx中相关。
ctx.EventManager().EmitEvent(sdk.NewEvent(
    sdk.EventTypeMessage,
    sdk.NewAttribute(sdk.AttributeKeyModule, types.AttributeValueCategory)),
)

Go Context包

基本的Context是在Golang Context包中定义的。Context是一个不可改变的数据结构,它跨API和进程中携带请求范围的数据。Context也被设计成可以实现并发,并被用于goroutine。

Context的目的是不可改变的;它们不应该被编辑。相反,惯例是使用With函数从其父级创建一个子级context。例如:

childCtx = parentCtx.WithBlockHeader(header)

Golang context包 文档指导开发人员显式传递context ctx 作为进程的第一个参数。

存储分支

Context包含一个MultiStore,它允许使用CacheMultiStore进行分支和缓存功能(CacheMultiStore中的查询被缓存以避免未来的往返)。每个KVStore都在一个安全和隔离的短暂存储中被分支。进程可以自由地向CacheMultiStore写入变化。如果一个状态转换序列的执行没有问题,存储分支可以在序列结束时提交给底层存储,或者在出错时不考虑它们。Context的使用模式如下:

  • 一个进程从其父进程接收一个Context ctx,它提供了执行该进程所需的信息。
  • ctx.ms是一个分支存储,即多存储的一个分支,这样进程就可以在执行过程中对状态进行修改,而不改变原始ctx.ms。这对于保护底层的多存储是很有用的,以防在执行的某个时刻需要恢复这些改变。
  • 进程在执行过程中可以从ctx中读和写。它可以调用一个子进程,并根据需要将ctx传递给它。
  • 当子进程返回时,它检查结果是成功还是失败。如果是失败,不需要做什么——分支ctx被简单地丢弃。如果成功,对CacheMultiStore的修改可以通过Write()提交到原来的ctx.ms。

例如,这里是baseapp中runTx函数的一个片段:

runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes)
result = app.runMsgs(runMsgCtx, msgs, mode)
result.GasWanted = gasWanted
if mode != runTxModeDeliver {
  return result
}
if result.IsOK() {
  msCache.Write()
}

流程如下:

  • 在事务中的消息调用runMsgs之前,它使用app.cacheTxContext()来分支和缓存context和multistore。
  • runMsgCtx - 带有分支存储的context,在runMsgs中被用来返回结果。
  • 如果进程在checkTxMode中运行,就不需要写变化——结果会立即返回。
  • 如果进程在deliverTxMode中运行,并且结果表明成功地运行了所有的消息,那么分叉的multistore就会被写回原始的。


节点客户端

Cosmos SDK应用程序的主要端点是守护者客户端,也称为全节点客户端。全节点运行状态机,从一个创世文件开始。它连接到运行相同客户端的对等点,以接收和转发交易、阻止提议和签名。全节点由Cosmos SDK定义的应用程序和通过ABCI连接到应用程序的共识引擎组成。

main函数

任何Cosmos SDK应用程序的全节点客户端都是通过运行main函数构建的。客户端通常是通过在应用程序名称后面加上-d后缀来命名的(例如,appd用于名为app的应用程序),主要功能在./appd/cmd/main.go文件中定义。运行这个函数会创建一个带有一组命令的可执行的appd。对于一个名为app的应用程序,主命令是appd start,它启动了全节点。

一般来说,开发者会用以下结构实现main.go函数:

  • 首先,为应用程序实例化一个encodingCodec。
  • 然后,检索配置并设置配置参数。这主要涉及为地址设置Bech32前缀。
// Config is the structure that holds the SDK configuration parameters.
// This could be used to initialize certain configuration parameters for the SDK.
type Config struct {
	fullFundraiserPath  string
	bech32AddressPrefix map[string]string
	txEncoder           TxEncoder
	addressVerifier     func([]byte) error
	mtx                 sync.RWMutex

	// SLIP-44 related
	purpose  uint32
	coinType uint32

	sealed   bool
	sealedch chan struct{}
}
  • 使用cobra,全节点客户端的root命令被创建。之后,使用rootCmd的AddCommand()方法添加应用程序的所有自定义命令。
  • 使用server.AddCommands()方法向rootCmd添加默认的服务器命令。这些命令与上面添加的命令是分开的,因为它们是标准的,在Cosmos SDK层面上定义的。它们应该被所有基于Cosmos SDK的应用程序所共享。它们包括最重要的命令:启动命令。
  • 准备和执行执行器。
// Executor wraps the cobra Command with a nicer Execute method
type Executor struct {
	*cobra.Command
	Exit func(int) // this is os.Exit by default, override in tests
}

请参阅simapp应用程序中的main函数示例,Cosmos SDK的应用程序用于演示目的:

package main

import (
	"os"

	"github.com/cosmos/cosmos-sdk/server"
	svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
	"github.com/cosmos/cosmos-sdk/simapp"
	"github.com/cosmos/cosmos-sdk/simapp/simd/cmd"
)

func main() {
	rootCmd, _ := cmd.NewRootCmd()

	if err := svrcmd.Execute(rootCmd, "", simapp.DefaultNodeHome); err != nil {
		switch e := err.(type) {
		case server.ErrorCode:
			os.Exit(e.Code)

		default:
			os.Exit(1)
		}
	}
}

启动命令

启动命令被定义在Cosmos SDK的/server文件夹中。它被添加到main函数中全节点客户端的根命令中,并由终端用户调用以启动他们的节点。

# For an example app named "app", the following command starts the full-node.
appd start

# Using the Cosmos SDK's own simapp, the following commands start the simapp node.
simd start

作为提醒,全节点由三个概念层组成:网络层、共识层和应用层。前两个通常被捆绑在一个叫做共识引擎(默认为Tendermint Core)的实体中,而第三个是在Cosmos SDK的帮助下定义的状态机。目前,Cosmos SDK使用Tendermint作为默认的共识引擎,这意味着启动命令的实现是为了启动Tendermint节点。

启动命令的流程是非常直接的。首先,它从context中检索配置,以便打开数据库(默认是一个leveldb实例)。这个数据库包含了应用程序的最新已知状态(如果应用程序是第一次启动,则为空)。

有了这个数据库,启动命令使用appCreator函数创建一个新的应用程序实例:

	app := appCreator(ctx.Logger, db, traceWriter, ctx.Viper)

请注意,appCreator是一个满足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

在实践中,应用程序的构造函数是作为appCreator传递的。

// newApp is an appCreator
func (a appCreator) newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
	var cache sdk.MultiStorePersistentCache

	if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
		cache = store.NewCommitKVStoreCacheManager()
	}

	skipUpgradeHeights := make(map[int64]bool)
	for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) {
		skipUpgradeHeights[int64(h)] = true
	}

	pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts)
	if err != nil {
		panic(err)
	}

	snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots")
	snapshotDB, err := dbm.NewDB("metadata", server.GetAppDBBackend(appOpts), snapshotDir)
	if err != nil {
		panic(err)
	}
	snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir)
	if err != nil {
		panic(err)
	}

	snapshotOptions := snapshottypes.NewSnapshotOptions(
		cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval)),
		cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent)),
	)

	return simapp.NewSimApp(
		logger, db, traceStore, true, skipUpgradeHeights,
		cast.ToString(appOpts.Get(flags.FlagHome)),
		cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
		a.encCfg,
		appOpts,
		baseapp.SetPruning(pruningOpts),
		baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))),
		baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))),
		baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))),
		baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))),
		baseapp.SetInterBlockCache(cache),
		baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))),
		baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))),
		baseapp.SetSnapshot(snapshotStore, snapshotOptions),
	)
}

然后,app的实例用于实例化一个新的Tendermint节点:

		tmNode, err = node.New(cfg, ctx.Logger, abciclient.NewLocalCreator(app), genDoc)
		if err != nil {
			return err
		}

Tendermint节点可以用app创建,因为后者满足abci.Application接口(鉴于app扩展了baseapp)。作为node.New方法的一部分,Tendermint确保应用程序的高度(即自创世以来的块数)与Tendermint节点的高度相等。这两个高度之间的差值应该总是负的或空的。如果它是严格的负值,node.New将重放块,直到应用程序的高度达到Tendermint节点的高度。最后,如果应用程序的高度为0,Tendermint节点将在应用程序上调用InitChain来初始化来自创世文件的状态。

一旦Tendermint节点被实例化并与应用程序同步,该节点就可以被启动:

		if err := tmNode.Start(); err != nil {
			return err
		}

启动后,节点将启动其RPC和P2P服务器,并开始拨打对等方。在与对等节点握手期间,如果节点意识到他们领先,它将按顺序查询所有区块以便赶上。然后,它将等待来自验证者的新区块提议和区块签名以便取得进展。


原文链接:https://docs.cosmos.network/main/core/transactions.html

https://docs.cosmos.network/main/core/context.html

https://docs.cosmos.network/main/core/node.html


---煤油灯科技victorlamp.com翻译整理---

你可能也喜欢这些文章