kit

package
v1.39.1 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0, MIT Imports: 131 Imported by: 4

Documentation

Index

Constants

View Source
const (
	TestDealStateFailed     = TestDealState(-1)
	TestDealStateInProgress = TestDealState(0)
	TestDealStateComplete   = TestDealState(1)
)
View Source
const DefaultPresealsPerBootstrapMiner = 2

DefaultPresealsPerBootstrapMiner is the number of preseals that every bootstrap miner has by default. It can be overridden through the PresealSectors option.

View Source
const EnvRunExpensiveTests = "LOTUS_RUN_EXPENSIVE_TESTS"

EnvRunExpensiveTests is the environment variable that needs to be present and set to value "1" to enable running expensive tests outside of CI.

View Source
const EnvRunVeryExpensiveTests = "LOTUS_RUN_VERY_EXPENSIVE_TESTS"

EnvRunVeryExpensiveTests is the environment variable that needs to be present and set to value "1" to enable running very expensive tests outside of CI. A "very expensive" test is one that is expected to take too long to run in a standard CI setup, and should be skipped unless explicitly enabled.

Variables

View Source
var (
	BogusPieceCid1 = cid.MustParse("baga6ea4seaqjtovkwk4myyzj56eztkh5pzsk5upksan6f5outesy62bsvl4dsha")
	BogusPieceCid2 = cid.MustParse("baga6ea4seaqlhznlutptgfwhffupyer6txswamerq5fc2jlwf2lys2mm5jtiaeq")
)

TODO: make a randomiser for this

View Source
var DefaultEnsembleOpts = ensembleOpts{
	// contains filtered or unexported fields
}
View Source
var DefaultNodeOpts = nodeOpts{
	// contains filtered or unexported fields
}

DefaultNodeOpts are the default options that will be applied to test nodes.

View Source
var EventMatrixContract = SolidityContractDef{
	Filename: "contracts/EventMatrix.hex",
	Fn: map[string][]byte{
		"logEventZeroData":             EthFunctionHash("logEventZeroData()"),
		"logEventOneData":              EthFunctionHash("logEventOneData(uint256)"),
		"logEventTwoData":              EthFunctionHash("logEventTwoData(uint256,uint256)"),
		"logEventThreeData":            EthFunctionHash("logEventThreeData(uint256,uint256,uint256)"),
		"logEventFourData":             EthFunctionHash("logEventFourData(uint256,uint256,uint256,uint256)"),
		"logEventOneIndexed":           EthFunctionHash("logEventOneIndexed(uint256)"),
		"logEventTwoIndexed":           EthFunctionHash("logEventTwoIndexed(uint256,uint256)"),
		"logEventThreeIndexed":         EthFunctionHash("logEventThreeIndexed(uint256,uint256,uint256)"),
		"logEventOneIndexedWithData":   EthFunctionHash("logEventOneIndexedWithData(uint256,uint256)"),
		"logEventTwoIndexedWithData":   EthFunctionHash("logEventTwoIndexedWithData(uint256,uint256,uint256)"),
		"logEventThreeIndexedWithData": EthFunctionHash("logEventThreeIndexedWithData(uint256,uint256,uint256,uint256)"),
	},
	Ev: map[string]ethtypes.EthHash{
		"EventZeroData":             EthTopicHash("EventZeroData()"),
		"EventOneData":              EthTopicHash("EventOneData(uint256)"),
		"EventTwoData":              EthTopicHash("EventTwoData(uint256,uint256)"),
		"EventThreeData":            EthTopicHash("EventThreeData(uint256,uint256,uint256)"),
		"EventFourData":             EthTopicHash("EventFourData(uint256,uint256,uint256,uint256)"),
		"EventOneIndexed":           EthTopicHash("EventOneIndexed(uint256)"),
		"EventTwoIndexed":           EthTopicHash("EventTwoIndexed(uint256,uint256)"),
		"EventThreeIndexed":         EthTopicHash("EventThreeIndexed(uint256,uint256,uint256)"),
		"EventOneIndexedWithData":   EthTopicHash("EventOneIndexedWithData(uint256,uint256)"),
		"EventTwoIndexedWithData":   EthTopicHash("EventTwoIndexedWithData(uint256,uint256,uint256)"),
		"EventThreeIndexedWithData": EthTopicHash("EventThreeIndexedWithData(uint256,uint256,uint256,uint256)"),
	},
}
View Source
var EventsContract = SolidityContractDef{
	Filename: "contracts/events.bin",
	Fn: map[string][]byte{
		"log_zero_data":   {0x00, 0x00, 0x00, 0x00},
		"log_zero_nodata": {0x00, 0x00, 0x00, 0x01},
		"log_four_data":   {0x00, 0x00, 0x00, 0x02},
	},
	Ev: map[string]ethtypes.EthHash{},
}

Functions

func AssertFilesEqual

func AssertFilesEqual(t *testing.T, left, right string)

AssertFilesEqual compares two files by blake2b hash equality and fails the test if unequal.

func CalcFuncSignature added in v1.20.0

func CalcFuncSignature(funcName string) []byte

CalcFuncSignature returns the first 4 bytes of the hash of the function name and types

func ComputeContractAddress added in v1.37.0

func ComputeContractAddress(t *testing.T, deployer ethtypes.EthAddress, nonce uint64) ethtypes.EthAddress

ComputeContractAddress computes the address of a contract deployed by the specified address with the specified nonce: keccak256(rlp([deployer, nonce]))[12:], the EVM's CREATE rule.

func CreateRandomFile

func CreateRandomFile(t *testing.T, rseed, size int) (path string)

CreateRandomFile creates a random file with the provided seed and the provided size.

func CurrentDeadlineIndex added in v1.29.0

func CurrentDeadlineIndex(di *dline.Info) uint64

CurrentDeadlineIndex is the deadline index di.CurrentEpoch falls in, which is what the actor enforces.

func DeadlineCloseAfter added in v1.37.0

func DeadlineCloseAfter(di *dline.Info, dlIdx uint64, from abi.ChainEpoch) abi.ChainEpoch

DeadlineCloseAfter returns the first epoch at or after `from` at which deadline dlIdx closes, which is when the actor next settles that deadline's faults and fees.

func DeadlineForHeight added in v1.37.0

func DeadlineForHeight(di *dline.Info, height abi.ChainEpoch) *dline.Info

DeadlineForHeight returns the deadline that height falls in, on di's schedule. Index, Open, Close and Challenge all come from that one deadline, unlike the recorded deadline a miner out of cron reports.

func DeadlineNotAfter added in v1.37.0

func DeadlineNotAfter(di *dline.Info, height abi.ChainEpoch) *dline.Info

DeadlineNotAfter rewinds di by whole proving periods until di.Open <= height. The result keeps di.Index and may already have closed at height, so callers should rely only on Open, PeriodStart and Index.

func EnsembleMinimal

func EnsembleMinimal(t *testing.T, opts ...interface{}) (*TestFullNode, *TestMiner, *Ensemble)

EnsembleMinimal creates and starts an Ensemble with a single full node and a single miner. It does not interconnect nodes nor does it begin mining.

This function supports passing both ensemble and node functional options. Functional options are applied to all nodes.

func EnsembleOneTwo

func EnsembleOneTwo(t *testing.T, opts ...interface{}) (*TestFullNode, *TestMiner, *TestMiner, *Ensemble)

EnsembleOneTwo creates and starts an Ensemble with one full node and two miners. It does not interconnect nodes nor does it begin mining.

This function supports passing both ensemble and node functional options. Functional options are applied to all nodes.

func EnsembleTwoOne

func EnsembleTwoOne(t *testing.T, opts ...interface{}) (*TestFullNode, *TestFullNode, *TestMiner, *Ensemble)

EnsembleTwoOne creates and starts an Ensemble with two full nodes and one miner. It does not interconnect nodes nor does it begin mining.

This function supports passing both ensemble and node functional options. Functional options are applied to all nodes.

func EnsembleWorker added in v1.15.2

