consensus

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2020 License: MIT Imports: 25 Imported by: 12

Documentation

Index

Constants

View Source
const (
	// DatabaseFilename contains the filename of the database that will be used
	// when managing consensus.
	DatabaseFilename = modules.ConsensusDir + ".db"
)

Variables

View Source
var (
	// ChangeLog contains a list of atomic changes that have happened to the
	// consensus set so that subscribers can subscribe from the most recent
	// change they have seen.
	ChangeLog = []byte("ChangeLog")

	// ChangeLogTailID is a key that points to the id of the current changelog
	// tail.
	ChangeLogTailID = []byte("ChangeLogTailID")
)
View Source
var (

	// BlockHeight is a bucket that stores the current block height.
	//
	// Generally we would just look at BlockPath.Stats(), but there is an error
	// in boltdb that prevents the bucket stats from updating until a tx is
	// committed. Wasn't a problem until we started doing the entire block as
	// one tx.
	//
	// DEPRECATED - block.Stats() should be sufficient to determine the block
	// height, but currently stats are only computed after committing a
	// transaction, therefore cannot be assumed reliable.
	BlockHeight = []byte("BlockHeight")

	// BlockMap is a database bucket containing all of the processed blocks,
	// keyed by their id. This includes blocks that are not currently in the
	// consensus set, and blocks that may not have been fully validated yet.
	BlockMap = []byte("BlockMap")

	// BlockPath is a database bucket containing a mapping from the height of a
	// block to the id of the block at that height. BlockPath only includes
	// blocks in the current path.
	BlockPath = []byte("BlockPath")

	// Consistency is a database bucket with a flag indicating whether
	// inconsistencies within the database have been detected.
	Consistency = []byte("Consistency")

	// CoinOutputs is a database bucket that contains all of the unspent
	// coin outputs.
	CoinOutputs = []byte("CoinOutputs")

	// BlockStakeOutputs is a database bucket that contains all of the unspent
	// blockstake outputs.
	BlockStakeOutputs = []byte("BlockStakeOutputs")

	// TransactionIDMap is a database bucket that containsall of the present
	// transaction IDs linked to their short ID
	TransactionIDMap = []byte("TransactionIDMap")

	// BucketPlugins is a database buckets that contains all plugins and their metadata.
	BucketPlugins = []byte("Plugins")
)
View Source
var (
	// ErrPluginNameReserved is returned in case a plugin with that name
	// is not allowed because it is a reserved bucket name.
	ErrPluginNameReserved = errors.New("plugin bucket name is reserved")
	// ErrPluginNameEmpty is returned in case a plugin with that name is empty.
	ErrPluginNameEmpty = errors.New("plugin bucket name cannot be empty")
	// ErrPluginExists is returned in case a plugin with the same name is registered.
	ErrPluginExists = errors.New("a plugin with that name is already registered")
)

plugin user errors

View Source
var (
	// ErrPluginGhostMetadata is returned in case a plugin which wasn't registered yet, does have metadata.
	ErrPluginGhostMetadata = errors.New("a plugin that wasn't registered yet does have metadata")
	// ErrMissingPluginMetadata is returned in case a plugin is missing metadata.
	ErrMissingPluginMetadata = errors.New("the metadata of the plugin is missing")
	// ErrMissingMetadataBucket is returned in case root plugins metadata folder is missing
	ErrMissingMetadataBucket = errors.New("root plugins metadata folder is missing")
)

plugin system errors

View Source
var (
	// MaxCatchUpBlocks is the maxiumum number of blocks that can be given to
	// the consensus set in a single iteration during the initial blockchain
	// download.
	MaxCatchUpBlocks = func() types.BlockHeight {
		switch build.Release {
		case "dev":
			return 50
		case "testing":
			return 3
		default:
			if build.Release != "standard" {
				build.Severe("unrecognized build.Release")
			}
			return 10
		}
	}()
)
View Source
var SurpassThreshold = big.NewRat(20, 100)

SurpassThreshold is a percentage that dictates how much heavier a competing chain has to be before the node will switch to mining on that chain. This is not a consensus rule. This percentage is only applied to the most recent block, not the entire chain; see blockNode.heavierThan.

If no threshold were in place, it would be possible to manipulate a block's timestamp to produce a sufficiently heavier block.

Functions

func StandardTransactionValidators added in v1.2.0

func StandardTransactionValidators() []modules.TransactionValidationFunction

