cli

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 3, 2024 License: Apache-2.0 Imports: 65 Imported by: 0

Documentation

Overview

Package network implements and exposes a fully operational in-process Tendermint test network that consists of at least one or potentially many validators. This test network can be used primarily for integration tests or unit test suites.

The test network utilizes SimApp as the ABCI application and uses all the modules defined in the Cosmos SDK. An in-process test network can be configured with any number of validators as well as account funds and even custom genesis state.

when creating a test network, a series of Validator objects are returned. Each Validator object has useful information such as their address and public key. A Validator will also provide its RPC, P2P, and API addresses that can be useful for integration testing. In addition, a Tendermint local RPC client is also provided which can be handy for making direct RPC calls to Tendermint.

Note, due to limitations in concurrency and the design of the RPC layer in Tendermint, only the first Validator object will have an RPC and API client exposed. Due to this exact same limitation, only a single test network can exist at a time. A caller must be certain it calls Cleanup after it no longer needs the network.

A typical testing flow might look like the following:

type IntegrationTestSuite struct {
	suite.Suite

	cfg     testutil.Config
	network *testutil.Network
}

func (s *IntegrationTestSuite) SetupSuite() {
	s.T().Log("setting up integration test suite")

	cfg := testutil.DefaultConfig()
	cfg.NumValidators = 1

	s.cfg = cfg
	s.network = testutil.New(s.T(), cfg)

	_, err := s.network.WaitForHeight(1)
	s.Require().NoError(err)
}

func (s *IntegrationTestSuite) TearDownSuite() {
	s.T().Log("tearing down integration test suite")

	// This is important and must be called to ensure other tests can create
	// a network!
	s.network.Cleanup()
}

func (s *IntegrationTestSuite) TestQueryBalancesRequestHandlerFn() {
	val := s.network.Validators[0]
	baseURL := val.APIAddress

	// Use baseURL to make API HTTP requests or use val.RPCClient to make direct
	// Tendermint RPC calls.
	// ...
}

func TestIntegrationTestSuite(t *testing.T) {
	suite.Run(t, new(IntegrationTestSuite))
}

Index

Constants

View Source
const (
	// EncodingTypeJSON defines the types are JSON encoded or need to be encoded using JSON.
	EncodingTypeJSON = iota
	// EncodingTypeProto defines the types are proto encoded or need to be encoded using proto.
	EncodingTypeProto
)

Variables

View Source
var DEFAULT_TX_OPTIONS = execTxOptions{
	Fees:             sdk.NewCoins(sdk.NewCoin(denoms.NIBI, sdk.NewInt(1000))),
	Gas:              2000000,
	SkipConfirmation: true,
	BroadcastMode:    flags.BroadcastSync,
	CanFail:          false,
	KeyringBackend:   keyring.BackendTest,
}

Functions

func ExecQuery

func ExecQuery(
	clientCtx client.Context,
	cmd *cobra.Command,
	args []string,
	result codec.ProtoMarshaler,
	opts ...ExecQueryOption,
) error

ExecQuery executes a CLI query onto the provided Network.

func FillWalletFromValidator

func FillWalletFromValidator(
	addr sdk.AccAddress, balance sdk.Coins, val *Validator, feesDenom string,
) error

FillWalletFromValidator fills the wallet with some coins that come from the validator.

func LogMnemonic added in v0.21.9

func LogMnemonic(l Logger, secret string)

LogMnemonic logs a secret to the network's logger for debugging and manual testing

func NewAccount

func NewAccount(network *Network, uid string) sdk.AccAddress

NewAccount Creates a new account with a random mnemonic, stores the mnemonic in the keyring, and returns the address.

args:

  • network: the network in which to create the account and key
  • uid: a unique identifier to ensure duplicate accounts are not created

ret:

  • addr: the address of the new account

func NewKeyring added in v0.21.9

func NewKeyring(t *testing.T) (
	kring keyring.Keyring,
	algo keyring.SignatureAlgo,
	nodeDirName string,
)

func QueryOracleExchangeRate

func QueryOracleExchangeRate(clientCtx client.Context, pair asset.Pair) (*oracletypes.QueryExchangeRateResponse, error)

func QuerySudoers added in v0.21.0

func QuerySudoers(clientCtx client.Context) (*sudotypes.QuerySudoersResponse, error)

