state

package
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2023 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	InitChainSource       = "ResponseInitChain"
	PrepareProposalSource = "ResponsePrepareProposal"
	ProcessProposalSource = "ResponseProcessProposal"
)
View Source
const (
	// MetricsSubsystem is a subsystem shared by all metrics exposed by this
	// package.
	MetricsSubsystem = "state"
)

Variables

View Source
var (
	ErrBlockRejected = errors.New("block not accepted by abci app")
)
View Source
var InitStateVersion = Version{
	Consensus: version.Consensus{
		Block: version.BlockProtocol,
		App:   0,
	},
	Software: version.TMCoreSemVer,
}

InitStateVersion sets the Consensus.Block and Software versions, but leaves the Consensus.App version blank. The Consensus.App version will be set during the Handshake, once we hear from the app what protocol version it is running.

Functions

func BlockExecWithAppClient

func BlockExecWithAppClient(appClient abciclient.Client) func(e *BlockExecutor)

BlockExecWithAppClient sets application client to BlockExecutor

func BlockExecWithLogger

func BlockExecWithLogger(logger log.Logger) func(e *BlockExecutor)

BlockExecWithLogger is an option function to set a logger to BlockExecutor

func BockExecWithMetrics

func BockExecWithMetrics(metrics *Metrics) func(e *BlockExecutor)

BockExecWithMetrics is an option function to set a metrics to BlockExecutor

func ExecReplayedCommitBlock

func ExecReplayedCommitBlock(
	ctx context.Context,
	appConn abciclient.Client,
	block *types.Block,
	commit *types.Commit,
	logger log.Logger,
) (*abci.ResponseFinalizeBlock, error)

---------------------------------------------------------------------------------------------------- Execute block without state. TODO: eliminate ExecReplayedCommitBlock executes and commits a block on the proxyApp without validating or mutating the state. It returns the application root hash (apphash - result of abci.flushMempool).

CONTRACT: Block should already be delivered to the app with PrepareProposal or ProcessProposal

func MakeGenesisDocFromFile

func MakeGenesisDocFromFile(genDocFile string) (*types.GenesisDoc, error)

MakeGenesisDocFromFile reads and unmarshals genesis doc from the given file.

func Rollback

func Rollback(bs BlockStore, ss Store) (int64, []byte, error)

Rollback overwrites the current Tendermint state (height n) with the most recent previous state (height n - 1). Note that this function does not affect application state.

func TxPostCheckForState

func TxPostCheckForState(state State) mempool.PostCheckFunc

func TxPostCheckFromStore

func TxPostCheckFromStore(store Store) mempool.PostCheckFunc

TxPostCheckFromStore returns a function to filter transactions after processing. The function limits the gas wanted by a transaction to the block's maximum total gas.

func TxPreCheckForState

func TxPreCheckForState(state State) mempool.PreCheckFunc

func TxPreCheckFromStore

func TxPreCheckFromStore(store Store) mempool.PreCheckFunc

TxPreCheckFromStore returns a function to filter transactions before processing. The function limits the size of a transaction to the block's maximum data size.

func ValidateBlockChainLock

func ValidateBlockChainLock(state State, block *types.Block) error

ValidateBlockChainLock validates the given block chain lock against the given state. If the block is invalid, it returns an error. Validation does not mutate state, but does require historical information from the stateDB, ie. to verify evidence from a validator at an old height.

Types

type BlockExecutor

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

BlockExecutor provides the context and accessories for properly executing a block.

func NewBlockExecutor

func NewBlockExecutor(
	stateStore Store,
	appClient abciclient.Client,
	pool mempool.Mempool,
	evpool EvidencePool,
	blockStore BlockStore,
	eventBus *eventbus.EventBus,
	opts ...func(e *BlockExecutor),
) *BlockExecutor

NewBlockExecutor returns a new BlockExecutor with the passed-in EventBus.

func (*BlockExecutor) ApplyBlock

func (blockExec *BlockExecutor) ApplyBlock(
	ctx context.Context,
	state State,
	blockID types.BlockID,
	block *types.Block,
	commit *types.Commit,
) (State, error)

