api

package
v0.2201.3 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2022 License: Apache-2.0 Imports: 23 Imported by: 10

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"

	// GasOpSubmitMsg is the gas operation identifier for message submission transaction cost.
	GasOpSubmitMsg transaction.Op = "submit_msg"
)
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 returned when an invalid evidence is submitted.
	ErrInvalidEvidence = errors.New(ModuleName, 10, "roothash: invalid evidence")

	// ErrIncomingMessageQueueFull is the error returned when the incoming message queue is full.
	ErrIncomingMessageQueueFull = errors.New(ModuleName, 11, "roothash: incoming message queue full")

	// ErrIncomingMessageInsufficientFee is the error returned when the provided fee is smaller than
	// the configured minimum incoming message submission fee.
	ErrIncomingMessageInsufficientFee = errors.New(ModuleName, 12, "roothash: insufficient fee")

	// ErrMaxInMessagesTooBig is the error returned when the MaxInMessages parameter is set to a
	// value larger than the MaxInRuntimeMessages specified in consensus parameters.
	ErrMaxInMessagesTooBig = errors.New(ModuleName, 13, "roothash: max incoming runtime messages is too big")

	// 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{})

	// MethodSubmitMsg is the method name for queuing incoming runtime messages.
	MethodSubmitMsg = transaction.NewMethodName(ModuleName, "SubmitMsg", SubmitMsg{})

	// Methods is a list of all methods supported by the roothash backend.
	Methods = []transaction.MethodName{
		MethodExecutorCommit,
		MethodExecutorProposerTimeout,
		MethodEvidence,
		MethodSubmitMsg,
	}
)

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 NewSubmitMsgTx added in v0.2200.0

func NewSubmitMsgTx(nonce uint64, fee *transaction.Fee, msg *SubmitMsg) *transaction.Transaction

NewSubmitMsgTx creates a new incoming runtime message submission 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)

	// GetLastRoundResults returns the given runtime's last normal round results.
	GetLastRoundResults(ctx context.Context, request *RuntimeRequest) (*RoundResults, error)

	// GetIncomingMessageQueueMeta returns the given runtime's incoming message queue metadata.
	GetIncomingMessageQueueMeta(ctx context.Context, request *RuntimeRequest) (*message.IncomingMessageQueueMeta, error)

	// GetIncomingMessageQueue returns the given runtime's queued incoming messages.
	GetIncomingMessageQueue(ctx context.Context, request *InMessageQueueRequest) ([]*message.IncomingMessage, 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"`

	// MaxInRuntimeMessages is the maximum number of allowed incoming messages that can be queued.
	MaxInRuntimeMessages uint32 `json:"max_in_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 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 EquivocationProposalEvidence added in v0.2200.0

type EquivocationProposalEvidence struct {
	ProposalA commitment.Proposal `json:"prop_a"`
	ProposalB commitment.Proposal `json:"prop_b"`
}

EquivocationProposalEvidence is evidence of executor proposed batch equivocation.

func (*EquivocationProposalEvidence) ValidateBasic added in v0.2200.0

func (ev *EquivocationProposalEvidence) 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 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"`
	InMsgProcessed               *InMsgProcessedEvent               `json:"in_msg_processed,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"`
	EquivocationProposal *EquivocationProposalEvidence `json:"equivocation_prop,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.

func (*ExecutionDiscrepancyDetectedEvent) EventKind added in v0.2200.0

EventKind returns a string representation of this event's kind.

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.

func (*ExecutorCommittedEvent) EventKind added in v0.2200.0

func (e *ExecutorCommittedEvent) EventKind() string

EventKind returns a string representation of this event's kind.

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"`
}

FinalizedEvent is a finalized event.

func (*FinalizedEvent) EventKind added in v0.2200.0

func (e *FinalizedEvent) EventKind() string

EventKind returns a string representation of this event's kind.

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 InMessageQueueRequest added in v0.2200.0

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

	Offset uint64 `json:"offset,omitempty"`
	Limit  uint32 `json:"limit,omitempty"`
}

InMessageQueueRequest is a request for queued incoming messages.

type InMsgProcessedEvent added in v0.2200.0

type InMsgProcessedEvent struct {
	// ID is the unique incoming message identifier.
	ID uint64 `json:"id"`
	// Round is the round where the incoming message was processed.
	Round uint64 `json:"round"`
	// Caller is the incoming message submitter address.
	Caller staking.Address `json:"caller"`
	// Tag is an optional tag provided by the caller.
	Tag uint64 `json:"tag,omitempty"`
}

InMsgProcessedEvent is an event of a specific incoming message being processed.

In order to see details one needs to query the runtime at the specified round.

func (*InMsgProcessedEvent) EventKind added in v0.2200.0

func (e *InMsgProcessedEvent) EventKind() string

EventKind returns a string representation of this event's kind.

type LivenessStatistics added in v0.2200.0

type LivenessStatistics struct {
	// TotalRounds is the total number of rounds in the last epoch, excluding any rounds generated
	// by the roothash service itself.
	TotalRounds uint64 `json:"total_rounds"`

	// LiveRounds is a list of counters, specified in committee order (e.g. counter at index i has
	// the value for node i in the committee).
	LiveRounds []uint64 `json:"good_rounds"`
}

LivenessStatistics has the per-epoch liveness statistics for nodes.

func NewLivenessStatistics added in v0.2200.0

func NewLivenessStatistics(numNodes int) *LivenessStatistics

NewLivenessStatistics creates a new instance of per-epoch liveness statistics.

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"`

	// Result contains CBOR-encoded message execution result for successfully executed messages.
	Result cbor.RawMessage `json:"result,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 RuntimeIDAttribute added in v0.2200.0

type RuntimeIDAttribute struct {
	ID common.Namespace
}

RuntimeIDAttribute is the event attribute for specifying runtime ID. ID is base64 encoded runtime ID.

func (*RuntimeIDAttribute) DecodeValue added in v0.2200.0

func (e *RuntimeIDAttribute) DecodeValue(value string) error

DecodeValue decodes the attribute event value.

func (*RuntimeIDAttribute) EventKind added in v0.2200.0

func (e *RuntimeIDAttribute) EventKind() string

EventKind returns a string representation of this event's kind.

func (*RuntimeIDAttribute) EventValue added in v0.2200.0

func (e *RuntimeIDAttribute) EventValue() string

EventValue returns a string representation of this event's kind.

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 contains the executor commitment pool.
	ExecutorPool *commitment.Pool `json:"executor_pool"`

	// LivenessStatistics contains the liveness statistics for the current epoch.
	LivenessStatistics *LivenessStatistics `json:"liveness_stats"`
}

RuntimeState is the per-runtime state.

type SubmitMsg added in v0.2200.0

type SubmitMsg struct {
	// ID is the destination runtime ID.
	ID common.Namespace `json:"id"`
	// Tag is an optional tag provided by the caller which is ignored and can be used to match
	// processed incoming message events later.
	Tag uint64 `json:"tag,omitempty"`
	// Fee is the fee sent into the runtime as part of the message being sent. The fee is
	// transferred before the message is processed by the runtime.
	Fee quantity.Quantity `json:"fee,omitempty"`
	// Tokens are any tokens sent into the runtime as part of the message being sent. The tokens are
	// transferred before the message is processed by the runtime.
	Tokens quantity.Quantity `json:"tokens,omitempty"`
	// Data is arbitrary runtime-dependent data.
	Data []byte `json:"data,omitempty"`
}

SubmitMsg is the argument set for the SubmitMsg method.

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