func EnsembleWorker(t *testing.T, opts ...interface{}) (*TestFullNode, *TestMiner, *TestWorker, *Ensemble)

func EthAddressForCreate added in v1.37.0

func EthAddressForCreate(t *testing.T, sender address.Address) ethtypes.EthAddress

EthAddressForCreate returns the EVM-space address that the EAM derives sender's contract addresses from: an f410 sender is already in that space, an f1/f3 sender hashes into it.

func EthFunctionHash added in v1.20.0

func EthFunctionHash(sig string) []byte

func EthTopicHash added in v1.20.0

func EthTopicHash(sig string) ethtypes.EthHash

func EvmCalldata added in v1.36.2

func EvmCalldata(sig string, words ...[]byte) []byte

EvmCalldata builds calldata from a function signature and pre-encoded EVM words.

func EvmDecodeUint64 added in v1.36.0

func EvmDecodeUint64(output []byte) (uint64, error)

EvmDecodeUint64 interprets the low 8 bytes of an EVM word as a big-endian uint64. Returns an error if output is shorter than 8 bytes.

func EvmWordBytes added in v1.36.0

func EvmWordBytes(input []byte) []byte

EvmWordBytes right-aligns input into a 32-byte big-endian EVM word. Panics if input is longer than 32 bytes.

func EvmWordFromAddr added in v1.36.0

func EvmWordFromAddr(ctx context.Context, t *testing.T, client *TestFullNode, from address.Address) []byte

EvmWordFromAddr resolves a Filecoin address to its corresponding Ethereum address and returns it as a 32-byte big-endian EVM word.

func EvmWordInt64 added in v1.37.0

func EvmWordInt64(n int64) []byte

EvmWordInt64 encodes n as a two's complement 32-byte big-endian EVM word.

func EvmWordUint64 added in v1.36.0

func EvmWordUint64(n uint64) []byte

EvmWordUint64 encodes n as a 32-byte big-endian EVM word.

func Expensive

func Expensive(t *testing.T)

Expensive marks a test as expensive, skipping it immediately if not running in a CI environment or if the LOTUS_RUN_EXPENSIVE_TESTS environment variable is not set to "1".

func LoadReward19 added in v1.37.0

func LoadReward19(ctx context.Context, t *testing.T, node api.FullNode, store cbor.IpldStore, tsk types.TipSetKey) (*types.Actor, *reward19.State, *reward19.StreamsState)

LoadReward19 loads the v19 reward actor state and streams, checking invariants.

func MakeStableExecute added in v1.34.0

func MakeStableExecute(ctx context.Context, t *testing.T, getTipSet func(t *testing.T) *types.TipSet) func(fn func()) *types.TipSet

MakeStableExecute is a helper that will execute a function required by a test case repeatedly until the tipset observed before is the same as after execution of the function. This helps reduce flakies that come from reorgs between capturing the tipset and executing the function. Unfortunately it doesn't remove the problem entirely as we could have multiple reorgs off the tipset we observe and then back to it, but it should be extremely rare.

func MustActor added in v1.37.0

func MustActor(ctx context.Context, t *testing.T, node api.FullNode, addr address.Address, tsk types.TipSetKey) *types.Actor

func QuietAllLogsExcept added in v1.20.0

func QuietAllLogsExcept(names ...string)

func QuietMiningLogs

func QuietMiningLogs()

func RequireMessageSuccess added in v1.37.0

func RequireMessageSuccess(t *testing.T, lookup *api.MsgLookup)

func SendFunds

func SendFunds(ctx context.Context, t *testing.T, sender *TestFullNode, recipient address.Address, amount abi.TokenAmount)

SendFunds sends funds from the default wallet of the specified sender node to the recipient address.

func SetupAllocation added in v1.32.0

func SetupAllocation(
	ctx context.Context,
	t *testing.T,
	node *TestFullNode,
	minerId uint64,
	dc abi.PieceInfo,
	verifiedClientAddr address.Address,
	expiration abi.ChainEpoch,
	termMax abi.ChainEpoch,
) (clientID abi.ActorID, allocationID verifregtypes13.AllocationId)

func SetupVerifiedClients added in v1.32.0

func SetupVerifiedClients(ctx context.Context, t *testing.T, client *TestFullNode, rootKey *key.Key, verifierKey *key.Key, verifiedClientKeys []*key.Key) (verifierAddr address.Address, ret []address.Address)

SetupVerifiedClients assumes that rootKey has been set in the ensemble's genesis and that verifierKey and verifiedClientKeys exist as accounts. It first sets up the verifier with datacap to allocate, and then allocates datacap to each of the verified clients. It returns the address of the verifier and the addresses of the verified clients.

func TipsetAtOrAfter added in v1.37.0

func TipsetAtOrAfter(ctx context.Context, t *testing.T, node api.FullNode, target abi.ChainEpoch) *types.TipSet

TipsetAtOrAfter skips null epochs and returns the first tipset at or after target.

func VeryExpensive added in v1.28.0

func VeryExpensive(t *testing.T)

VeryExpensive marks a test as VERY expensive, skipping it immediately if the LOTUS_RUN_VERY_EXPENSIVE_TESTS environment variable is not set to "1".

func WaitForMinerQAP added in v1.37.0

func WaitForMinerQAP(ctx context.Context, t *testing.T, client *TestFullNode, maddr address.Address, want uint64, maxWait time.Duration)

WaitForMinerQAP polls the miner's quality-adjusted power (StateMinerPower) until it equals want, failing the test after maxWait. Each poll advances the head ~50 epochs.

Types

type BlockMiner

type BlockMiner struct {
	// contains filtered or unexported fields
}

BlockMiner is a utility that makes a test miner Mine blocks on a timer.

func NewBlockMiner

func NewBlockMiner(t *testing.T, miner *TestMiner) *BlockMiner

func (*BlockMiner) ExpectFailure added in v1.38.0

func (bm *BlockMiner) ExpectFailure(fn func(error))

ExpectFailure hands the next MineBlocksMustPost failure to fn instead of failing the test, for tests of the failure path itself. Block production still stops and the ensemble's failure context is still cancelled with the failure.

func (*BlockMiner) InjectNulls

func (bm *BlockMiner) InjectNulls(rounds abi.ChainEpoch)

InjectNulls injects the specified amount of null rounds in the next mining rounds.

func (*BlockMiner) MineBlocks

func (bm *BlockMiner) MineBlocks(ctx context.Context, blocktime time.Duration)

func (*BlockMiner) MineBlocksMustPost added in v1.14.0

func (bm *BlockMiner) MineBlocksMustPost(ctx context.Context, blocktime time.Duration)

MineBlocksMustPost is like MineBlocks but refuses to mine a block that would take a watched miner past a window PoSt deadline before that miner's PoSt message is in the mempool. Every block mined must succeed. It's a brake that couples chain time to the PoSt scheduler, test chains can produce blocks faster than a scheduler can prove, so without it deadlines pass unproven, sectors fault, and a miner that loses its power can no longer win elections. Use it for tests whose sectors must keep their power across deadlines (onboarding, upgrades, extensions, terminations, fee checks), with managed or unmanaged miners.