ApplyBlock validates the block against the state, executes it against the app using ProcessProposal ABCI request, fires the relevant events, finalizes with FinalizeBlock, and saves the new state and responses. It returns the new state. It's the only function that needs to be called from outside this package to process and commit an entire block. It takes a blockID to avoid recomputing the parts hash.

func (*BlockExecutor) Copy

func (blockExec *BlockExecutor) Copy(opts ...func(e *BlockExecutor)) *BlockExecutor

Copy returns a new instance of BlockExecutor and applies option functions

func (*BlockExecutor) CreateProposalBlock

func (blockExec *BlockExecutor) CreateProposalBlock(
	ctx context.Context,
	height int64,
	round int32,
	state State,
	commit *types.Commit,
	proposerProTxHash []byte,
	proposedAppVersion uint64,
) (*types.Block, CurrentRoundState, error)

CreateProposalBlock calls state.MakeBlock with evidence from the evpool and txs from the mempool. The max bytes must be big enough to fit the commit. Up to 1/10th of the block space is allocated for maximum sized evidence. The rest is given to txs, up to the max gas.

Contract: application will not return more bytes than are sent over the wire.

func (*BlockExecutor) ExtendVote

func (blockExec *BlockExecutor) ExtendVote(ctx context.Context, vote *types.Vote)

ExtendVote gets vote-extensions from ABCI and updates vote.VoteExtensions with this value

func (*BlockExecutor) FinalizeBlock

func (blockExec *BlockExecutor) FinalizeBlock(
	ctx context.Context,
	state State,
	uncommittedState CurrentRoundState,
	blockID types.BlockID,
	block *types.Block,
	commit *types.Commit,
) (State, error)

func (*BlockExecutor) ProcessProposal

func (blockExec *BlockExecutor) ProcessProposal(
	ctx context.Context,
	block *types.Block,
	round int32,
	state State,
	verify bool,
) (CurrentRoundState, error)

ProcessProposal sends the proposal to ABCI App and verifies the response

func (*BlockExecutor) SetAppHashSize

func (blockExec *BlockExecutor) SetAppHashSize(size int)

SetAppHashSize ...

func (*BlockExecutor) Store

func (blockExec *BlockExecutor) Store() Store

func (*BlockExecutor) ValidateBlock

func (blockExec *BlockExecutor) ValidateBlock(ctx context.Context, state State, block *types.Block) error

ValidateBlock validates the given block against the given state. If the block is invalid, it returns an error. Validation does not mutate state, but does require historical information from the stateDB, ie. to verify evidence from a validator at an old height.

func (*BlockExecutor) ValidateBlockWithRoundState

func (blockExec *BlockExecutor) ValidateBlockWithRoundState(
	ctx context.Context,
	state State,
	uncommittedState CurrentRoundState,
	block *types.Block,
) error

func (*BlockExecutor) VerifyVoteExtension

func (blockExec *BlockExecutor) VerifyVoteExtension(ctx context.Context, vote *types.Vote) error

type BlockStore

type BlockStore interface {
	Base() int64
	Height() int64
	CoreChainLockedHeight() uint32
	Size() int64

	LoadBaseMeta() *types.BlockMeta
	LoadBlockMeta(height int64) *types.BlockMeta
	LoadBlock(height int64) *types.Block

	SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit)

	PruneBlocks(height int64) (uint64, error)

	LoadBlockByHash(hash []byte) *types.Block
	LoadBlockMetaByHash(hash []byte) *types.BlockMeta
	LoadBlockPart(height int64, index int) *types.Part

	LoadBlockCommit(height int64) *types.Commit
	LoadSeenCommit() *types.Commit
	LoadSeenCommitAt(height int64) *types.Commit
}

BlockStore defines the interface used by the ConsensusState.

type CurrentRoundState

type CurrentRoundState struct {
	// Base state for the changes
	Base State

	// Round at which we are right now
	Round int32

	ProTxHash types.ProTxHash

	// AppHash of current block
	AppHash tmbytes.HexBytes `json:"app_hash"`

	// TxResults for current block
	TxResults []*abci.ExecTxResult `json:"tx_results"`
	// ResultsHash of current block
	ResultsHash []byte `json:"results_hash"`

	CoreChainLock *types.CoreChainLock

	NextConsensusParams              types.ConsensusParams
	LastHeightConsensusParamsChanged int64

	NextValidators              *types.ValidatorSet
	LastHeightValidatorsChanged int64

	Params RoundParams
}

