v0.50.8 Latest Latest

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

Go to latest
Published: Jul 15, 2024 License: Apache-2.0 Imports: 67 Imported by: 1,017



Package network implements and exposes a fully operational in-process CometBFT 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 CometBFT local RPC client is also provided which can be handy for making direct RPC calls to CometBFT.

Note, due to limitations in concurrency and the design of the RPC layer in CometBFT, 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 {

	cfg     network.Config
	network *network.Network

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

	cfg := network.DefaultConfig()
	cfg.NumValidators = 1
	s.cfg = cfg

	var err error, err = network.New(s.T(), s.T().TempDir(), cfg)


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!

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

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

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



This section is empty.


This section is empty.


func FreeTCPAddr added in v0.50.0

func FreeTCPAddr() (addr, port string, closeFn func() error, err error)

Get a free address for a test CometBFT server protocol is either tcp, http, etc

func MinimumAppConfig added in v0.47.0

func MinimumAppConfig() depinject.Config

MinimumAppConfig defines the minimum of modules required for a call to New to succeed


type AppConstructor

type AppConstructor = func(val ValidatorI) servertypes.Application

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

type CLILogger added in v0.46.0

type CLILogger struct {
	// contains filtered or unexported fields

CLILogger wraps a cobra.Command and provides command logging methods.

func NewCLILogger added in v0.46.0

func NewCLILogger(cmd *cobra.Command) CLILogger

NewCLILogger creates a new CLILogger.

func (CLILogger) Log added in v0.46.0

func (s CLILogger) Log(args ...interface{})

Log logs given args.

func (CLILogger) Logf added in v0.46.0

func (s CLILogger) Logf(format string, args ...interface{})

Logf logs given args according to a format specifier.

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              // 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
	PruningStrategy  string                     // the pruning strategy each validator will have
	EnableLogging    bool                       // enable 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)
	PrintMnemonic    bool                       // print the mnemonic of first validator as log output for testing

Config defines the necessary configuration used to bootstrap and start an in-process local testing network.

func DefaultConfig

func DefaultConfig(factory TestFixtureFactory) Config

DefaultConfig returns a sane default configuration suitable for nearly all testing requirements.

func DefaultConfigWithAppConfig added in v0.47.0

func DefaultConfigWithAppConfig(appConfig depinject.Config) (Config, error)

type Logger added in v0.46.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 {
	Logger     Logger
	BaseDir    string
	Validators []*Validator

	Config Config

Network defines a local in-process testing network using SimApp. It can be configured to start any number of validators, each with its own RPC and API clients. Typically, this test network would be used in client and integration testing where user input is expected.

Note, due to CometBFT constraints in regards to RPC functionality, there may only be one test network running at a time. Thus, any caller must be sure to Cleanup after testing is finished in order to allow other tests to create networks. In addition, only the first validator will have a valid RPC and API server/client.

func New

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

New creates a new Network for integration tests or in-process testnets run via the CLI

func (*Network) Cleanup

func (n *Network) Cleanup()

Cleanup removes the root testing (temporary) directory and stops both the CometBFT 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) 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) RetryForBlocks added in v0.47.1

func (n *Network) RetryForBlocks(retryFunc func() error, blocks int) error

RetryForBlocks will wait for the next block and execute the function provided. It will do this until the function returns a nil error or until the number of blocks has been reached.

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 TestFixture added in v0.47.0

type TestFixture struct {
	AppConstructor AppConstructor
	GenesisState   map[string]json.RawMessage
	EncodingConfig moduletestutil.TestEncodingConfig

type TestFixtureFactory added in v0.47.0

type TestFixtureFactory = func() TestFixture

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

type Validator

type Validator struct {
	AppConfig  *srvconfig.Config
	ClientCtx  client.Context
	Ctx        *server.Context
	Dir        string
	NodeID     string
	PubKey     cryptotypes.PubKey
	Moniker    string
	APIAddress string
	RPCAddress string
	P2PAddress string
	Address    sdk.AccAddress
	ValAddress sdk.ValAddress
	RPCClient  cmtclient.Client
	// contains filtered or unexported fields

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

func (Validator) GetAppConfig added in v0.47.0

func (v Validator) GetAppConfig() *srvconfig.Config

func (Validator) GetCtx added in v0.47.0

func (v Validator) GetCtx() *server.Context

type ValidatorI added in v0.47.0

type ValidatorI interface {
	GetCtx() *server.Context
	GetAppConfig() *srvconfig.Config

ValidatorI expose a validator's context and configuration

Jump to

Keyboard shortcuts

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