avail

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2023 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package avail provides the implementation of the Avail consensus protocol for the blockchain network. Avail is a modular and flexible optimistic consensus mechanism designed to ensure secure and efficient transaction processing and block creation. It offers different node types, including Sequencer and WatchTower, each with specific roles and responsibilities in the consensus process.

The package includes functionalities for initializing and starting the Avail consensus mechanism, handling node synchronization, verifying block headers, processing headers, retrieving block creators, and managing account balances. It also provides hooks for pre-commit state operations and sealing blocks.

With Avail, nodes can participate in the consensus protocol, validate transactions, and contribute to the creation of new blocks. The consensus mechanism employs active participant querying and employs staking to ensure the integrity and security of the network.

Index

Constants

View Source
const (
	// AVL represents 1 Avail token which is equivalent to 10^18 fractions of an Avail token.
	AVL = 1_000_000_000_000_000_000

	// DefaultBlockProductionIntervalS represents the default interval in seconds for attempting block production.
	DefaultBlockProductionIntervalS = 1

	// StakingPollPeersIntervalMs is the interval in milliseconds to wait for when waiting for peers to come up before staking.
	StakingPollPeersIntervalMs = 200
)

Constants and Variables

Variables

View Source
var (
	ErrTxPoolHashNotFound          = errors.New("hash not found in the txpool")
	ChainProcessingDisabled uint32 = 0
	ChainProcessingEnabled  uint32 = 1
)

Functions

func MechanismExists

func MechanismExists(mechanism MechanismType) bool

MechanismExists is a helper function designed to check if a given MechanismType exists in the list of mechanism types. It returns true if the MechanismType exists and false otherwise.

func New

func New(config Config) (consensus.Consensus, error)

New creates and initializes a new instance of the Avail consensus protocol with the provided configuration. It also sets up necessary dependencies including the staking node, private signing key, miner address, snapshot distributor etc. It validates the configuration and returns the Avail consensus protocol instance. The function can panic if it fails to find or decode the signing key. Returns error if the configuration is invalid or it fails to setup any of the dependencies.

Types

type Avail

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

Avail represents the consensus protocol for the Avail network. It implements the Consensus interface and contains various configurations and mechanisms for consensus.

func (*Avail) Close

func (d *Avail) Close() error

Close closes the Avail consensus. It closes the internal close channel and returns nil.

func (*Avail) FilterExtra

func (d *Avail) FilterExtra(extra []byte) ([]byte, error)

FilterExtra is a method that is part of the consensus.BaseConsensus interface. As of now, the function returns the input 'extra' without any modifications. It does not perform any filtering operations.

func (*Avail) GetAccountBalance

func (d *Avail) GetAccountBalance(addr types.Address) (*big.Int, error)

GetAccountBalance retrieves the balance of an account. It fetches the latest header from Avail and returns the balance associated with the specified address. If the balance is not found or any error occurs, an error is returned.

func (*Avail) GetBlockCreator

func (d *Avail) GetBlockCreator(header *types.Header) (types.Address, error)

GetBlockCreator returns the address of the block creator for a given header. It delegates the retrieval process to the underlying verifier. The function returns the block creator address or an error if the retrieval fails.

func (*Avail) GetBridgeProvider

func (d *Avail) GetBridgeProvider() consensus.BridgeDataProvider

GetBridgeProvider returns an instance of BridgeDataProvider. As of now, the function returns nil as the BridgeDataProvider is not implemented.

func (*Avail) GetSyncProgression

func (d *Avail) GetSyncProgression() *progress.Progression

GetSyncProgression returns the progression of the node's sync process. As of now, the function returns nil as the sync progression is not implemented.

func (*Avail) Initialize

func (d *Avail) Initialize() error

Initialize verifies the initial balance of the miner's account. If the account does not exist or does not have a balance yet (returns a 'state not found' error), it returns nil. If the account's balance is less than the minimum required balance, the function attempts to find the account in the faucet. If the account is not found in the faucet or any other error occurs, an error is returned.

func (*Avail) PreCommitState