CurrentRoundState ...

func NewCurrentRoundState

func NewCurrentRoundState(proTxHash types.ProTxHash, rp RoundParams, baseState State) (CurrentRoundState, error)

NewCurrentRoundState returns a new instance of CurrentRoundState

func (*CurrentRoundState) GetHeight

func (candidate *CurrentRoundState) GetHeight() int64

GetHeight returns height of current block

func (*CurrentRoundState) MatchesBlock

func (candidate *CurrentRoundState) MatchesBlock(blockHeader types.Header, round int32) bool

func (*CurrentRoundState) UpdateBlock

func (candidate *CurrentRoundState) UpdateBlock(target *types.Block) error

UpdateBlock changes block fields to reflect the ones returned in PrepareProposal

func (*CurrentRoundState) UpdateFunc

func (candidate *CurrentRoundState) UpdateFunc(state State) (State, error)

UpdateFunc implements UpdateFunc

func (*CurrentRoundState) UpdateState

func (candidate *CurrentRoundState) UpdateState(target *State) error

UpdateState updates state when the block is committed. State will contain data needed by next block.

type EmptyEvidencePool

type EmptyEvidencePool struct{}

EmptyEvidencePool is an empty implementation of EvidencePool, useful for testing. It also complies to the consensus evidence pool interface

func (EmptyEvidencePool) AddEvidence

func (EmptyEvidencePool) CheckEvidence

func (EmptyEvidencePool) CheckEvidence(ctx context.Context, evList types.EvidenceList) error

func (EmptyEvidencePool) PendingEvidence

func (EmptyEvidencePool) PendingEvidence(maxBytes int64) (ev []types.Evidence, size int64)

func (EmptyEvidencePool) ReportConflictingVotes

func (EmptyEvidencePool) ReportConflictingVotes(voteA, voteB *types.Vote)

func (EmptyEvidencePool) Update

type ErrAppBlockHeightTooHigh

type ErrAppBlockHeightTooHigh struct {
	CoreHeight int64
	AppHeight  int64
}

func (ErrAppBlockHeightTooHigh) Error

func (e ErrAppBlockHeightTooHigh) Error() string

type ErrAppBlockHeightTooLow

type ErrAppBlockHeightTooLow struct {
	AppHeight int64
	StoreBase int64
}

func (ErrAppBlockHeightTooLow) Error

func (e ErrAppBlockHeightTooLow) Error() string

type ErrBlockHashMismatch

type ErrBlockHashMismatch struct {
	CoreHash []byte
	AppHash  []byte
	Height   int64
}

func (ErrBlockHashMismatch) Error

func (e ErrBlockHashMismatch) Error() string

type ErrInvalidBlock

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

type ErrLastStateMismatch

type ErrLastStateMismatch struct {
	Height int64
	Core   []byte
	App    []byte
}

func (ErrLastStateMismatch) Error

func (e ErrLastStateMismatch) Error() string

type ErrNoABCIResponsesForHeight

type ErrNoABCIResponsesForHeight struct {
	Height int64
}

func (ErrNoABCIResponsesForHeight) Error

type ErrNoConsensusParamsForHeight

type ErrNoConsensusParamsForHeight struct {
	Height int64
}

func (ErrNoConsensusParamsForHeight) Error

type ErrNoFinalizeBlockResponsesForHeight

type ErrNoFinalizeBlockResponsesForHeight struct {
	Height int64
}

func (ErrNoFinalizeBlockResponsesForHeight) Error

type ErrNoValSetForHeight

type ErrNoValSetForHeight struct {
	Height int64
	Err    error
}

func (ErrNoValSetForHeight) Error

func (e ErrNoValSetForHeight) Error() string

func (ErrNoValSetForHeight) Unwrap

func (e ErrNoValSetForHeight) Unwrap() error

