api

package
v0.2103.7 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2021 License: Apache-2.0 Imports: 17 Imported by: 8

Documentation

Overview

Package api implements the root hash backend API and common datastructures.

Index

Constants

View Source
const (
	// ModuleName is a unique module name for the roothash module.
	ModuleName = "roothash"

	// RoundInvalid is a special round number that refers to an invalid round.
	RoundInvalid uint64 = math.MaxUint64

	// LogEventExecutionDiscrepancyDetected is a log event value that signals
	// an execution discrepancy has been detected.
	LogEventExecutionDiscrepancyDetected = "roothash/execution_discrepancy_detected"
	// LogEventTimerFired is a log event value that signals a timer has fired.
	LogEventTimerFired = "roothash/timer_fired"
	// LogEventRoundFailed is a log event value that signals a round has failed.
	LogEventRoundFailed = "roothash/round_failed"
	// LogEventMessageUnsat is a log event value that signals a roothash message was not satisfactory.
	LogEventMessageUnsat = "roothash/message_unsat"
	// LogEventHistoryReindexing is a log event value that signals a roothash runtime reindexing
	// was run.
	LogEventHistoryReindexing = "roothash/history_reindexing"
)
View Source
const (
	// GasOpComputeCommit is the gas operation identifier for compute commits.
	GasOpComputeCommit transaction.Op = "compute_commit"

	// GasOpProposerTimeout is the gas operation identifier for executor propose timeout cost.
	GasOpProposerTimeout transaction.Op = "proposer_timeout"

	// GasOpEvidence is the gas operation identifier for evidence submission transaction cost.
	GasOpEvidence transaction.Op = "evidence"
)
View Source
const (
	// EvidenceKindEquivocation is the evidence kind for equivocation.
	EvidenceKindEquivocation = 1
)
View Source
const RoundLatest = RoundInvalid

RoundLatest is a special round number always referring to the latest round.

Variables

View Source
var (
	// ErrInvalidArgument is the error returned on malformed argument(s).
	ErrInvalidArgument = errors.New(ModuleName, 1, "roothash: invalid argument")

	// ErrNotFound is the error returned when a block is not found.
	ErrNotFound = errors.New(ModuleName, 2, "roothash: block not found")

	// ErrInvalidRuntime is the error returned when the passed runtime is invalid.
	ErrInvalidRuntime = errors.New(ModuleName, 3, "roothash: invalid runtime")

	// ErrNoExecutorPool is the error returned when there is no executor pool.
	ErrNoExecutorPool = errors.New(ModuleName, 4, "roothash: no executor pool")

	// ErrRuntimeSuspended is the error returned when the passed runtime is suspended.
	ErrRuntimeSuspended = errors.New(ModuleName, 5, "roothash: runtime is suspended")

	// ErrProposerTimeoutNotAllowed is the error returned when proposer timeout is not allowed.
	ErrProposerTimeoutNotAllowed = errors.New(ModuleName, 6, "roothash: proposer timeout not allowed")

	// ErrMaxMessagesTooBig is the error returned when the MaxMessages parameter is set to a value
	// larger than the MaxRuntimeMessages specified in consensus parameters.
	ErrMaxMessagesTooBig = errors.New(ModuleName, 7, "roothash: max runtime messages is too big")

	// ErrRuntimeDoesNotSlash is the error returned when misbehaviour evidence is submitted for a
	// runtime that does not slash.
	ErrRuntimeDoesNotSlash = errors.New(ModuleName, 8, "roothash: runtime does not slash")

	// ErrDuplicateEvidence is the error returned when submitting already existing evidence.
	ErrDuplicateEvidence = errors.New(ModuleName, 9, "roothash: duplicate evidence")

	// ErrInvalidEvidence is the error return when an invalid evidence is submitted.
	ErrInvalidEvidence = errors.New(ModuleName, 10, "roothash: invalid evidence")

	// MethodExecutorCommit is the method name for executor commit submission.
	MethodExecutorCommit = transaction.NewMethodName(ModuleName, "ExecutorCommit", ExecutorCommit{})

	// MethodExecutorProposerTimeout is the method name for executor proposer timeout.
	MethodExecutorProposerTimeout = transaction.NewMethodName(ModuleName, "ExecutorProposerTimeout", ExecutorProposerTimeoutRequest{})

	// MethodEvidence is the method name for submitting evidence of node misbehavior.
	MethodEvidence = transaction.NewMethodName(ModuleName, "Evidence", Evidence{})

	// Methods is a list of all methods supported by the roothash backend.
	Methods = []transaction.MethodName{
		MethodExecutorCommit,
		MethodExecutorProposerTimeout,
		MethodEvidence,
	}
)
View Source
var DefaultGasCosts = transaction.Costs{
	GasOpComputeCommit:   1000,
	GasOpProposerTimeout: 1000,
	GasOpEvidence:        1000,
}