func (d *Avail) PreCommitState(header *types.Header, tx *state.Transition) error

PreCommitState is a hook called before finalizing the state transition on inserting a block. It delegates the pre-commit state process to the underlying verifier. The function returns an error if the pre-commit state operation fails.

func (*Avail) Prepare

func (d *Avail) Prepare(header *types.Header) error

Prepare is a method that is part of the consensus.BaseConsensus interface. As of now, the function is empty and does not perform any specific operations.

func (*Avail) ProcessHeaders

func (d *Avail) ProcessHeaders(headers []*types.Header) error

ProcessHeaders processes a batch of block headers. It delegates the processing to the underlying verifier. The function returns an error if any header fails to process.

func (*Avail) Seal

func (d *Avail) Seal(block *types.Block, ctx context.Context) (*types.Block, error)

Seal is a method that is part of the consensus.BaseConsensus interface. As of now, the function is empty and does not perform any specific operations.

func (*Avail) Start

func (d *Avail) Start() error

Start initiates the consensus mechanism. It enables P2P gossiping and verifies if the node type is not a BootstrapSequencer. For node types other than BootstrapSequencer, it ensures that at least one bootnode is available before syncing. If there are no nodes to push transactions towards, this function waits for 2 seconds before attempting to sync again. After a successful sync, the function checks the node type and starts the respective process. If the node type is invalid, an error is returned. Note: A panic occurs if the node fails to sync.

func (*Avail) VerifyHeader

func (d *Avail) VerifyHeader(header *types.Header) error

VerifyHeader verifies the validity of a block header. It delegates the verification process to the underlying verifier. The function returns an error if the header is invalid.

type Config

type Config struct {
	AccountFilePath       string
	AvailAccount          signature.KeyringPair
	AvailClient           avail.Client
	AvailSender           avail.Sender
	Blockchain            *blockchain.Blockchain
	BlockTime             uint64
	Bootnode              bool
	Chain                 *chain.Chain
	Context               context.Context
	Config                *consensus.Config
	Executor              *state.Executor
	FraudListenerAddr     string
	Logger                hclog.Logger
	Network               *network.Server
	NodeType              string
	SecretsManager        secrets.SecretsManager
	Snapshotter           snapshot.Snapshotter
	TxPool                *txpool.TxPool
	AvailAppID            avail_types.UCompact
	NumBlockConfirmations uint64
}

Config is a structure that holds various configuration options required by the Avail consensus protocol.

type Fraud

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

Fraud is a structure that represents the state of a node in a blockchain system that is capable of detecting and handling fraudulent activities. It contains various state data and services required to perform its function.

func NewFraudResolver

func NewFraudResolver(logger hclog.Logger, b *blockchain.Blockchain, e *state.Executor, txp *txpool.TxPool, w watchtower.WatchTower, blockProductionEnabled *atomic.Bool, nodeAddr types.Address, nodeSignKey *ecdsa.PrivateKey, availSender avail.Sender, nodeType MechanismType) *Fraud

NewFraudResolver creates a new FraudResolver instance which is used to detect and handle fraudulent activity within the blockchain network. The FraudResolver uses several components such as a logger, a blockchain, an executor, a transaction pool, and a watchtower to perform its functions. It also requires several settings such as the node address, node signing key, a sender for Avail network communication, and the node type (sequencer or watchtower). The created FraudResolver also includes information on the status of chain processing and block production.

func (*Fraud) CheckAndSetFraudBlock

func (f *Fraud) CheckAndSetFraudBlock(blocks []*types.Block) bool

CheckAndSetFraudBlock checks a list of blocks and sets a block suspected of fraud if it finds one. This is done by analyzing the extra data attached to a block.

func (*Fraud) CheckAndSlash

func (f *Fraud) CheckAndSlash() (bool, error)