type ErrProxyAppConn

type ErrProxyAppConn error

type ErrStateMismatch

type ErrStateMismatch struct {
	Got      *State
	Expected *State
}

func (ErrStateMismatch) Error

func (e ErrStateMismatch) Error() string

type ErrUnknownBlock

type ErrUnknownBlock struct {
	Height int64
}

func (ErrUnknownBlock) Error

func (e ErrUnknownBlock) Error() string

type EventSet

type EventSet struct {
	NewBlock           *types.EventDataNewBlock
	NewBlockHeader     *types.EventDataNewBlockHeader
	NewEvidence        []types.EventDataNewEvidence
	Txs                []types.EventDataTx
	ValidatorSetUpdate *types.EventDataValidatorSetUpdate
}

EventSet is a set of events that are published immediately after the block is committed.

func NewFullEventSet

func NewFullEventSet(
	block *types.Block,
	blockID types.BlockID,
	uncommittedState CurrentRoundState,
	fbResp *abci.ResponseFinalizeBlock,
	validatorsSet *types.ValidatorSet,
) EventSet

NewFullEventSet returns a full EventSet

func (*EventSet) Publish

func (e *EventSet) Publish(publisher types.BlockEventPublisher) error

Publish publishes events that were added to a EventSet if Tenderdash crashes before commit, some or all of these events may be published again

func (*EventSet) WithNewBlock

func (e *EventSet) WithNewBlock(
	block *types.Block,
	blockID types.BlockID,
	fbResp abci.ResponseFinalizeBlock,
) *EventSet

WithNewBlock adds types.EventDataNewBlock event to a set

func (*EventSet) WithNewEvidences

func (e *EventSet) WithNewEvidences(block *types.Block) *EventSet

WithNewEvidences creates and adds types.EventDataNewEvidence events to a set

func (*EventSet) WithTxs

func (e *EventSet) WithTxs(block *types.Block, txResults []*abci.ExecTxResult) *EventSet

WithTxs creates and adds types.EventDataTx events to a set

func (*EventSet) WithValidatorSetUpdate

func (e *EventSet) WithValidatorSetUpdate(validatorSet *types.ValidatorSet) *EventSet

WithValidatorSetUpdate creates and adds types.EventDataValidatorSetUpdate event to a set

func (*EventSet) WthNewBlockHeader

func (e *EventSet) WthNewBlockHeader(
	block *types.Block,
	ppResp abci.ResponseProcessProposal,
	fbResp abci.ResponseFinalizeBlock,
) *EventSet

WthNewBlockHeader adds types.EventDataNewBlockHeader event to a set

type EvidencePool

type EvidencePool interface {
	PendingEvidence(maxBytes int64) (ev []types.Evidence, size int64)
	AddEvidence(context.Context, types.Evidence) error
	Update(context.Context, State, types.EvidenceList)
	CheckEvidence(context.Context, types.EvidenceList) error
}

EvidencePool defines the EvidencePool interface used by State.

type Executor

type Executor interface {
	VoteExtender
	CreateProposalBlock(
		ctx context.Context,
		height int64,
		round int32,
		state State,
		commit *types.Commit,
		proposerProTxHash []byte,
		proposedAppVersion uint64,
	) (*types.Block, CurrentRoundState, error)

	ProcessProposal(
		ctx context.Context,
		block *types.Block,
		round int32,
		state State,
		verify bool,
	) (CurrentRoundState, error)

	ValidateBlock(ctx context.Context, state State, block *types.Block) error

	ValidateBlockWithRoundState(
		ctx context.Context,
		state State,
		uncommittedState CurrentRoundState,
		block *types.Block,
	) error

	FinalizeBlock(
		ctx context.Context,
		state State,
		uncommittedState CurrentRoundState,
		blockID types.BlockID,
		block *types.Block,
		commit *types.Commit,
	) (State, error)

	ApplyBlock(
		ctx context.Context,
		state State,
		blockID types.BlockID,
		block *types.Block,
		commit *types.Commit,
	) (State, error)

	VerifyVoteExtension(ctx context.Context, vote *types.Vote) error
}

type Metrics