func QueryTx added in v0.21.0

func QueryTx(ctx client.Context, txHash string) (*sdk.TxResponse, error)

Types

type AppConstructor

type AppConstructor = func(val Validator) servertypes.Application

AppConstructor defines a function which accepts a network configuration and creates an ABCI Application to provide to Tendermint.

func NewAppConstructor added in v0.21.0

func NewAppConstructor(encodingCfg app.EncodingConfig, chainID string) AppConstructor

NewAppConstructor returns a new simapp AppConstructor

type Config

type Config struct {
	Codec             codec.Codec
	LegacyAmino       *codec.LegacyAmino // TODO: Remove!
	InterfaceRegistry codectypes.InterfaceRegistry

	TxConfig         client.TxConfig
	AccountRetriever client.AccountRetriever

	AppConstructor  AppConstructor             // the ABCI application constructor
	GenesisState    map[string]json.RawMessage // custom genesis state to provide
	TimeoutCommit   time.Duration              // TimeoutCommit: the consensus commitment timeout.
	ChainID         string                     // the network chain-id
	NumValidators   int                        // the total number of validators to create and bond
	Mnemonics       []string                   // custom user-provided validator operator mnemonics
	BondDenom       string                     // the staking bond denomination
	MinGasPrices    string                     // the minimum gas prices each validator will accept
	AccountTokens   sdkmath.Int                // the amount of unique validator tokens (e.g. 1000node0)
	StakingTokens   sdkmath.Int                // the amount of tokens each validator has available to stake
	BondedTokens    sdkmath.Int                // the amount of tokens each validator stakes
	StartingTokens  sdk.Coins                  // Additional tokens to be added to the starting block to validators
	PruningStrategy string                     // the pruning strategy each validator will have
	EnableTMLogging bool                       // enable Tendermint logging to STDOUT
	CleanupDir      bool                       // remove base temporary directory during cleanup
	SigningAlgo     string                     // signing algorithm for keys
	KeyringOptions  []keyring.Option           // keyring configuration options
	RPCAddress      string                     // RPC listen address (including port)
	APIAddress      string                     // REST API listen address (including port)
	GRPCAddress     string                     // GRPC server listen address (including port)
}

Config: Defines the parameters needed to start a local test network.

func BuildNetworkConfig

func BuildNetworkConfig(appGenesis app.GenesisState) Config

BuildNetworkConfig returns a configuration for a local in-testing network

func (*Config) AbsorbListenAddresses added in v0.21.9

func (cfg *Config) AbsorbListenAddresses(val *Validator)

AbsorbListenAddresses ensures that the listening addresses for an active node are set on the network config.

func (*Config) AbsorbServerConfig added in v0.21.9

func (cfg *Config) AbsorbServerConfig(srvCfg *serverconfig.Config)

func (*Config) AbsorbTmConfig added in v0.21.9

func (cfg *Config) AbsorbTmConfig(tmCfg *tmconfig.Config)

type EncodingType

type EncodingType int

EncodingType defines the encoding methodology for requests and responses.

type ExecQueryOption

type ExecQueryOption func(queryOption *queryOptions)

ExecQueryOption defines a type which customizes a CLI query operation.

func WithQueryEncodingType

func WithQueryEncodingType(e EncodingType) ExecQueryOption

WithQueryEncodingType defines how the response of the CLI query should be decoded.

type ExecTxOption

type ExecTxOption func(*execTxOptions)

func WithTxOptions added in v0.21.9

func WithTxOptions(newOptions TxOptionChanges) ExecTxOption

type Logger added in v0.21.0

type Logger interface {
	Log(args ...interface{})
	Logf(format string, args ...interface{})
}

Logger is a network logger interface that exposes testnet-level Log() methods for an in-process testing network This is not to be confused with logging that may happen at an individual node or validator level

type Network

type Network struct {
	BaseDir    string
	Config     Config
	Validators []*Validator
	Logger     Logger
}

Network defines a in-process testing network. It is primarily intended for client and integration testing. The Network struct can spawn any number of validators, each with its own RPC and API clients.

### Constraints

  1. Only the first validator will have a functional RPC and API server/client.
  2. Due to constraints in Tendermint's JSON-RPC implementation, only one test network can run at a time. For this reason, it's essential to invoke `Network.Cleanup` after testing to allow other tests to create networks.