StandardTransactionValidators returns the standard transaction validators that are used if no custom set of transaction validators (effecitively rules that apply to every transaction) are defined, or if `nil` rules are set, in which case these default validators will be used as well.

func StandardTransactionVersionMappedValidators added in v1.2.0

func StandardTransactionVersionMappedValidators() map[types.TransactionVersion][]modules.TransactionValidationFunction

StandardTransactionVersionMappedValidators returns the standard version-mapped transaction validators that are used if no custom set of transaction validators (effecitively rules that apply to every transaction) are defined, or if `nil` rules are set, in which case these default validators will be used as well.

func ValidateBlockStakeInputsAreFulfilled added in v1.2.0

func ValidateBlockStakeInputsAreFulfilled(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateBlockStakeInputsAreFulfilled validates that all block stake inputs are fulfilled

func ValidateBlockStakeInputsAreValid added in v1.2.0

func ValidateBlockStakeInputsAreValid(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateBlockStakeInputsAreValid is a validator function that checks if all block stake inputs are standard, meaning their fulfillment is considered standard (== known) and their parent ID is defined.

func ValidateBlockStakeOutputsAreBalanced added in v1.2.0

func ValidateBlockStakeOutputsAreBalanced(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateBlockStakeOutputsAreBalanced is a validator function that checks if the sum of all block stakes outputs equals the sum of all block stake inputs.

func ValidateBlockStakeOutputsAreValid added in v1.2.0

func ValidateBlockStakeOutputsAreValid(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateBlockStakeOutputsAreValid is a validator function that checks if all block stake output is standard, meaning their condition is considered standard (== known) and their (block stake) value is individually greater than zero.

func ValidateCoinInputsAreFulfilled added in v1.2.0

func ValidateCoinInputsAreFulfilled(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateCoinInputsAreFulfilled validates that all coin outputs are validated

func ValidateCoinInputsAreValid added in v1.2.0

func ValidateCoinInputsAreValid(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateCoinInputsAreValid is a validator function that checks if all coin inputs are standard, meaning their fulfillment is considered standard (== known) and their parent ID is defined.

func ValidateCoinOutputsAreBalanced added in v1.2.0

func ValidateCoinOutputsAreBalanced(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateCoinOutputsAreBalanced is a validator function that checks if the sum of all types of coin outputs equals the sum of coin inputs.

func ValidateCoinOutputsAreValid added in v1.2.0

func ValidateCoinOutputsAreValid(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateCoinOutputsAreValid is a validator function that checks if all coin outputs are standard, meaning their condition is considered standard (== known) and their (coin) value is individually greater than zero.

func ValidateDoubleBlockStakeSpends added in v1.2.0

func ValidateDoubleBlockStakeSpends(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateDoubleBlockStakeSpends validates that no block stake output is spent twice.

func ValidateDoubleCoinSpends added in v1.2.0

func ValidateDoubleCoinSpends(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateDoubleCoinSpends validates that no coin output is spent twice.

func ValidateInvalidByDefault added in v1.2.0

ValidateInvalidByDefault returns always an error and can be used to not allow transactions to be validated.

func ValidateMinerFeeIsPresent added in v1.2.0

func ValidateMinerFeeIsPresent(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateMinerFeeIsPresent is a validator function that checks that at least one miner fee is present

func ValidateMinerFeesAreValid added in v1.2.0

func ValidateMinerFeesAreValid(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateMinerFeesAreValid is a validator function that checks if all miner fees are valid, meaning their (coin) value is individually greater than zero.

func ValidateTransactionArbitraryData added in v1.2.0

func ValidateTransactionArbitraryData(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateTransactionArbitraryData is a validator function that checks if a transaction's arbitrary data is valid

func ValidateTransactionFitsInABlock added in v1.2.0

func ValidateTransactionFitsInABlock(tx modules.ConsensusTransaction, ctx types.TransactionValidationContext) error

ValidateTransactionFitsInABlock is a validator function that checks if a transaction fits in a block

Types

type ConsensusSet

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

The ConsensusSet is the object responsible for tracking the current status of the blockchain. Broadly speaking, it is responsible for maintaining consensus. It accepts blocks and constructs a blockchain, forking when necessary.

func New

func New(gateway modules.Gateway, bootstrap bool, persistDir string, bcInfo types.BlockchainInfo, chainCts types.ChainConstants, verboseLogging bool, dbDebugFile string) (*ConsensusSet, error)

New returns a new ConsensusSet, containing at least the genesis block. If there is an existing block database present in the persist directory, it will be loaded.

func (*ConsensusSet) AcceptBlock

func (cs *ConsensusSet) AcceptBlock(b types.Block) error

AcceptBlock will try to add a block to the consensus set. If the block does not extend the longest currently known chain, an error is returned but the block is still kept in memory. If the block extends a fork such that the fork becomes the longest currently known chain, the consensus set will reorganize itself to recognize the new longest fork. If a block is accepted without error, it will be relayed to all connected peers. This function should only be called for new blocks.

func (*ConsensusSet) BlockAtHeight

func (cs *ConsensusSet) BlockAtHeight(height types.BlockHeight) (block types.Block, exists bool)

BlockAtHeight returns the block at a given height.

func (*ConsensusSet) BlockHeightOfBlock added in v0.1.0

func (cs *ConsensusSet) BlockHeightOfBlock(block types.Block) (height types.BlockHeight, exists bool)

BlockHeightOfBlock returns the blockheight given a block.

func (*ConsensusSet) CalculateStakeModifier added in v0.1.0

func (cs *ConsensusSet) CalculateStakeModifier(height types.BlockHeight, block types.Block, delay types.BlockHeight) *big.Int

CalculateStakeModifier calculates the stakemodifier from the blockchain. Height is the height for which to calculate the stakemodifier. This is needed in case height - StakeModifierDelay goes

sub-genesis

Block is a block on the correct fork, so we can roll back from it. Delay is the amount of blocks we roll back from `block`. Block and delay must be chosen so that rolling back `delay` blocks from `block` reaches first block with which to calculate the stakemodifier.

func (*ConsensusSet) ChildTarget

func (cs *ConsensusSet) ChildTarget(id types.BlockID) (target types.Target, exists bool)

ChildTarget returns the target for the child of a block.

func (*ConsensusSet) Close

func (cs *ConsensusSet) Close() error

Close closes the registered plugins and safely closes the database.

func (*ConsensusSet) ConsensusSetSubscribe

func (cs *ConsensusSet) ConsensusSetSubscribe(subscriber modules.ConsensusSetSubscriber, start modules.ConsensusChangeID, cancel <-chan struct{}) error

ConsensusSetSubscribe adds a subscriber to the list of subscribers, and gives them every consensus change that has occurred since the change with the provided id.

As a special case, using an empty id as the start will have all the changes sent to the modules starting with the genesis block.

func (*ConsensusSet) CurrentBlock

func (cs *ConsensusSet) CurrentBlock() (block types.Block)

CurrentBlock returns the latest block in the heaviest known blockchain.

func (*ConsensusSet) FindParentBlock added in v1.0.3

func (cs *ConsensusSet) FindParentBlock(b types.Block, depth types.BlockHeight) (block types.Block, exists bool)

FindParentBlock finds the parent of a block at the given depth. While this function is expensive, it guarantees that the correct parent block is found, even if the block is not on the longest fork. If it is known up front that a lookup is done within the current fork, "BlockAtHeight" should be used.

func (*ConsensusSet) FindParentHash added in v1.2.0

func (cs *ConsensusSet) FindParentHash(h types.BlockID, depth types.BlockHeight) (id types.BlockID, exists bool)

FindParentHash starts at a given hash h, and traverse the chain for the given depth to acquire the hash (block ID) of a block. The caller must ensure that the block with ID `h` is already present in the consensus DB, else this function will fail. Specifically, when this function is used for validation, the parent ID of the block being validated should be used, and depth adjusted accordingly

func (*ConsensusSet) Flush

func (cs *ConsensusSet) Flush() error

Flush will block until the consensus set has finished all in-progress routines.

func (*ConsensusSet) GetBlockStakeOutput added in v1.0.6

func (cs *ConsensusSet) GetBlockStakeOutput(id types.BlockStakeOutputID) (bso types.BlockStakeOutput, err error)

GetBlockStakeOutput returns the unspent blockstake output for the given ID

func (*ConsensusSet) GetCoinOutput added in v1.0.6

func (cs *ConsensusSet) GetCoinOutput(id types.CoinOutputID) (co types.CoinOutput, err error)

GetCoinOutput returns the unspent coin output for the given ID

func (*ConsensusSet) Height

func (cs *ConsensusSet) Height() (height types.BlockHeight)

Height returns the height of the consensus set.

func (*ConsensusSet) InCurrentPath

func (cs *ConsensusSet) InCurrentPath(id types.BlockID) (inPath bool)

InCurrentPath returns true if the block presented is in the current path, false otherwise.

func (*ConsensusSet) LoadedPlugins added in v1.3.1

func (cs *ConsensusSet) LoadedPlugins() []string

LoadedPlugins returns a list of all loaded plugins, by nane.

func (*ConsensusSet) MinimumValidChildTimestamp

func (cs *ConsensusSet) MinimumValidChildTimestamp(id types.BlockID) (timestamp types.Timestamp, exists bool)

MinimumValidChildTimestamp returns the earliest timestamp that the next block can have in order for it to be considered valid.

func (*ConsensusSet) RegisterPlugin added in v1.2.0

func (cs *ConsensusSet) RegisterPlugin(ctx context.Context, name string, plugin modules.ConsensusSetPlugin) error

RegisterPlugin registers a plugin to the map of plugins, initializes its bucket using the plugin and ensures it receives all consensus updates it is missing (as a special case this means anything). This initial sync is cancelled if tyhe passed context is cancelled.

func (*ConsensusSet) SetTransactionValidators added in v1.2.0

func (cs *ConsensusSet) SetTransactionValidators(validators ...modules.TransactionValidationFunction)

SetTransactionValidators sets the transaction validators used by the ConsensusSet as rules for all transactions, regardless of the version. Use SetTransactionVersionMappedValidators in case you want rules that only apply to a specific tx version. If no validators are passed, the validators returned by the `consensus.StandardTransactionValidators` function are used.

func (*ConsensusSet) SetTransactionVersionMappedValidators added in v1.2.0

func (cs *ConsensusSet) SetTransactionVersionMappedValidators(version types.TransactionVersion, validators ...modules.TransactionValidationFunction)

SetTransactionVersionMappedValidators sets the transaction validators used by the ConsensusSet as rules for the transactions of the defined version. If no validators are passed, the validators for the given transaction version, as returned by the `consensus.StandardTransactionVersionMappedValidators` function, are used.

func (*ConsensusSet) Start added in v1.2.0

func (cs *ConsensusSet) Start()

Start the consensusset

func (*ConsensusSet) Synced

func (cs *ConsensusSet) Synced() bool

Synced returns true if the consensus set is synced with the network.

func (*ConsensusSet) TransactionAtID added in v0.6.0

TransactionAtID allows you to fetch a transaction from a block within the blockchain, using a given transaction ID. If that transaction does not exist, false is returned

func (*ConsensusSet) TransactionAtShortID added in v0.6.0

func (cs *ConsensusSet) TransactionAtShortID(shortID types.TransactionShortID) (types.Transaction, bool)

TransactionAtShortID allows you fetch a transaction from a block within the blockchain, using a given shortID. If that transaction does not exist, false is returned.

func (*ConsensusSet) TryTransactionSet

func (cs *ConsensusSet) TryTransactionSet(txns []types.Transaction) (modules.ConsensusChange, error)

TryTransactionSet applies the input transactions to the consensus set to determine if they are valid. An error is returned IFF they are not a valid set in the current consensus set. The size of the transactions and the set is not checked. After the transactions have been validated, a consensus change is returned detailing the diffs that the transaction set would have.

func (*ConsensusSet) UnregisterPlugin added in v1.2.0

func (cs *ConsensusSet) UnregisterPlugin(name string, plugin modules.ConsensusSetPlugin)

UnregisterPlugin removes a plugin from the map of plugins

func (*ConsensusSet) Unsubscribe

func (cs *ConsensusSet) Unsubscribe(subscriber modules.ConsensusSetSubscriber)

Unsubscribe removes a subscriber from the list of subscribers, allowing for garbage collection and rescanning. If the subscriber is not found in the subscriber database, no action is taken.

type PluginViewStorage added in v1.2.0

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

A PluginViewStorage struct is a definition for the storage tool for a plugin bucket

func NewPluginStorage added in v1.2.0

func NewPluginStorage(db *persist.BoltDatabase, name string, wg *sync.WaitGroup) *PluginViewStorage

NewPluginStorage creates a new plugin storage for a given plugin bucket. PluginViewStorage abstracts the way the plugin bucket manages its data.

func (*PluginViewStorage) Close added in v1.2.0

func (ps *PluginViewStorage) Close() error

Close closes pluginViewStorage

func (*PluginViewStorage) View added in v1.2.0

func (ps *PluginViewStorage) View(callback func(bucket *bolt.Bucket) error) error

View takes in a callback to a bucket and takes care of managing the database knowledge

Jump to

Keyboard shortcuts

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