type Metrics struct {
	// Time between BeginBlock and EndBlock.
	BlockProcessingTime metrics.Histogram `metrics_buckettype:"lin" metrics_bucketsizes:"1,10,10"`

	// ConsensusParamUpdates is the total number of times the application has
	// udated the consensus params since process start.
	//metrics:Number of consensus parameter updates returned by the application since process start.
	ConsensusParamUpdates metrics.Counter

	// ValidatorSetUpdates is the total number of times the application has
	// udated the validator set since process start.
	//metrics:Number of validator set updates returned by the application since process start.
	ValidatorSetUpdates metrics.Counter
}

Metrics contains metrics exposed by this package.

func NopMetrics

func NopMetrics() *Metrics

func PrometheusMetrics

func PrometheusMetrics(namespace string, labelsAndValues ...string) *Metrics

type RoundParams

type RoundParams struct {
	AppHash               tmbytes.HexBytes
	TxResults             []*abci.ExecTxResult
	ConsensusParamUpdates *tmtypes.ConsensusParams
	ValidatorSetUpdate    *abci.ValidatorSetUpdate
	CoreChainLock         *types.CoreChainLock
	Source                string
	Round                 int32
}

RoundParams contains parameters received from ABCI which are necessary for reaching a consensus

func RoundParamsFromInitChain

func RoundParamsFromInitChain(resp *abci.ResponseInitChain) (RoundParams, error)

RoundParamsFromInitChain creates RoundParams from ResponseInitChain

func RoundParamsFromPrepareProposal

func RoundParamsFromPrepareProposal(resp *abci.ResponsePrepareProposal, round int32) (RoundParams, error)

RoundParamsFromPrepareProposal creates RoundParams from ResponsePrepareProposal

func RoundParamsFromProcessProposal

func RoundParamsFromProcessProposal(resp *abci.ResponseProcessProposal, coreChainLock *types.CoreChainLock, round int32) RoundParams

RoundParamsFromProcessProposal creates RoundParams from ResponseProcessProposal

func (RoundParams) ToProcessProposal

func (rp RoundParams) ToProcessProposal() *abci.ResponseProcessProposal

ToProcessProposal reconstructs ResponseProcessProposal structure from a current state of RoundParams

type State

type State struct {
	// FIXME: This can be removed as TMVersion is a constant, and version.Consensus should
	// eventually be replaced by VersionParams in ConsensusParams
	Version Version

	// immutable
	ChainID       string
	InitialHeight int64 // should be 1, not 0, when starting from height 1

	// LastBlockHeight=0 at genesis (ie. block(H=0) does not exist)
	LastBlockHeight int64
	LastBlockID     types.BlockID
	LastBlockTime   time.Time

	// Last Chain Lock is the last known chain locked height in consensus
	// It does not go to 0 if a block had no chain lock and should stay the same as the previous block
	LastCoreChainLockedBlockHeight uint32

	// LastValidators is used to validate block.LastPrecommits.
	// Validators are persisted to the database separately every time they change,
	// so we can query for historical validator sets.
	// Note that if s.LastBlockHeight causes a valset change,
	// we set s.LastHeightValidatorsChanged = s.LastBlockHeight + 1 + 1
	// Extra +1 due to nextValSet delay.
	Validators                  *types.ValidatorSet
	LastValidators              *types.ValidatorSet
	LastHeightValidatorsChanged int64

	// Consensus parameters used for validating blocks.
	// Changes returned by FinalizeBlock and updated after Commit.
	ConsensusParams                  types.ConsensusParams
	LastHeightConsensusParamsChanged int64

	// Merkle root of the results from executing prev block
	LastResultsHash tmbytes.HexBytes

	// the latest LastAppHash we've received from calling abci.Commit()
	LastAppHash tmbytes.HexBytes
}

State is a short description of the latest committed block of the Tendermint consensus. It keeps all information necessary to validate new blocks, including the last validator set and the consensus params. All fields are exposed so the struct can be easily serialized, but none of them should be mutated directly. Instead, use state.Copy() or updateState(...). NOTE: not goroutine-safe.

func FromProto

func FromProto(pb *tmstate.State) (*State, error)