func New added in v0.21.0

func New(logger Logger, baseDir string, cfg Config) (*Network, error)

New creates a new Network for integration tests.

func (*Network) BroadcastMsgs added in v0.21.9

func (chain *Network) BroadcastMsgs(
	from sdk.AccAddress, msgs ...sdk.Msg,
) (*sdk.TxResponse, error)

func (*Network) Cleanup

func (n *Network) Cleanup()

Cleanup removes the root testing (temporary) directory and stops both the Tendermint and API services. It allows other callers to create and start test networks. This method must be called when a test is finished, typically in a defer.

func (Network) ExecQuery added in v1.0.0

func (chain Network) ExecQuery(
	cmd *cobra.Command,
	args []string,
	result codec.ProtoMarshaler,
	opts ...ExecQueryOption,
) error

func (*Network) ExecTxCmd added in v0.21.9

func (network *Network) ExecTxCmd(
	cmd *cobra.Command, from sdk.AccAddress, args []string, opts ...ExecTxOption,
) (*sdk.TxResponse, error)

func (*Network) LatestHeight

func (n *Network) LatestHeight() (int64, error)

LatestHeight returns the latest height of the network or an error if the query fails or no validators exist.

func (*Network) WaitForDuration

func (n *Network) WaitForDuration(duration time.Duration) error

WaitForDuration waits for at least the duration provided in blockchain time.

func (*Network) WaitForHeight

func (n *Network) WaitForHeight(h int64) (int64, error)

WaitForHeight performs a blocking check where it waits for a block to be committed after a given block. If that height is not reached within a timeout, an error is returned. Regardless, the latest height queried is returned.

func (*Network) WaitForHeightWithTimeout

func (n *Network) WaitForHeightWithTimeout(h int64, t time.Duration) (int64, error)

WaitForHeightWithTimeout is the same as WaitForHeight except the caller can provide a custom timeout.

func (*Network) WaitForNextBlock

func (n *Network) WaitForNextBlock() error

WaitForNextBlock waits for the next block to be committed, returning an error upon failure.

type TxOptionChanges added in v0.21.9

type TxOptionChanges struct {
	BroadcastMode    *string
	CanFail          *bool
	Fees             *sdk.Coins
	Gas              *int64
	KeyringBackend   *string
	SkipConfirmation *bool
}

type Validator

type Validator struct {
	AppConfig *serverconfig.Config
	ClientCtx client.Context
	Ctx       *server.Context
	// Dir is the root directory of the validator node data and config. Passed to the Tendermint config.
	Dir string

	// NodeID is a unique ID for the validator generated when the
	// 'cli.Network' is started.
	NodeID string
	PubKey cryptotypes.PubKey

	// Moniker is a human-readable name that identifies a validator. A
	// moniker is optional and may be empty.
	Moniker string

	// APIAddress is the endpoint that the validator API server binds to.
	// Only the first validator of a 'cli.Network' exposes the full API.
	APIAddress string

	// RPCAddress is the endpoint that the RPC server binds to. Only the
	// first validator of a 'cli.Network' exposes the full API.
	RPCAddress string

	// P2PAddress is the endpoint that the RPC server binds to. The P2P
	// server handles Tendermint peer-to-peer (P2P) networking and is
	// critical for blockchain replication and consensus. It allows nodes
	// to gossip blocks, transactions, and consensus messages. Only the
	// first validator of a 'cli.Network' exposes the full API.
	P2PAddress string

	// Address - account address
	Address sdk.AccAddress

	// ValAddress - validator operator (valoper) address
	ValAddress sdk.ValAddress

	// RPCClient wraps most important rpc calls a client would make to
	// listen for events, test if it also implements events.EventSwitch.
	//
	// RPCClient implementations in "github.com/cometbft/cometbft/rpc" v0.37.2:
	// - rcp.HTTP
	// - rpc.Local
	RPCClient tmclient.Client
	// contains filtered or unexported fields
}

Validator defines an in-process Tendermint validator node. Through this object, a client can make RPC and API calls and interact with any client command or handler.

func (Validator) SecretMnemonic added in v0.21.9

func (val Validator) SecretMnemonic() string

func (Validator) SecretMnemonicSlice added in v0.21.9

func (val Validator) SecretMnemonicSlice() []string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL