network

package
v8.0.0-...-5b23e30 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2024 License: Apache-2.0 Imports: 56 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

	network *network.Network
}

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

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

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

	baseDir, err := ioutil.TempDir(suite.T().TempDir(), cfg.ChainID)
	suite.Require().NoError(err)
	suite.T().Logf("created temporary directory: %s", baseDir)

	suite.network, err = network.New(suite.T(), baseDir, cfg)
	suite.Require().NoError(err)

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

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

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

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

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FreeTCPAddr

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

func StartInProcess

func StartInProcess(ctx context.Context, errGroup *errgroup.Group, appConstructor AppConstructor, val *Validator) error

StartInProcess creates and starts an in-process local test network.

Types

type AppConstructor

type AppConstructor = func(appConfig *fxcfg.Config, ctx *server.Context) servertypes.Application

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

type Config

type Config struct {
	Codec                codec.Codec
	InterfaceRegistry    codectypes.InterfaceRegistry
	TxConfig             client.TxConfig
	AccountRetriever     client.AccountRetriever
	AppConstructor       AppConstructor             // the ABCI application constructor
	GenesisState         map[string]json.RawMessage // custom gensis state to provide
	TimeoutCommit        time.Duration              // the consensus commitment timeout
	StakingTokens        sdkmath.Int                // the amount of tokens each validator has available to stake
	BondedTokens         sdkmath.Int                // the amount of tokens each validator stakes
	NumValidators        int                        // the total number of validators to create and bond
	Mnemonics            []string                   // custom user-provided validator operator mnemonics
	ChainID              string                     // the network chain-id
	BondDenom            string                     // the staking bond denomination
	MinGasPrices         string                     // the minimum gas prices each validator will accept
	PruningStrategy      string                     // the pruning strategy each validator will have
	RPCAddress           string                     // RPC listen address (including port)
	JSONRPCAddress       string                     // JSON-RPC listen address (including port)
	APIAddress           string                     // REST API listen address (including port)
	GRPCAddress          string                     // GRPC server listen address (including port)
	EnableJSONRPC        bool                       // enable JSON-RPC service
	EnableAPI            bool                       // enable REST API service
	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
	BypassMinFeeMsgTypes []string                   // bypass minimum fee check for the given message types
}

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

type Network

type Network struct {
	BaseDir    string
	Config     Config
	Validators []*Validator
	// contains filtered or unexported fields
}

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 Tendermint 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(t *testing.T, cfg Config) *Network

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 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) GetContext

func (n *Network) GetContext() context.Context

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) TrapSignal

func (n *Network) TrapSignal(group *errgroup.Group)

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.

func (*Network) WaitNumberBlock

func (n *Network) WaitNumberBlock(number int64) (int64, error)

type Validator

type Validator struct {
	AppConfig     *fxcfg.Config
	ClientCtx     client.Context
	Ctx           *server.Context
	NodeID        string
	PubKey        cryptotypes.PubKey
	Address       sdk.AccAddress
	ValAddress    sdk.ValAddress
	RPCClient     tmclient.Client
	JSONRPCClient *ethclient.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 GenerateGenesisAndValidators

func GenerateGenesisAndValidators(baseDir string, cfg *Config, logger log.Logger) ([]*Validator, error)

GenerateGenesisAndValidators

Jump to

Keyboard shortcuts

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