Each round:

  • Read the current deadline of every watched miner (the BlockMiner's own and any added with WatchMinerForPost) at the current head.
  • Work out the epoch the next block will land on: the head, plus one, plus any null rounds requested for this round.
  • For each open deadline that epoch would bring too near to its close, wait until that miner's PoSt message is pending in the mempool or already included, so the next block has it.
  • Mine. *On a lost election* (more likely the more power other miners hold) the miner itself counts a null round on the same mining base, so the next attempt lands one epoch later. Before each retry the deadline check runs again for the new landing epoch, across all open deadlines, so a losing streak can't mine past a deadline close without first forcing the PoSt that's due.
  • Null rounds requested by the caller are injected once, on the first attempt; retries rely on the miner's own null count.

A PoSt that has not arrived within postWait, a mining error, or a mined block that never reaches the node's head fails the test and stops block production. The failure goes to postFailure, which for an ensemble's block miner cancels the ensemble's failure context, so waiters on that context return the error rather than wait on a stopped chain.

func (*BlockMiner) MineUntilBlock

func (bm *BlockMiner) MineUntilBlock(ctx context.Context, fn *TestFullNode, cb func(abi.ChainEpoch))

func (*BlockMiner) Pause added in v1.17.1

func (bm *BlockMiner) Pause()

Pause compels the miner to wait for a signal to restart

func (*BlockMiner) Restart added in v1.17.1

func (bm *BlockMiner) Restart()

Restart continues mining after a pause. This will hang if called before pause

func (*BlockMiner) Stop

func (bm *BlockMiner) Stop()

Stop stops the block miner.

func (*BlockMiner) WatchMinerForPost added in v1.27.1

func (bm *BlockMiner) WatchMinerForPost(minerAddr address.Address)

WatchMinerForPost adds a miner to the list of miners that the BlockMiner will watch for window post submissions when using MineBlocksMustPost. This is useful when we have more than just the BlockMiner submitting posts, particularly in the case of UnmanagedMiners which don't participate in block mining.

type CfgOption added in v1.17.1

type CfgOption func(cfg *config.FullNode) error

type ChainPredicate

type ChainPredicate func(set *types.TipSet) bool

ChainPredicate encapsulates a chain condition.

func BlocksMinedByAll added in v1.20.0

func BlocksMinedByAll(miner ...address.Address) ChainPredicate

BlocksMinedByAll returns a ChainPredicate that is satisfied when we observe a tipset including blocks from all the specified miners, in no particular order.

func HeightAtLeast

func HeightAtLeast(target abi.ChainEpoch) ChainPredicate

HeightAtLeast returns a ChainPredicate that is satisfied when the chain height is equal or higher to the target.

type Closer added in v1.19.0

type Closer func()

func CreateRPCServer

func CreateRPCServer(t *testing.T, handler http.Handler, listener net.Listener) (*httptest.Server, multiaddr.Multiaddr, Closer)

type EVM added in v1.20.0

type EVM struct{ *TestFullNode }

EVM groups EVM-related actions.

func (*EVM) AssertAddressBalanceConsistent added in v1.20.0

func (e *EVM) AssertAddressBalanceConsistent(ctx context.Context, addr address.Address) big.Int

AssertAddressBalanceConsistent checks that the balance reported via the Filecoin and Ethereum operations for an f410 address is identical, returning the balance.

func (*EVM) BuildDeployContractTx added in v1.36.2

func (e *EVM) BuildDeployContractTx(ctx context.Context, ethAddr ethtypes.EthAddress, contractPath string) *ethtypes.Eth1559TxArgs

BuildDeployContractTx returns an unsigned Ethereum transaction for deploying the contract bytecode at contractPath from ethAddr.

func (*EVM) ComputeContractAddress added in v1.20.0

func (e *EVM) ComputeContractAddress(deployer ethtypes.EthAddress, nonce uint64) ethtypes.EthAddress

ComputeContractAddress computes the address of a contract deployed by the specified address with the specified nonce.

func (*EVM) DeployContract added in v1.20.0

func (e *EVM) DeployContract(ctx context.Context, sender address.Address, bytecode []byte) eam.CreateReturn

func (*EVM) DeployContractFromFilename added in v1.20.0

func (e *EVM) DeployContractFromFilename(ctx context.Context, binFilename string) (address.Address, address.Address)

func (*EVM) DeployContractFromFilenameWithValue added in v1.20.0

func (e *EVM) DeployContractFromFilenameWithValue(ctx context.Context, binFilename string, value big.Int) (address.Address, address.Address)

func (*EVM) DeployContractWithValue added in v1.20.0

func (e *EVM) DeployContractWithValue(ctx context.Context, sender address.Address, bytecode []byte, value big.Int) eam.CreateReturn

func (*EVM) GetEthBlockFromWait added in v1.20.0

func (e *EVM) GetEthBlockFromWait(ctx context.Context, wait *api.MsgLookup) ethtypes.EthBlock

GetEthBlockFromWait returns and eth block from a wait return. This necessarily goes back one parent in the chain because wait is one block ahead of execution.

func (*EVM) InvokeContractByFuncName added in v1.20.0

func (e *EVM) InvokeContractByFuncName(ctx context.Context, fromAddr address.Address, idAddr address.Address, funcSignature string, inputData []byte) ([]byte, *api.MsgLookup, error)

func (*EVM) InvokeContractByFuncNameExpectExit added in v1.20.0

func (e *EVM) InvokeContractByFuncNameExpectExit(ctx context.Context, fromAddr address.Address, idAddr address.Address, funcSignature string, inputData []byte, exit exitcode.ExitCode)

func (*EVM) InvokeSolidity added in v1.20.0

func (e *EVM) InvokeSolidity(ctx context.Context, sender address.Address, target address.Address, selector []byte, inputData []byte) (*api.MsgLookup, error)

func (*EVM) InvokeSolidityWithValue added in v1.23.0

func (e *EVM) InvokeSolidityWithValue(ctx context.Context, sender address.Address, target address.Address, selector []byte, inputData []byte, value big.Int) (*api.MsgLookup, error)

func (*EVM) LoadEvents added in v1.20.0

func (e *EVM) LoadEvents(ctx context.Context, eventsRoot cid.Cid) []types.Event

LoadEvents loads all events in an event AMT.

func (*EVM) NewAccount added in v1.20.0

func (e *EVM) NewAccount() (*key.Key, ethtypes.EthAddress, address.Address)

func (*EVM) SignLegacyEIP155Transaction added in v1.27.1

func (e *EVM) SignLegacyEIP155Transaction(tx *ethtypes.EthLegacy155TxArgs, privKey []byte, chainID big.Int)

SignLegacyEIP155Transaction signs a legacy Homstead Ethereum transaction in place with the supplied private key.

func (*EVM) SignLegacyHomesteadTransaction added in v1.27.1

func (e *EVM) SignLegacyHomesteadTransaction(tx *ethtypes.EthLegacyHomesteadTxArgs, privKey []byte)

SignLegacyHomesteadTransaction signs a legacy Homstead Ethereum transaction in place with the supplied private key.

func (*EVM) SignTransaction added in v1.20.0

func (e *EVM) SignTransaction(tx *ethtypes.Eth1559TxArgs, privKey []byte)

SignTransaction signs an Ethereum transaction in place with the supplied private key.

func (*EVM) SubmitTransaction added in v1.20.0

func (e *EVM) SubmitTransaction(ctx context.Context, tx ethtypes.EthTransaction) ethtypes.EthHash

SubmitTransaction submits the transaction via the Eth endpoint.

func (*EVM) TransferValueOrFail added in v1.20.0

func (e *EVM) TransferValueOrFail(ctx context.Context, fromAddr address.Address, toAddr address.Address, sendAmount big.Int) *api.MsgLookup

func (*EVM) WaitTransaction added in v1.25.2

func (e *EVM) WaitTransaction(ctx context.Context, hash ethtypes.EthHash) (*ethtypes.EthTxReceipt, error)

type Ensemble

type Ensemble struct {
	// contains filtered or unexported fields
}

Ensemble is a collection of nodes instantiated within a test.

Create a new ensemble with:

ens := kit.NewEnsemble(t, kit.MockProofs())

Create full nodes and miners:

var full TestFullNode
var miner TestMiner
ens.FullNode(&full, opts...)       // populates a full node
ens.Miner(&miner, &full, opts...)  // populates a miner, using the full node as its chain daemon

It is possible to pass functional options to set initial balances, presealed sectors, owner keys, etc.

After the initial nodes are added, call `ens.Start()` to forge genesis and start the network. Mining will NOT be started automatically. It needs to be started explicitly by calling `BeginMining`.

Nodes also need to be connected with one another, either via `ens.Connect()` or `ens.InterconnectAll()`. A common inchantation for simple tests is to do:

ens.InterconnectAll().BeginMining(blocktime)

You can continue to add more nodes, but you must always follow with `ens.Start()` to activate the new nodes.

The API is chainable, so it's possible to do a lot in a very succinct way:

kit.NewEnsemble(t, kit.MockProofs()).FullNode(&full).Miner(&miner, &full).Start().InterconnectAll().BeginMining()

You can also find convenient fullnode:miner presets, such as 1:1, 1:2, and 2:1, e.g.:

kit.EnsembleMinimal(t, kit.MockProofs())
kit.EnsembleOneTwo(t, kit.MockProofs())
kit.EnsembleTwoOne(t, kit.MockProofs())

func NewEnsemble

func NewEnsemble(t *testing.T, opts ...EnsembleOpt) *Ensemble

NewEnsemble instantiates a new blank Ensemble.

func (*Ensemble) AddInactiveMiner added in v1.19.0

func (n *Ensemble) AddInactiveMiner(m *TestMiner)

func (*Ensemble) AddInactiveUnmanagedMiner added in v1.27.1

func (n *Ensemble) AddInactiveUnmanagedMiner(m *TestUnmanagedMiner)

func (*Ensemble) BeginMining

func (n *Ensemble) BeginMining(blocktime time.Duration, miners ...*TestMiner) []*BlockMiner

BeginMining kicks off mining for the specified miners. If nil or 0-length, it will kick off mining for all enrolled and active miners. It also adds a cleanup function to stop all mining operations on test teardown.

func (*Ensemble) BeginMiningMustPost added in v1.14.0

func (n *Ensemble) BeginMiningMustPost(blocktime time.Duration, miners ...*TestMiner) []*BlockMiner

func (*Ensemble) Connect

func (n *Ensemble) Connect(from api.Net, to ...api.Net) *Ensemble

Connect connects one full node to the provided full nodes.

func (*Ensemble) FailureContext added in v1.38.0

func (n *Ensemble) FailureContext(ctx context.Context) context.Context

FailureContext returns a caller-derived context cancelled by a terminal WindowPoSt failure from an unmanaged miner or a MustPost block miner.

func (*Ensemble) FullNode

func (n *Ensemble) FullNode(full *TestFullNode, opts ...NodeOpt) *Ensemble

FullNode enrolls a new full node.

func (*Ensemble) InterconnectAll

func (n *Ensemble) InterconnectAll() *Ensemble

InterconnectAll connects all miners and full nodes to one another.

func (*Ensemble) Miner

func (n *Ensemble) Miner(minerNode *TestMiner, full *TestFullNode, opts ...NodeOpt) *Ensemble

func (*Ensemble) MinerEnroll added in v1.19.0

func (n *Ensemble) MinerEnroll(minerNode *TestMiner, full *TestFullNode, opts ...NodeOpt) *Ensemble

MinerEnroll enrolls a new miner, using the provided full node for chain interactions.

func (*Ensemble) Mocknet added in v1.15.1

func (n *Ensemble) Mocknet() mocknet.Mocknet

Mocknet returns the underlying mocknet.

func (*Ensemble) NewPrivKey added in v1.19.0

func (n *Ensemble) NewPrivKey() (libp2pcrypto.PrivKey, peer.ID)

func (*Ensemble) Start

func (n *Ensemble) Start() *Ensemble

Start starts all enrolled nodes.

func (*Ensemble) UnmanagedMiner added in v1.27.1

func (n *Ensemble) UnmanagedMiner(ctx context.Context, full *TestFullNode, opts ...NodeOpt) (*TestUnmanagedMiner, *Ensemble)

func (*Ensemble) Worker added in v1.15.2

func (n *Ensemble) Worker(minerNode *TestMiner, worker *TestWorker, opts ...NodeOpt) *Ensemble

Worker enrolls a new worker, using the provided full node for chain interactions.

type EnsembleOpt

type EnsembleOpt func(opts *ensembleOpts) error

func Account

func Account(key *key.Key, balance abi.TokenAmount) EnsembleOpt

Account sets up an account at genesis with the specified key and balance.

func GenesisNetworkVersion added in v1.11.2

func GenesisNetworkVersion(nv network.Version) EnsembleOpt

GenesisNetworkVersion sets the network version of genesis.

func LatestActorsAt

func LatestActorsAt(upgradeHeight abi.ChainEpoch) EnsembleOpt

func MockProofs

func MockProofs() EnsembleOpt

MockProofs activates mock proofs for the entire ensemble.

func NetworkName added in v1.32.2

func NetworkName(name string) EnsembleOpt

NetworkName sets the network name for the ensemble in the genesis template.

func RealProofs added in v1.36.2

func RealProofs() EnsembleOpt

RealProofs activates real proofs for the entire ensemble. CI scans for this marker when deciding whether to download proof parameters for an itest.

func RewardSWA added in v1.39.0

func RewardSWA(key *key.Key, timelock abi.ChainEpoch) EnsembleOpt

RewardSWA installs key's account as the reward actor's FIP-0118 stream weight actor at genesis, holding its writes for timelock epochs, so the key can send f02's SWA methods directly. The account is funded with 100 FIL for gas. The genesis network version must be nv29 or later.

func RootVerifier

func RootVerifier(key *key.Key, balance abi.TokenAmount) EnsembleOpt

RootVerifier specifies the key to be enlisted as the verified registry root, as well as the initial balance to be attributed during genesis.

func UpgradeSchedule added in v1.11.2

func UpgradeSchedule(upgrades ...stmgr.Upgrade) EnsembleOpt

func WithRealStorageManager added in v1.36.2

func WithRealStorageManager() EnsembleOpt

WithRealStorageManager keeps the real storage manager wired when using MockProofs. This is useful for tests that exercise the storage-manager API surface without needing real cryptographic proofs.

type EthFilterBuilder added in v1.20.0

type EthFilterBuilder struct {
	// contains filtered or unexported fields
}

func NewEthFilterBuilder added in v1.20.0

func NewEthFilterBuilder() *EthFilterBuilder

func (*EthFilterBuilder) AddressOneOf added in v1.20.0

func (e *EthFilterBuilder) AddressOneOf(as ...ethtypes.EthAddress) *EthFilterBuilder

func (*EthFilterBuilder) BlockHash added in v1.20.0

func (*EthFilterBuilder) Filter added in v1.20.0

func (*EthFilterBuilder) FromBlock added in v1.20.0

func (e *EthFilterBuilder) FromBlock(v string) *EthFilterBuilder

func (*EthFilterBuilder) FromBlockEpoch added in v1.20.0

func (e *EthFilterBuilder) FromBlockEpoch(v abi.ChainEpoch) *EthFilterBuilder

func (*EthFilterBuilder) ToBlock added in v1.20.0

func (e *EthFilterBuilder) ToBlock(v string) *EthFilterBuilder

func (*EthFilterBuilder) ToBlockEpoch added in v1.20.0

func (e *EthFilterBuilder) ToBlockEpoch(v abi.ChainEpoch) *EthFilterBuilder

func (*EthFilterBuilder) Topic1OneOf added in v1.20.0

func (e *EthFilterBuilder) Topic1OneOf(hs ...ethtypes.EthHash) *EthFilterBuilder

func (*EthFilterBuilder) Topic2OneOf added in v1.20.0

func (e *EthFilterBuilder) Topic2OneOf(hs ...ethtypes.EthHash) *EthFilterBuilder

func (*EthFilterBuilder) Topic3OneOf added in v1.20.0

func (e *EthFilterBuilder) Topic3OneOf(hs ...ethtypes.EthHash) *EthFilterBuilder

func (*EthFilterBuilder) Topic4OneOf added in v1.20.0

func (e *EthFilterBuilder) Topic4OneOf(hs ...ethtypes.EthHash) *EthFilterBuilder

type ItestdNotif added in v1.15.1

type ItestdNotif struct {
	NodeType string // api env var name
	TestName string
	Api      string
}

type Libp2p added in v1.19.0

type Libp2p struct {
	PeerID  peer.ID
	PrivKey libp2pcrypto.PrivKey
}

type MinerSubsystem added in v1.11.1

type MinerSubsystem int
const (
	SMining MinerSubsystem = 1 << iota
	SSealing
	SSectorStorage

	MinerSubsystems = 0
)

func (MinerSubsystem) Add added in v1.11.1

func (MinerSubsystem) Has added in v1.11.1

func (ms MinerSubsystem) Has(single MinerSubsystem) bool

type MockCLI

type MockCLI struct {
	// contains filtered or unexported fields
}

func NewMockCLI

func NewMockCLI(ctx context.Context, t *testing.T, cmds []*lcli.Command, nodeType api.NodeType, appFlags ...lcli.Flag) *MockCLI

NewMockCLI builds a CLI app around cmds. It always uses an --api-url flag so that a command can be pointed at a particular node; appFlags adds any further app-level flags the commands read, such as lotus-miner's --actor.

func (*MockCLI) Client

func (c *MockCLI) Client(addr multiaddr.Multiaddr) *MockCLIClient

type MockCLIClient

type MockCLIClient struct {
	// contains filtered or unexported fields
}

MockCLIClient runs commands against a particular node

func (*MockCLIClient) RunCmd

func (c *MockCLIClient) RunCmd(input ...string) string

func (*MockCLIClient) RunCmdRaw

func (c *MockCLIClient) RunCmdRaw(input ...string) (string, error)

func (*MockCLIClient) RunInteractiveCmd

func (c *MockCLIClient) RunInteractiveCmd(cmd []string, interactive []string) string

type MockECFinalityProvider added in v1.35.1

type MockECFinalityProvider struct {
	FinalizedTipSet *types.TipSet
	ThresholdDepth  int
	Err             error
}

MockECFinalityProvider satisfies ecfinality.ECFinalityCalculator (for ChainModuleV2) and eth.ECFinalityProvider (for tipSetResolver), allowing tests to control the EC finality calculator response without the additional cost of running the FRC-0089 calculator across 905 tipsets on every head change when the block time is tiny.

Set FinalizedTipSet and ThresholdDepth to control the response. Set Err to simulate a calculator failure.

func NewMockECFinalityProvider added in v1.35.1

func NewMockECFinalityProvider() *MockECFinalityProvider

func (*MockECFinalityProvider) GetFinalizedTipSet added in v1.35.1

func (m *MockECFinalityProvider) GetFinalizedTipSet(_ context.Context) (*types.TipSet, error)

func (*MockECFinalityProvider) GetStatus added in v1.35.1

type MockF3Backend added in v1.33.0

type MockF3Backend struct {
	Running       bool
	LatestCert    *certs.FinalityCertificate
	LatestCertErr error
	Finalizing    bool
	// contains filtered or unexported fields
}

func NewMockF3Backend added in v1.33.0

func NewMockF3Backend() *MockF3Backend

func (*MockF3Backend) GetCert added in v1.33.0

func (t *MockF3Backend) GetCert(_ context.Context, instance uint64) (*certs.FinalityCertificate, error)

func (*MockF3Backend) GetF3PowerTable added in v1.33.0

func (*MockF3Backend) GetLatestCert added in v1.33.0

func (*MockF3Backend) GetManifest added in v1.33.0

func (t *MockF3Backend) GetManifest(context.Context) (*manifest.Manifest, error)

func (*MockF3Backend) GetOrRenewParticipationTicket added in v1.33.0

func (t *MockF3Backend) GetOrRenewParticipationTicket(_ context.Context, minerID uint64, _ api.F3ParticipationTicket, _ uint64) (api.F3ParticipationTicket, error)

func (*MockF3Backend) GetPowerTable added in v1.33.0

func (*MockF3Backend) GetPowerTableByInstance added in v1.33.1

func (t *MockF3Backend) GetPowerTableByInstance(context.Context, uint64) (gpbft.PowerEntries, error)

func (*MockF3Backend) IsRunning added in v1.33.0

func (t *MockF3Backend) IsRunning() bool

func (*MockF3Backend) ListParticipants added in v1.33.0

func (t *MockF3Backend) ListParticipants() []api.F3Participant

func (*MockF3Backend) Participate added in v1.33.0

func (*MockF3Backend) Progress added in v1.33.0

func (t *MockF3Backend) Progress() gpbft.InstanceProgress

type NodeOpt

type NodeOpt func(opts *nodeOpts) error

NodeOpt is a functional option for test nodes.

func ConstructorOpts

func ConstructorOpts(extra ...node.Option) NodeOpt

ConstructorOpts are Lotus node constructor options that are passed as-is to the node.

func DisableETHBlockCache added in v1.29.0

func DisableETHBlockCache() NodeOpt

func DisableEthRPC added in v1.20.0

func DisableEthRPC() NodeOpt

func DisableLibp2p added in v1.11.1

func DisableLibp2p() NodeOpt

func ECFinalityProvider added in v1.35.1

func ECFinalityProvider(provider *MockECFinalityProvider) NodeOpt

ECFinalityProvider overrides the EC finality calculator used by the test node with the given mock, replacing the real ECFinalityCache which walks 905 tipsets on every head change.

func F3Backend added in v1.33.0

func F3Backend(backend lf3.F3Backend) NodeOpt

F3Backend overrides the F3 backend implementation used by test node.

func F3Config added in v1.33.0

func F3Config(cfg *lf3.Config) NodeOpt

F3Config sets the F3 configuration to be used by test node.

func F3Disabled added in v1.33.0

func F3Disabled() NodeOpt

F3Disabled disables the F3 subsystem for this node.

func FsRepo added in v1.17.1

func FsRepo() NodeOpt

func LiteNode

func LiteNode() NodeOpt

LiteNode specifies that this node will be a lite node. Only relevant when creating a fullnode.

func MainMiner added in v1.11.1

func MainMiner(m *TestMiner) NodeOpt

func MutateSealingConfig added in v1.15.2

func MutateSealingConfig(mut func(sc *config.SealingConfig)) NodeOpt

func NoStorage added in v1.17.1

func NoStorage() NodeOpt

NoStorage initializes miners with no writable storage paths (just read-only preseal paths)

func OwnerAddr

func OwnerAddr(wk *key.Key) NodeOpt

OwnerAddr sets the owner address of a miner. Only relevant when creating a miner.

func OwnerBalance

func OwnerBalance(balance abi.TokenAmount) NodeOpt

OwnerBalance specifies the balance to be attributed to a miner's owner account. Only relevant when creating a miner.

func PresealSectors

func PresealSectors(sectors int) NodeOpt

PresealSectors specifies the amount of preseal sectors to give to a miner at genesis. Only relevant when creating a miner.

func SectorSize added in v1.11.3

func SectorSize(sectorSize abi.SectorSize) NodeOpt

SectorSize sets the sector size for this miner. Start() will populate the corresponding proof type depending on the network version (genesis network version if the Ensemble is unstarted, or the current network version if started).

func SplitstoreDisable added in v1.25.0

func SplitstoreDisable() NodeOpt

func SplitstoreDiscard added in v1.17.1

func SplitstoreDiscard() NodeOpt

func SplitstoreMessges added in v1.19.0

func SplitstoreMessges() NodeOpt

func SplitstoreUniversal added in v1.17.1

func SplitstoreUniversal() NodeOpt

func ThroughRPC

func ThroughRPC() NodeOpt

ThroughRPC makes interactions with this node throughout the test flow through the JSON-RPC API.

func WithAllSubsystems added in v1.11.1

func WithAllSubsystems() NodeOpt

func WithAssigner added in v1.17.0

func WithAssigner(a string) NodeOpt

func WithCfgOpt added in v1.17.1

func WithCfgOpt(opt CfgOption) NodeOpt

func WithDisallowRemoteFinalize added in v1.17.0

func WithDisallowRemoteFinalize(d bool) NodeOpt

func WithEthRPC added in v1.20.0

func WithEthRPC() NodeOpt

func WithNoLocalSealing added in v1.15.2

func WithNoLocalSealing(nope bool) NodeOpt

func WithSubsystems added in v1.11.1

func WithSubsystems(systems ...MinerSubsystem) NodeOpt

func WithTaskTypes added in v1.15.2

func WithTaskTypes(tt []sealtasks.TaskType) NodeOpt

func WithWorkerName added in v1.17.1

func WithWorkerName(n string) NodeOpt

func WithWorkerStorage added in v1.15.2

func WithWorkerStorage(transform func(paths.Store) paths.Store) NodeOpt

type OnboardOpt added in v1.29.0

type OnboardOpt func(opts *onboardOpt) error

func WithExpectedExitCodes added in v1.29.0

func WithExpectedExitCodes(exitCodes []exitcode.ExitCode) OnboardOpt

func WithModifyNIActivationsBeforeSubmit added in v1.29.0

func WithModifyNIActivationsBeforeSubmit(f func([]miner14.SectorNIActivationInfo) []miner14.SectorNIActivationInfo) OnboardOpt

func WithRequireActivationSuccess added in v1.29.0

func WithRequireActivationSuccess(requireActivationSuccess bool) OnboardOpt

type OptBuilder

type OptBuilder func(activeNodes []*TestFullNode) node.Option

OptBuilder is used to create an option after some other node is already active. Takes all active nodes as a parameter.

type SchedInfo added in v1.20.0

type SchedInfo struct {
	CallToWork   struct{}
	EarlyRet     interface{}
	ReturnedWork interface{}
	SchedInfo    struct {
		OpenWindows []string
		Requests    []struct {
			Priority int
			SchedId  uuid.UUID
			Sector   struct {
				Miner  int
				Number int
			}
			TaskType string
		}
	}
	Waiting interface{}
}

SchedInfo comes from https://github.com/filecoin-project/lotus/blob/8ba4355cabd25e5f65261aaa561ff676321ffbd8/storage/sealer/manager.go#L1226 todo: have this defined in one place

type SectorBatch added in v1.32.0

type SectorBatch struct {
	// contains filtered or unexported fields
}

SectorBatch is a builder for creating sector manifests

func NewSectorBatch added in v1.32.0

func NewSectorBatch() *SectorBatch

NewSectorBatch creates an empty sector batch

func (*SectorBatch) AddEmptySectors added in v1.32.0

func (sb *SectorBatch) AddEmptySectors(count int) *SectorBatch

AddEmptySectors adds the specified number of CC sectors to the batch

func (*SectorBatch) AddSector added in v1.32.0

func (sb *SectorBatch) AddSector(manifest SectorManifest) *SectorBatch

AddSector adds a custom sector manifest

func (*SectorBatch) AddSectorsWithRandomPieces added in v1.32.0

func (sb *SectorBatch) AddSectorsWithRandomPieces(count int) *SectorBatch

AddSectorsWithRandomPieces adds sectors with random pieces

type SectorManifest added in v1.32.0

type SectorManifest struct {
	Piece    cid.Cid
	Verified *miner14.VerifiedAllocationKey
	Duration abi.ChainEpoch
}

SectorManifest is (currently) a simplified SectorAllocationManifest, allowing zero or one pieces to be built into a sector, where that one piece may be verified. Undefined Piece and nil Verified onboards a CC sector. Duration changes the default sector expiration of 300 days past the minimum.

func EmptySector added in v1.32.0

func EmptySector() SectorManifest

EmptySector creates an empty (CC) sector with no pieces

func SectorWithPiece added in v1.32.0

func SectorWithPiece(piece cid.Cid) SectorManifest

SectorWithPiece creates a sector with the specified piece CID

func SectorWithVerifiedPiece added in v1.32.0

func SectorWithVerifiedPiece(piece cid.Cid, key *miner14.VerifiedAllocationKey) SectorManifest

SectorWithVerifiedPiece creates a sector with a verified allocation

type SendCall added in v1.20.0

type SendCall struct {
	Method abi.MethodNum
	Params []byte
}

type SolidityContractDef added in v1.20.0

type SolidityContractDef struct {
	Filename string                      // filename of the hex of the contract, e.g. contracts/EventMatrix.hex
	Fn       map[string][]byte           // mapping of function names to 32-bit selector
	Ev       map[string]ethtypes.EthHash // mapping of event names to 256-bit signature hashes
}

SolidityContractDef holds information about one of the test contracts

type SolsticeEnv added in v1.37.0

type SolsticeEnv struct {
	Ctx       context.Context
	Client    *TestFullNode
	Um        *TestUnmanagedMiner
	Maddr     address.Address
	Ssize     abi.SectorSize // always 2KiB
	SealProof abi.RegisteredSealProof
}

SolsticeEnv bundles the ensemble pieces (ctx, client, unmanaged miner, miner address, sector size, seal proof) produced by NewSolsticeUpgradeEnv for use by the solstice itests.

func NewSolsticeUpgradeEnv added in v1.37.0

func NewSolsticeUpgradeEnv(t *testing.T, o SolsticeOpts) *SolsticeEnv

NewSolsticeUpgradeEnv builds the standard solstice itest ensemble: a single unmanaged miner on a chain that upgrades NV28->NV29 or starts on NV29, mock proofs over RPC, mining started, and the miner's WindowPoSt driven by its own in-kit loop. It returns the pieces as a *SolsticeEnv for the caller to bind.

type SolsticeOpts added in v1.37.0

type SolsticeOpts struct {
	// UpgradeEpoch > 0 upgrades the chain NV28 -> NV29 at this height (with the neutral Solstice
	// reward bootstrap so the migration matches the other solstice itests). 0 starts the chain on
	// NV29.
	UpgradeEpoch abi.ChainEpoch
	// Optional verifreg plumbing: when RootKey/VerifierKey/VerifiedClientKey are non-nil the
	// ensemble is created with a RootVerifier + two funded Accounts (default funding 100 FIL). The
	// same keys are returned to the caller via the enclosing test's own locals, so SetupVerifiedClients
	// / SetupAllocation can reuse them after the ensemble exists.
	RootKey, VerifierKey, VerifiedClientKey *key.Key
	Bal                                     int64
}

SolsticeOpts configures NewSolsticeUpgradeEnv.

type TestDealState

type TestDealState int

func CategorizeDealState

func CategorizeDealState(dealStatus string) TestDealState

CategorizeDealState categorizes deal states into one of three states: Complete, InProgress, Failed.

type TestFullNode

type TestFullNode struct {
	v1api.FullNode
	V2 v2api.FullNode

	// ListenAddr is the address on which an API server is listening, if an
	// API server is created for this Node.
	ListenAddr multiaddr.Multiaddr
	ListenURL  string
	DefaultKey *key.Key

	Pkey *Libp2p

	Stop node.StopFunc

	// gateway handler makes it convenient to register callbalks per topic, so we
	// also use it for tests
	EthSubRouter *gateway.EthSubHandler
	// contains filtered or unexported fields
}

TestFullNode represents a full node enrolled in an Ensemble.

func SetupFEVMTest added in v1.20.0

func SetupFEVMTest(t *testing.T, opts ...interface{}) (context.Context, context.CancelFunc, *TestFullNode)

func (*TestFullNode) AssertActorType added in v1.20.0

func (f *TestFullNode) AssertActorType(ctx context.Context, addr address.Address, actorType string)

AssertActorType verifies that the supplied address is an actor of the specified type (as per its manifest key).

func (*TestFullNode) AssignPrivKey added in v1.19.0

func (f *TestFullNode) AssignPrivKey(pkey *Libp2p)

func (*TestFullNode) CurrentProvingDeadline added in v1.37.0

func (f *TestFullNode) CurrentProvingDeadline(ctx context.Context, maddr address.Address) *dline.Info

CurrentProvingDeadline returns the miner's proving deadline at the current chain head, rewound if necessary so that di.Open <= head height.

StateMinerProvingDeadline reads the parent state of the queried tipset. At a deadline boundary that follows a null round the miner cron has not yet advanced the recorded deadline, so NextNotElapsed reports the same deadline index one proving period later, and a test waiting for di.Open + di.WPoStProvingPeriod would wait two periods instead of one.

func (*TestFullNode) DeadlineForHead added in v1.37.0

func (f *TestFullNode) DeadlineForHead(ctx context.Context, maddr address.Address) *dline.Info

DeadlineForHead returns the deadline the chain head falls in, for a miner whose recorded deadline may be stale because it is not enrolled in cron.

func (*TestFullNode) DoRawRPCRequest added in v1.33.0

func (full *TestFullNode) DoRawRPCRequest(t *testing.T, version int, body string) (int, []byte)

func (*TestFullNode) EVM added in v1.20.0

func (f *TestFullNode) EVM() *EVM

func (*TestFullNode) ExpectSend added in v1.20.0

func (f *TestFullNode) ExpectSend(ctx context.Context, from, to address.Address, value types.BigInt, errContains string, sc ...SendCall) *types.SignedMessage

func (*TestFullNode) MakeSendCall added in v1.20.0

func (f *TestFullNode) MakeSendCall(m abi.MethodNum, params cbg.CBORMarshaler) SendCall

func (*TestFullNode) MinerQAP added in v1.37.0

func (f *TestFullNode) MinerQAP(ctx context.Context, maddr address.Address, tsk types.TipSetKey) (minerQAP, networkQAP uint64)

MinerQAP returns the miner's and the whole network's quality-adjusted power at tsk.

func (*TestFullNode) MinerRawPower added in v1.37.0

func (f *TestFullNode) MinerRawPower(ctx context.Context, maddr address.Address, tsk types.TipSetKey) uint64

MinerRawPower returns the miner's raw byte power at tsk.

func (*TestFullNode) MinerState added in v1.37.0

func (f *TestFullNode) MinerState(ctx context.Context, maddr address.Address, tsk types.TipSetKey) *stminer.State

MinerState loads a miner actor's v19 state at tsk.

func (*TestFullNode) MustSectorInfo added in v1.37.0

MustSectorInfo reads a sector that has to be committed at tsk.

func (TestFullNode) Shutdown added in v1.19.0

func (f TestFullNode) Shutdown(ctx context.Context) error

func (*TestFullNode) Store added in v1.37.0

func (f *TestFullNode) Store(ctx context.Context) gstStore.Store

Store gives an IPLD store backed by this node, for sneaky state reads.

func (*TestFullNode) UpgradeSectorQualityParams added in v1.37.0

func (f *TestFullNode) UpgradeSectorQualityParams(ctx context.Context, maddr address.Address, sector abi.SectorNumber, tsk types.TipSetKey) []byte

UpgradeSectorQualityParams builds the parameters for raising one sector's quality.

func (*TestFullNode) WaitForDeadlineIndex added in v1.37.0

func (f *TestFullNode) WaitForDeadlineIndex(ctx context.Context, maddr address.Address, idx uint64) types.TipSetKey

WaitForDeadlineIndex advances the chain to the window in which idx is the miner's current proving deadline, and returns a tipset inside it.

func (*TestFullNode) WaitForDeclarableDeadline added in v1.38.0

func (f *TestFullNode) WaitForDeclarableDeadline(ctx context.Context, maddr address.Address, dlIdx uint64) *types.TipSet

WaitForDeclarableDeadline returns the first head at which a declaration for deadline dlIdx would land a challenge window ahead of its fault declaration cutoff.

func (*TestFullNode) WaitForSectorActive added in v1.15.2

func (f *TestFullNode) WaitForSectorActive(ctx context.Context, t *testing.T, sn abi.SectorNumber, maddr address.Address)

func (*TestFullNode) WaitMsg added in v1.11.1

func (f *TestFullNode) WaitMsg(ctx context.Context, msg cid.Cid)

func (*TestFullNode) WaitMsgResult added in v1.38.0

func (f *TestFullNode) WaitMsgResult(ctx context.Context, msg cid.Cid, confidence uint64) (*api.MsgLookup, error)

WaitMsgResult is StateWaitMsg with no lookback limit, bounded by the ensemble's failure context. A wait cut short by ctx or by a failure reported to the ensemble returns the cancellation cause.

func (*TestFullNode) WaitTillChain

func (f *TestFullNode) WaitTillChain(ctx context.Context, pred ChainPredicate) *types.TipSet

WaitTillChain waits until a specified chain condition is met. It returns the first tipset where the condition is met. A failure reported to the ensemble fails the test with that failure; a wait still open at test cleanup ends its goroutine quietly.

func (*TestFullNode) WaitTillChainOrError added in v1.27.1

func (f *TestFullNode) WaitTillChainOrError(ctx context.Context, pred ChainPredicate) (*types.TipSet, error)

WaitTillChainOrError waits until a specified chain condition is met. It returns the first tipset where the condition is met. In the case of an error it will return the error. A wait cut short by ctx or by a failure reported to the ensemble returns the cancellation cause.

type TestMiner

type TestMiner struct {
	api.StorageMiner

	BaseAPI api.StorageMiner

	// ListenAddr is the address on which an API server is listening, if an
	// API server is created for this Node
	ListenAddr multiaddr.Multiaddr

	ActorAddr address.Address
	OwnerKey  *key.Key
	MineOne   func(context.Context, miner.MineReq) error
	Stop      func(context.Context) error

	FullNode       *TestFullNode
	PresealDir     string
	PresealSectors int

	Libp2p struct {
		PeerID  peer.ID
		PrivKey libp2pcrypto.PrivKey
	}

	RemoteListener net.Listener
	// contains filtered or unexported fields
}

TestMiner represents a miner enrolled in an Ensemble.

func (*TestMiner) AddStorage

func (tm *TestMiner) AddStorage(ctx context.Context, t *testing.T, conf func(*storiface.LocalStorageMeta)) storiface.ID

func (*TestMiner) FlushSealingBatches

func (tm *TestMiner) FlushSealingBatches(ctx context.Context)

func (*TestMiner) PledgeSectors

func (tm *TestMiner) PledgeSectors(ctx context.Context, n, existing int, blockNotif <-chan struct{})

func (*TestMiner) SchedInfo added in v1.20.0

func (tm *TestMiner) SchedInfo(ctx context.Context) SchedInfo

func (*TestMiner) SectorsListNonGenesis added in v1.17.1

func (tm *TestMiner) SectorsListNonGenesis(ctx context.Context) ([]abi.SectorNumber, error)

func (*TestMiner) SetControlAddresses added in v1.11.1

func (tm *TestMiner) SetControlAddresses(addrs ...addr.Address)

func (*TestMiner) StartPledge

func (tm *TestMiner) StartPledge(ctx context.Context, n, existing int, blockNotif <-chan struct{}) map[abi.SectorNumber]struct{}

func (*TestMiner) WaitSectorsProving added in v1.14.0

func (tm *TestMiner) WaitSectorsProving(ctx context.Context, toCheck map[abi.SectorNumber]struct{})

func (*TestMiner) WaitSectorsProvingAllowFails added in v1.17.2

func (tm *TestMiner) WaitSectorsProvingAllowFails(ctx context.Context, toCheck map[abi.SectorNumber]struct{}, okFails map[api.SectorState]struct{})

type TestUnmanagedMiner added in v1.27.1

type TestUnmanagedMiner struct {
	ActorAddr address.Address
	OwnerKey  *key.Key
	FullNode  *TestFullNode
	Libp2p    struct {
		PeerID  peer.ID
		PrivKey libp2pcrypto.PrivKey
	}
	// contains filtered or unexported fields
}

TestUnmanagedMiner is a miner that's not managed by the storage/infrastructure, all tasks must be manually executed, managed and scheduled by the test or test kit. Note: `TestUnmanagedMiner` is not thread safe and assumes linear access of its methods

func NewTestUnmanagedMiner added in v1.27.1

func NewTestUnmanagedMiner(ctx context.Context, t *testing.T, full *TestFullNode, actorAddr address.Address, mockProofs bool, opts ...NodeOpt) *TestUnmanagedMiner

func (*TestUnmanagedMiner) AssertDisputeFails added in v1.28.0

func (tm *TestUnmanagedMiner) AssertDisputeFails(sector abi.SectorNumber)

func (*TestUnmanagedMiner) AssertNoPower added in v1.27.1

func (tm *TestUnmanagedMiner) AssertNoPower()

func (*TestUnmanagedMiner) AssertNoWindowPostError added in v1.29.0

func (tm *TestUnmanagedMiner) AssertNoWindowPostError()

func (*TestUnmanagedMiner) AssertPower added in v1.27.1

func (tm *TestUnmanagedMiner) AssertPower(raw uint64, qa uint64)

func (*TestUnmanagedMiner) CurrentPower added in v1.27.1

func (tm *TestUnmanagedMiner) CurrentPower() *api.MinerPower

func (*TestUnmanagedMiner) DeclareFaults added in v1.37.0

func (tm *TestUnmanagedMiner) DeclareFaults(sectorNumbers []abi.SectorNumber) *api.MsgLookup

DeclareFaults declares the given sectors faulty (they must not be in the currently-open proving window, so we wait for a mutable deadline first). The lookup it returns says where the declaration landed, which is what decides when the actor first charges for the fault.

func (*TestUnmanagedMiner) ExtendSectorExpiration added in v1.32.0

func (tm *TestUnmanagedMiner) ExtendSectorExpiration(sectorNumber abi.SectorNumber, expiration abi.ChainEpoch, maintainClaims ...verifreg14.ClaimId) types.TipSetKey

ExtendSectorExpiration preserves the supplied verified claims when extending a sector.

func (*TestUnmanagedMiner) GetPostCount added in v1.32.0

func (tm *TestUnmanagedMiner) GetPostCount(sectorNumber abi.SectorNumber) int

func (*TestUnmanagedMiner) GetPostCountSince added in v1.32.0

func (tm *TestUnmanagedMiner) GetPostCountSince(epoch abi.ChainEpoch, sectorNumber abi.SectorNumber) int

func (*TestUnmanagedMiner) MaybeImmutableDeadline added in v1.33.1

func (tm *TestUnmanagedMiner) MaybeImmutableDeadline(deadlineIndex uint64) bool

MaybeImmutableDeadline checks if the deadline index is immutable. Immutable deadlines are defined as being the current deadline for the miner or their next deadline. But we also include the deadline after the next deadline in our check here to be conservative to avoid race conditions of the chain progressing before messages land.

func (*TestUnmanagedMiner) OnboardSectors added in v1.29.0

func (tm *TestUnmanagedMiner) OnboardSectors(
	proofType abi.RegisteredSealProof,
	sectorBatch *SectorBatch,
	opts ...OnboardOpt,
) ([]abi.SectorNumber, types.TipSetKey)

OnboardSectors onboards the specified number of sectors to the miner using the specified proof type. If `withPieces` is true and the proof type supports it, the sectors will be onboarded with pieces, otherwise they will be CC.

This method is synchronous but each sector is prepared in a separate goroutine to speed up the process with real proofs.

func (*TestUnmanagedMiner) PreCommitSectors added in v1.37.0

func (tm *TestUnmanagedMiner) PreCommitSectors(
	proofType abi.RegisteredSealProof,
	sectorBatch *SectorBatch,
) ([]abi.SectorNumber, error)

PreCommitSectors is the pre-commit half of OnboardSectors: it allocates sector numbers, runs PC1/PC2/C1/C2, submits the PreCommit to the network and generates the ProveCommit proof, but does NOT submit ProveCommit. The prepared sectors are retained internally so a later call to ProvePrecommittedSectors (e.g. after the chain has crossed an upgrade) can complete onboarding.

This lets a sector that is pre-committed under one network version land (activate) under another, which is exactly the FIP-0118 "precommit NV28 / prove NV29" scenario: only the network version at activation (prove) decides FULL_QA_POWER. Returns the precommitted sector numbers.

func (*TestUnmanagedMiner) ProvePrecommittedSectors added in v1.37.0

func (tm *TestUnmanagedMiner) ProvePrecommittedSectors(
	proofType abi.RegisteredSealProof,
	sectorNumbers []abi.SectorNumber,
) ([]abi.SectorNumber, error)

ProvePrecommittedSectors completes onboarding for sectors prepared by PreCommitSectors by submitting their ProveCommit to the network. On success each sector is committed and registered with the miner for WindowPoSt. Returns the sectors that were successfully committed.

func (*TestUnmanagedMiner) RecoverFaults added in v1.37.0

func (tm *TestUnmanagedMiner) RecoverFaults(sectorNumbers []abi.SectorNumber) *api.MsgLookup

RecoverFaults declares the given (previously faulty) sectors as recovered. The lookup it returns says where the declaration landed, which is the only state in which it is certainly still recorded: the proof that completes the recovery clears it.

func (*TestUnmanagedMiner) SnapDeal added in v1.28.0

func (tm *TestUnmanagedMiner) SnapDeal(sectorNumber abi.SectorNumber, sm SectorManifest) ([]abi.PieceInfo, types.TipSetKey)

SnapDeal snaps a deal into a sector, generating a new sealed sector and updating the sector's state. WindowPoSt should continue to operate after this operation if required. The SectorManifest argument (currently) only impacts mock proofs, and is ignored otherwise.

func (*TestUnmanagedMiner) Stop added in v1.29.0

func (tm *TestUnmanagedMiner) Stop()

func (*TestUnmanagedMiner) SubmitMessage added in v1.28.0

func (tm *TestUnmanagedMiner) SubmitMessage(
	params cbg.CBORMarshaler,
	value uint64,
	method abi.MethodNum,
) (*api.MsgLookup, error)

func (*TestUnmanagedMiner) TerminateSectors added in v1.37.0

func (tm *TestUnmanagedMiner) TerminateSectors(sectorNumbers []abi.SectorNumber)

TerminateSectors terminates the given sectors, dropping their power and charging their fee in the same message. On success they leave the local committedSectors set so the wdPost loop stops posting for them; a rejected post for a terminated sector would kill the whole loop, healthy sectors too.

func (*TestUnmanagedMiner) UpgradeSectorQuality added in v1.37.0

func (tm *TestUnmanagedMiner) UpgradeSectorQuality(sectorNumbers []abi.SectorNumber, newExpiration *abi.ChainEpoch) (*api.MsgLookup, error)

func (*TestUnmanagedMiner) WaitTillActivatedAndAssertPower added in v1.28.0

func (tm *TestUnmanagedMiner) WaitTillActivatedAndAssertPower(sectors []abi.SectorNumber, raw uint64, qa uint64) error

func (*TestUnmanagedMiner) WaitTillPostCount added in v1.32.0

func (tm *TestUnmanagedMiner) WaitTillPostCount(sectorNumber abi.SectorNumber, count int) error

WaitTillPostCount waits until the sector appears in count successful WindowPoSts. A live sector is proven once per proving period, so a miner that adds no post in one and a half of them has stopped. Cancellation and stalled progress return errors for the caller to report on its own goroutine.

type TestWorker added in v1.15.2

type TestWorker struct {
	api.Worker

	// ListenAddr is the address on which an API server is listening, if an
	// API server is created for this Node
	ListenAddr multiaddr.Multiaddr

	Stop func(context.Context) error

	FetchHandler   http.HandlerFunc
	MinerNode      *TestMiner
	RemoteListener net.Listener
	// contains filtered or unexported fields
}

TestWorker represents a worker enrolled in an Ensemble.

func (*TestWorker) AddStorage added in v1.17.1

func (tm *TestWorker) AddStorage(ctx context.Context, t *testing.T, conf func(*storiface.LocalStorageMeta)) storiface.ID

Jump to

Keyboard shortcuts

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