DefaultGasCosts are the "default" gas costs for operations.

Functions

func NewEvidenceTx added in v0.2100.0

func NewEvidenceTx(nonce uint64, fee *transaction.Fee, evidence *Evidence) *transaction.Transaction

NewEvidenceTx creates a new evidence transaction.

func NewExecutorCommitTx

func NewExecutorCommitTx(nonce uint64, fee *transaction.Fee, runtimeID common.Namespace, commits []commitment.ExecutorCommitment) *transaction.Transaction

NewExecutorCommitTx creates a new executor commit transaction.

func NewRequestProposerTimeoutTx added in v0.2010.0

func NewRequestProposerTimeoutTx(nonce uint64, fee *transaction.Fee, runtimeID common.Namespace, round uint64) *transaction.Transaction

NewRequestProposerTimeoutTx creates a new request proposer timeout transaction.

func RegisterService added in v0.2102.0

func RegisterService(server *grpc.Server, service Backend)

RegisterService registers a new roothash service with the given gRPC server.

func SanityCheckBlocks

func SanityCheckBlocks(blocks map[common.Namespace]*block.Block) error

SanityCheckBlocks examines the blocks table.

func VerifyRuntimeParameters added in v0.2100.0

func VerifyRuntimeParameters(logger *logging.Logger, rt *registry.Runtime, params *ConsensusParameters) error

VerifyRuntimeParameters verifies whether the runtime parameters are valid in the context of the roothash service.

Types

type AnnotatedBlock

type AnnotatedBlock struct {
	// Height is the underlying roothash backend's block height that
	// generated this block.
	Height int64 `json:"consensus_height"`

	// Block is the roothash block.
	Block *block.Block `json:"block"`
}

AnnotatedBlock is an annotated roothash block.

type Backend

type Backend interface {
	// GetGenesisBlock returns the genesis block.
	GetGenesisBlock(ctx context.Context, request *RuntimeRequest) (*block.Block, error)

	// GetLatestBlock returns the latest block.
	//
	// The metadata contained in this block can be further used to get
	// the latest state from the storage backend.
	GetLatestBlock(ctx context.Context, request *RuntimeRequest) (*block.Block, error)

	// GetRuntimeState returns the given runtime's state.
	GetRuntimeState(ctx context.Context, request *RuntimeRequest) (*RuntimeState, error)

	// WatchBlocks returns a channel that produces a stream of
	// annotated blocks.
	//
	// The latest block if any will get pushed to the stream immediately.
	// Subsequent blocks will be pushed into the stream as they are
	// confirmed.
	WatchBlocks(ctx context.Context, runtimeID common.Namespace) (<-chan *AnnotatedBlock, pubsub.ClosableSubscription, error)

	// WatchEvents returns a stream of protocol events.
	WatchEvents(ctx context.Context, runtimeID common.Namespace) (<-chan *Event, pubsub.ClosableSubscription, error)

	// TrackRuntime adds a runtime the history of which should be tracked.
	TrackRuntime(ctx context.Context, history BlockHistory) error

	// StateToGenesis returns the genesis state at specified block height.
	StateToGenesis(ctx context.Context, height int64) (*Genesis, error)

	// ConsensusParameters returns the roothash consensus parameters.
	ConsensusParameters(ctx context.Context, height int64) (*ConsensusParameters, error)

	// GetEvents returns the events at specified block height.
	GetEvents(ctx context.Context, height int64) ([]*Event, error)

	// Cleanup cleans up the roothash backend.
	Cleanup()
}