CheckAndSlash conducts a fraud investigation. It checks if the system is ready to slash a fraudulent block, and if so, it retrieves the hash of the suspected fraudulent block and checks the existence of a block with this hash in the blockchain. If the suspected block does not exist or if the block was produced by the same node running this function, it logs the issue and returns. If the suspected block exists and was produced by a different node, it checks the block for fraud using the implemented watchtower mechanism. If the check detects fraud, the function initiates the process of slashing the node that created the block. If the check does not detect fraud, the function slashes the watchtower node instead, as it incorrectly flagged the block as fraudulent. The function returns true if a node was slashed and false if not, along with an error if any occurred.

func (*Fraud) DiscoverDisputeResolutionTx

func (f *Fraud) DiscoverDisputeResolutionTx(hash types.Hash) (*types.Transaction, error)

DiscoverDisputeResolutionTx searches for a transaction matching the provided hash within the transaction pool. The function iterates through the transaction pool, and upon finding a match, pops the transaction from the pool, logs its discovery, and returns it with a nil error. If no matching transaction is found, the function returns a nil transaction and an error stating the transaction hash was not found.

func (*Fraud) EndDisputeResolution

func (f *Fraud) EndDisputeResolution()

EndDisputeResolution ends the dispute resolution process for a suspected fraudulent block. This is done by resetting the fraud block and updating the chain status to enabled.

func (*Fraud) GetBeginDisputeResolutionTxHash

func (f *Fraud) GetBeginDisputeResolutionTxHash() types.Hash

GetBeginDisputeResolutionTxHash retrieves the hash of the transaction that initiated the dispute resolution process. This is done by extracting the dispute resolution target from the extra data in the fraud block's header.

func (*Fraud) GetBlock

func (f *Fraud) GetBlock() *types.Block

GetBlock returns the block that is currently suspected of fraud. This block is the one that is currently under dispute resolution.

func (*Fraud) IsChainDisabled

func (f *Fraud) IsChainDisabled() bool

IsChainDisabled checks if the chain processing has been disabled. This could be due to an ongoing fraud dispute or other reasons.

func (*Fraud) IsDisputeResolutionEnded

func (f *Fraud) IsDisputeResolutionEnded(blk *types.Header) bool

IsDisputeResolutionEnded checks if the dispute resolution for a suspected fraudulent block has ended. This is done by comparing the current block hash with the hash attached as extra data in the block.

func (*Fraud) IsFraudProofBlock

func (f *Fraud) IsFraudProofBlock(blk *types.Block) bool

IsFraudProofBlock checks if the given block has evidence of fraudulent activity. The function checks the block's extra data for a fraud proof target. If found, the function returns true. If not, it returns false.

func (*Fraud) IsReadyToSlash

func (f *Fraud) IsReadyToSlash() bool

IsReadyToSlash checks if the node is ready to slash a fraudulent block. Slashing is the process of penalizing a node that has been proven to perform fraudulent actions.

func (*Fraud) SetBlock

func (f *Fraud) SetBlock(b *types.Block)

SetBlock sets the block suspected of fraud. It is called when a block is detected as fraudulent and needs to be processed for dispute resolution.

func (*Fraud) SetChainStatus

func (f *Fraud) SetChainStatus(status uint32)

SetChainStatus is used to update the status of the chain processing. This status can be updated based on whether the chain is operating normally or is under a fraud dispute.

func (*Fraud) ShouldStopProducingBlocks

func (f *Fraud) ShouldStopProducingBlocks(activeParticipantsQuerier staking.ActiveParticipants)

ShouldStopProducingBlocks contains the main logic of the fraud detection system. It monitors the transaction pool and checks for any transactions indicating fraudulent activities. If it detects a fraud, it will update the chain status to disabled and stop producing new blocks.

type FraudServer

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

FraudServer is a server for managing and performing fraud detection operations. It uses a mutex for synchronization and a sync.Once to ensure fraud detection is performed exactly once per invocation.

func NewFraudServer

func NewFraudServer() *FraudServer

NewFraudServer creates a new instance of FraudServer with the mutex and fraudFn initialized. It returns a pointer to the new instance of FraudServer. The first invocation of fraudFn is disposed off immediately to make the FraudServer ready for subsequent uses.

func (*FraudServer) ListenAndServe

func (fs *FraudServer) ListenAndServe(addr string) error