FromProto takes a state proto message & returns the local state type

func MakeGenesisState

func MakeGenesisState(genDoc *types.GenesisDoc) (State, error)

MakeGenesisState creates state from types.GenesisDoc.

func MakeGenesisStateFromFile

func MakeGenesisStateFromFile(genDocFile string) (State, error)

MakeGenesisStateFromFile reads and unmarshals state from the given file.

Used during replay and in tests.

func (State) Bytes

func (state State) Bytes() ([]byte, error)

Bytes serializes the State using protobuf, propagating marshaling errors

func (State) Copy

func (state State) Copy() State

Copy makes a copy of the State for mutating.

func (State) Equals

func (state State) Equals(state2 State) (bool, error)

Equals returns true if the States are identical.

func (State) IsEmpty

func (state State) IsEmpty() bool

IsEmpty returns true if the State is equal to the empty State.

func (State) IsInitialHeight

func (state State) IsInitialHeight() bool

func (State) MakeBlock

func (state State) MakeBlock(
	height int64,
	txs []types.Tx,
	lastCommit *types.Commit,
	evidence []types.Evidence,
	proposerProTxHash types.ProTxHash,
	proposedAppVersion uint64,
) *types.Block

MakeBlock builds a block from the current state with the given txs, commit, and evidence. Note it also takes a proposerProTxHash because the state does not track rounds, and hence does not know the correct proposer. TODO: fix this!

func (State) NewStateChangeset

func (state State) NewStateChangeset(ctx context.Context, rp RoundParams) (CurrentRoundState, error)

NewStateChangeset returns a structure that will hold new changes to the state, that can be applied once the block is finalized

func (*State) ToProto

func (state *State) ToProto() (*tmstate.State, error)

ToProto takes the local state type and returns the equivalent proto type

func (State) Update

func (state State) Update(
	blockID types.BlockID,
	header *types.Header,
	candidateState *CurrentRoundState,
) (State, error)

Update returns a copy of state with the fields set using the arguments passed in.

func (State) ValidatorsAtHeight

func (state State) ValidatorsAtHeight(height int64) *types.ValidatorSet

type Store

type Store interface {
	// Load loads the current state of the blockchain
	Load() (State, error)
	// LoadValidators loads the validator set that is used to validate the given height
	LoadValidators(int64) (*types.ValidatorSet, error)
	// LoadABCIResponses loads the abciResponse for a given height
	LoadABCIResponses(int64) (*tmstate.ABCIResponses, error)
	// LoadConsensusParams loads the consensus params for a given height
	LoadConsensusParams(int64) (types.ConsensusParams, error)
	// Save overwrites the previous state with the updated one
	Save(State) error
	// SaveABCIResponses saves ABCIResponses for a given height
	SaveABCIResponses(int64, tmstate.ABCIResponses) error
	// SaveValidatorSet saves the validator set at a given height
	SaveValidatorSets(int64, int64, *types.ValidatorSet) error
	// Bootstrap is used for bootstrapping state when not starting from a initial height.
	Bootstrap(State) error
	// PruneStates takes the height from which to prune up to (exclusive)
	PruneStates(int64) error
	// Close closes the connection with the database
	Close() error
}

Store defines the state store interface

It is used to retrieve current state and save and load ABCI responses, validators and consensus parameters

func NewStore

func NewStore(db dbm.DB) Store

NewStore creates the dbStore of the state pkg.

type Version

type Version struct {
	Consensus version.Consensus ` json:"consensus"`
	Software  string            ` json:"software"`
}

func VersionFromProto

func VersionFromProto(v tmstate.Version) Version

func (*Version) ToProto

func (v *Version) ToProto() tmstate.Version

type VoteExtender

type VoteExtender interface {
	ExtendVote(ctx context.Context, vote *types.Vote)
}

Directories

Path Synopsis
Package indexer defines Tendermint's block and transaction event indexing logic.
Package indexer defines Tendermint's block and transaction event indexing logic.
sink/psql
Package psql implements an event sink backed by a PostgreSQL database.
Package psql implements an event sink backed by a PostgreSQL database.
test

Jump to

Keyboard shortcuts

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