Backend is a root hash implementation.

func NewRootHashClient added in v0.2102.0

func NewRootHashClient(c *grpc.ClientConn) Backend

NewRootHashClient creates a new gRPC roothash client service.

type BlockHistory

type BlockHistory interface {
	// RuntimeID returns the runtime ID of the runtime this block history is for.
	RuntimeID() common.Namespace

	// Commit commits an annotated block into history.
	//
	// Must be called in order, sorted by round.
	Commit(blk *AnnotatedBlock, roundResults *RoundResults) error

	// ConsensusCheckpoint records the last consensus height which was processed
	// by the roothash backend.
	//
	// This method can only be called once all roothash blocks for consensus
	// heights <= height have been committed using Commit.
	ConsensusCheckpoint(height int64) error

	// LastConsensusHeight returns the last consensus height which was seen
	// by block history.
	LastConsensusHeight() (int64, error)

	// GetBlock returns the block at a specific round.
	//
	// Passing the special value `RoundLatest` will return the latest block.
	GetBlock(ctx context.Context, round uint64) (*block.Block, error)

	// GetAnnotatedBlock returns the annotated block at a specific round.
	//
	// Passing the special value `RoundLatest` will return the latest annotated block.
	GetAnnotatedBlock(ctx context.Context, round uint64) (*AnnotatedBlock, error)

	// GetEarliestBlock returns the earliest known block.
	GetEarliestBlock(ctx context.Context) (*block.Block, error)

	// GetRoundResults returns the round results for the given round.
	//
	// Passing the special value `RoundLatest` will return results for the latest round.
	GetRoundResults(ctx context.Context, round uint64) (*RoundResults, error)
}

BlockHistory is the root hash block history keeper interface.

All methods operate on a specific runtime.

type ConsensusParameters

type ConsensusParameters struct {
	// GasCosts are the roothash transaction gas costs.
	GasCosts transaction.Costs `json:"gas_costs,omitempty"`

	// DebugDoNotSuspendRuntimes is true iff runtimes should not be suspended
	// for lack of paying maintenance fees.
	DebugDoNotSuspendRuntimes bool `json:"debug_do_not_suspend_runtimes,omitempty"`

	// DebugBypassStake is true iff the roothash should bypass all of the staking
	// related checks and operations.
	DebugBypassStake bool `json:"debug_bypass_stake,omitempty"`

	// MaxRuntimeMessages is the maximum number of allowed messages that can be emitted by a runtime
	// in a single round.
	MaxRuntimeMessages uint32 `json:"max_runtime_messages"`

	// MaxEvidenceAge is the maximum age of submitted evidence in the number of rounds.
	MaxEvidenceAge uint64 `json:"max_evidence_age"`
}

ConsensusParameters are the roothash consensus parameters.

type EquivocationBatchEvidence added in v0.2100.0

type EquivocationBatchEvidence struct {
	BatchA commitment.SignedProposedBatch `json:"batch_a"`
	BatchB commitment.SignedProposedBatch `json:"batch_b"`
}

EquivocationBatchEvidence is evidence of executor proposed batch equivocation.

func (*EquivocationBatchEvidence) ValidateBasic added in v0.2100.0

func (ev *EquivocationBatchEvidence) ValidateBasic(id common.Namespace) error