ListenAndServe starts the FraudServer and listens for incoming HTTP requests on the specified address. It sets up a HTTP handler at "/fraud/prime" to prime the fraud detection operation for the next invocation.

func (*FraudServer) PerformFraud

func (fs *FraudServer) PerformFraud(f func())

PerformFraud takes a function as an argument and performs the fraud detection operation by calling the function exactly once. The function is performed under a mutex lock to ensure thread-safety.

func (*FraudServer) PrimeFraud

func (fs *FraudServer) PrimeFraud()

PrimeFraud resets the fraudFn to make it ready for the next invocation of fraud detection operation. It is performed under a mutex lock to ensure thread-safety.

type MechanismType

type MechanismType string

MechanismType represents the type of mechanism in the optimistic EVM rollup system. It is used to categorize and manipulate mechanisms based on their types.

const (
	BootstrapSequencer MechanismType = "bootstrap-sequencer"
	Sequencer          MechanismType = "sequencer"
	WatchTower         MechanismType = "watchtower"
)

MechanismType constants for the possible types of mechanisms.

func ParseMechanismConfigTypes

func ParseMechanismConfigTypes(mechanisms interface{}) ([]MechanismType, error)

ParseMechanismConfigTypes is a function that converts a list of string representations of mechanism types into a slice of MechanismType. It calls ParseType for each string in the list, and returns an error if any string does not correspond to a known MechanismType.

func ParseType

func ParseType(mechanism string) (MechanismType, error)

ParseType is a function that converts a string into a MechanismType. It checks if the conversion is possible and returns the corresponding MechanismType if it is, or an error if the string does not correspond to a known MechanismType.

func (MechanismType) LogString

func (t MechanismType) LogString() string

LogString is a method for representing a MechanismType as a string in a log-friendly format. It replaces dashes ("-") in the MechanismType with underscores ("_"), for better compatibility with logging systems.

func (MechanismType) String

func (t MechanismType) String() string

String is a method for representing a MechanismType as a string. It helps in casting a MechanismType to its string representation.

type SequencerWorker

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

SequencerWorker represents the struct for a Sequencer Worker. A Sequencer Worker is responsible for handling operations like running the block production process, snapshot processing, fraud detection and resolution, handling sequencer staking/unstaking, and more.

func NewSequencer

func NewSequencer(
	logger hclog.Logger, b *blockchain.Blockchain, e *state.Executor, txp *txpool.TxPool,
	snapshotter snapshot.Snapshotter, snapshotDistributor snapshot.Distributor,
	availClient avail.Client, availAccount signature.KeyringPair, availAppID avail_types.UCompact,
	nodeSignKey *ecdsa.PrivateKey, nodeAddr types.Address, nodeType MechanismType,
	apq staking.ActiveParticipants, stakingNode staking.Node, availSender avail.Sender, closeCh <-chan struct{},
	blockTime time.Duration, blockProductionIntervalSec uint64, currentNodeSyncIndex uint64,
	fraudListenerAddr string,
) (*SequencerWorker, error)

NewSequencer creates a new SequencerWorker. It returns an error if one occurs during the creation.

func (*SequencerWorker) IsNextSequencer

func (sw *SequencerWorker) IsNextSequencer(activeSequencersQuerier staking.ActiveSequencers) bool

IsNextSequencer checks if the current worker is the next sequencer. It queries the staked sequencers from the active sequencers querier, and compares the first sequencer with the node address of the current worker. If an error occurs during the querying, it logs the error and returns false. It returns true if the first sequencer is the current worker, false otherwise.

func (*SequencerWorker) Run

func (sw *SequencerWorker) Run(account accounts.Account, key *keystore.Key) error

Run starts the main operation of the SequencerWorker. It utilizes the given account and key to run various tasks like fraud detection and resolution, block production, snapshot processing, and more. Errors from these tasks are handled and appropriately logged.

type ValidatorSet

type ValidatorSet []types.Address

ValidatorSet represents a collection of addresses acting as validators in the optimistic EVM rollup system. It is implemented as a slice of Address values, each of which represents a unique validator in the network.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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