ValidateBasic performs stateless batch evidence validation checks.

Particularly evidence is not verified to not be expired as this requires stateful checks.

type EquivocationExecutorEvidence added in v0.2100.0

type EquivocationExecutorEvidence struct {
	CommitA commitment.ExecutorCommitment `json:"commit_a"`
	CommitB commitment.ExecutorCommitment `json:"commit_b"`
}

EquivocationExecutorEvidence is evidence of executor commitment equivocation.

func (*EquivocationExecutorEvidence) ValidateBasic added in v0.2100.0

func (ev *EquivocationExecutorEvidence) ValidateBasic(id common.Namespace) error

ValidateBasic performs stateless executor evidence validation checks.

Particularly evidence is not verified to not be expired as this requires stateful checks.

type Event

type Event struct {
	Height int64     `json:"height,omitempty"`
	TxHash hash.Hash `json:"tx_hash,omitempty"`

	RuntimeID common.Namespace `json:"runtime_id"`

	ExecutorCommitted            *ExecutorCommittedEvent            `json:"executor_committed,omitempty"`
	ExecutionDiscrepancyDetected *ExecutionDiscrepancyDetectedEvent `json:"execution_discrepancy,omitempty"`
	Finalized                    *FinalizedEvent                    `json:"finalized,omitempty"`
	Message                      *MessageEvent                      `json:"message,omitempty"`
}

Event is a roothash event.

type Evidence added in v0.2100.0

type Evidence struct {
	ID common.Namespace `json:"id"`

	EquivocationExecutor *EquivocationExecutorEvidence `json:"equivocation_executor,omitempty"`
	EquivocationBatch    *EquivocationBatchEvidence    `json:"equivocation_batch,omitempty"`
}

Evidence is an evidence of node misbehaviour.

func (*Evidence) Hash added in v0.2100.0

func (ev *Evidence) Hash() (hash.Hash, error)

Hash computes the evidence hash.

Hash is derived by hashing the evidence kind and the public key of the signer. Assumes evidence has been validated.

func (*Evidence) ValidateBasic added in v0.2100.0

func (ev *Evidence) ValidateBasic() error

ValidateBasic performs basic evidence validity checks.

type EvidenceKind added in v0.2100.0

type EvidenceKind uint8

EvidenceKind is the evidence kind.

type ExecutionDiscrepancyDetectedEvent

type ExecutionDiscrepancyDetectedEvent struct {
	// Timeout signals whether the discrepancy was due to a timeout.
	Timeout bool `json:"timeout"`
}

ExecutionDiscrepancyDetectedEvent is an execute discrepancy detected event.

type ExecutorCommit

type ExecutorCommit struct {
	ID      common.Namespace                `json:"id"`
	Commits []commitment.ExecutorCommitment `json:"commits"`
}

ExecutorCommit is the argument set for the ExecutorCommit method.

type ExecutorCommittedEvent

type ExecutorCommittedEvent struct {
	// Commit is the executor commitment.
	Commit commitment.ExecutorCommitment `json:"commit"`
}

ExecutorCommittedEvent is an event emitted each time an executor node commits.

type ExecutorProposerTimeoutRequest added in v0.2010.0

type ExecutorProposerTimeoutRequest struct {
	ID    common.Namespace `json:"id"`
	Round uint64           `json:"round"`
}

ExecutorProposerTimeoutRequest is an executor proposer timeout request.

type FinalizedEvent

type FinalizedEvent struct {
	// Round is the round that was finalized.
	Round uint64 `json:"round"`

	// GoodComputeNodes are the public keys of compute nodes that positively contributed to the
	// round by replicating the computation correctly.
	GoodComputeNodes []signature.PublicKey `json:"good_compute_nodes,omitempty"`

	// BadComputeNodes are the public keys of compute nodes that negatively contributed to the round
	// by causing discrepancies.
	BadComputeNodes []signature.PublicKey `json:"bad_compute_nodes,omitempty"`
}

FinalizedEvent is a finalized event.

type Genesis

type Genesis struct {
	// Parameters are the roothash consensus parameters.
	Parameters ConsensusParameters `json:"params"`

	// RuntimeStates are the runtime states at genesis.
	RuntimeStates map[common.Namespace]*GenesisRuntimeState `json:"runtime_states,omitempty"`
}

Genesis is the roothash genesis state.

func (*Genesis) SanityCheck

func (g *Genesis) SanityCheck() error

SanityCheck does basic sanity checking on the genesis state.

type GenesisRuntimeState added in v0.2100.0

type GenesisRuntimeState struct {
	registry.RuntimeGenesis

	// MessageResults are the message results emitted at the last processed round.
	MessageResults []*MessageEvent `json:"message_results,omitempty"`
}

GenesisRuntimeState contains state for runtimes that are restored in a genesis block.

type MessageEvent added in v0.2100.0

type MessageEvent struct {
	Module string `json:"module,omitempty"`
	Code   uint32 `json:"code,omitempty"`
	Index  uint32 `json:"index,omitempty"`
}

MessageEvent is a runtime message processed event.

func (*MessageEvent) IsSuccess added in v0.2100.0

func (me *MessageEvent) IsSuccess() bool

IsSuccess returns true if the event indicates that the message was successfully processed.

type MetricsMonitorable

type MetricsMonitorable interface {
	// WatchAllBlocks returns a channel that produces a stream of blocks.
	//
	// All blocks from all tracked runtimes will be pushed into the stream
	// immediately as they are finalized.
	WatchAllBlocks() (<-chan *block.Block, *pubsub.Subscription)
}

MetricsMonitorable is the interface exposed by backends capable of providing metrics data.

type RoundResults added in v0.2100.0

type RoundResults struct {
	// Messages are the results of executing emitted runtime messages.
	Messages []*MessageEvent `json:"messages,omitempty"`

	// GoodComputeEntities are the public keys of compute nodes' controlling entities that
	// positively contributed to the round by replicating the computation correctly.
	GoodComputeEntities []signature.PublicKey `json:"good_compute_entities,omitempty"`
	// BadComputeEntities are the public keys of compute nodes' controlling entities that
	// negatively contributed to the round by causing discrepancies.
	BadComputeEntities []signature.PublicKey `json:"bad_compute_entities,omitempty"`
}

RoundResults contains information about how a particular round was executed by the consensus layer.

type RuntimeRequest added in v0.2102.0

type RuntimeRequest struct {
	RuntimeID common.Namespace `json:"runtime_id"`
	Height    int64            `json:"height"`
}

RuntimeRequest is a generic roothash get request for a specific runtime.

type RuntimeState added in v0.2100.0

type RuntimeState struct {
	Runtime   *registry.Runtime `json:"runtime"`
	Suspended bool              `json:"suspended,omitempty"`

	GenesisBlock *block.Block `json:"genesis_block"`

	CurrentBlock       *block.Block `json:"current_block"`
	CurrentBlockHeight int64        `json:"current_block_height"`

	// LastNormalRound is the runtime round which was normally processed by the runtime. This is
	// also the round that contains the message results for the last processed runtime messages.
	LastNormalRound uint64 `json:"last_normal_round"`
	// LastNormalHeight is the consensus block height corresponding to LastNormalRound.
	LastNormalHeight int64 `json:"last_normal_height"`

	ExecutorPool *commitment.Pool `json:"executor_pool"`
}

RuntimeState is the per-runtime state.

Directories

Path Synopsis
Package block implements the roothash block and header.
Package block implements the roothash block and header.
Package commitment defines a roothash commitment.
Package commitment defines a roothash commitment.
Package message implements the supported runtime messages.
Package message implements the supported runtime messages.

Jump to

Keyboard shortcuts

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