consensus

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2025 License: MIT Imports: 13 Imported by: 12

Documentation

Overview

Package consensus implements the Bigfile consensus algorithms.

Index

Constants

This section is empty.

Variables

View Source
var ErrCommitmentMismatch = errors.New("commitment hash mismatch")

ErrCommitmentMismatch is returned when a block's commitment hash does not match the current state's commitment hash.

Functions

func ApplyBlock

func ApplyBlock(s State, b types.Block, bs V1BlockSupplement, targetTimestamp time.Time) (State, ApplyUpdate)

ApplyBlock applies b to s, producing a new state and a set of effects.

func ValidateBlock

func ValidateBlock(s State, b types.Block, bs V1BlockSupplement) error

ValidateBlock validates b in the context of s.

This function does not check whether the header's timestamp is too far in the future. That check should be performed at the time the block is received, e.g. in p2p networking code; see MaxFutureTimestamp.

func ValidateHeader added in v1.0.8

func ValidateHeader(s State, bh types.BlockHeader) error

ValidateHeader validates bh in the context of s.

func ValidateOrphan

func ValidateOrphan(s State, b types.Block) error

ValidateOrphan validates b in the context of s.

func ValidateTransaction

func ValidateTransaction(ms *MidState, txn types.Transaction, ts V1TransactionSupplement) error

ValidateTransaction validates txn within the context of ms and store.

func ValidateV2Transaction

func ValidateV2Transaction(ms *MidState, txn types.V2Transaction) error

ValidateV2Transaction validates txn within the context of ms.

Types

type ApplyUpdate

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

An ApplyUpdate represents the effects of applying a block to a state.

func (ApplyUpdate) BigfileElementDiffs added in v1.0.9

func (au ApplyUpdate) BigfileElementDiffs() []BigfileElementDiff

BigfileElementDiffs returns the bigfile element diffs related to the applied block.

func (ApplyUpdate) BigfundElementDiffs added in v1.0.4

func (au ApplyUpdate) BigfundElementDiffs() []BigfundElementDiff

BigfundElementDiffs returns the bigfund element diffs related to the applied block.

func (ApplyUpdate) ChainIndexElement

func (au ApplyUpdate) ChainIndexElement() types.ChainIndexElement

ChainIndexElement returns the chain index element for the applied block.

func (ApplyUpdate) FileContractElementDiffs added in v0.0.2

func (au ApplyUpdate) FileContractElementDiffs() []FileContractElementDiff

FileContractElementDiffs returns the file contract element diffs related to the applied block.

func (ApplyUpdate) ForEachTreeNode

func (au ApplyUpdate) ForEachTreeNode(fn func(row, col uint64, h types.Hash256))

ForEachTreeNode calls fn on each node in the accumulator affected by au.

func (ApplyUpdate) MarshalJSON

func (au ApplyUpdate) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*ApplyUpdate) UnmarshalJSON

func (au *ApplyUpdate) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (ApplyUpdate) UpdateElementProof

func (au ApplyUpdate) UpdateElementProof(e *types.StateElement)

UpdateElementProof updates the Merkle proof of the supplied element to incorporate the changes made to the accumulator. The element's proof must be up-to-date; if it is not, UpdateElementProof may panic.

func (ApplyUpdate) V2FileContractElementDiffs added in v0.0.2

func (au ApplyUpdate) V2FileContractElementDiffs() []V2FileContractElementDiff

V2FileContractElementDiffs returns the v2 file contract element diffs related to the applied block.

type BigfileElementDiff added in v1.0.9

type BigfileElementDiff struct {
	BigfileElement types.BigfileElement `json:"bigfileElement"`
	Created        bool                 `json:"created"`
	Spent          bool                 `json:"spent"`
}

A BigfileElementDiff is a BigfileElement that was created and/or spent within a block. Note that an element may be both created and spent in the the same block.

type BigfundElementDiff added in v1.0.4

type BigfundElementDiff struct {
	BigfundElement types.BigfundElement `json:"bigfundElement"`
	Created        bool                 `json:"created"`
	Spent          bool                 `json:"spent"`
}

A BigfundElementDiff is a BigfundElement that was created and/or spent within a block. Note that an element may be both created and spent in the the same block.

type ElementAccumulator

type ElementAccumulator struct {
	Trees     [64]types.Hash256
	NumLeaves uint64
}

An ElementAccumulator tracks the state of an unbounded number of elements without storing the elements themselves.

func (*ElementAccumulator) DecodeFrom

func (acc *ElementAccumulator) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (ElementAccumulator) EncodeTo

func (acc ElementAccumulator) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

func (ElementAccumulator) MarshalJSON

func (acc ElementAccumulator) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*ElementAccumulator) UnmarshalJSON

func (acc *ElementAccumulator) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*ElementAccumulator) ValidateTransactionElements added in v1.0.8

func (acc *ElementAccumulator) ValidateTransactionElements(txn types.V2Transaction) (err error)

ValidateTransactionElements validates the Merkle proofs of all elements in the supplied transaction.

type FileContractElementDiff added in v0.0.2

type FileContractElementDiff struct {
	FileContractElement types.FileContractElement `json:"fileContractElement"`
	Created             bool                      `json:"created"`
	// Non-nil if the contract was revised. If the contract was revised multiple
	// times, this is the revision with the highest revision number.
	Revision *types.FileContract `json:"revision"`
	Resolved bool                `json:"resolved"`
	Valid    bool                `json:"valid"`
}

A FileContractElementDiff is a FileContractElement that was created, revised, and/or resolved within a block. Note that a contract may be created, revised, and resolved all within the same block.

func (FileContractElementDiff) RevisionElement added in v0.0.2

func (diff FileContractElementDiff) RevisionElement() (types.FileContractElement, bool)

RevisionElement returns the revision, if present, as a FileContractElement. It returns a boolean indicating whether the revision exists or not. The element's memory is shared.

type MidState

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

A MidState represents the state of the chain within a block.

func NewMidState

func NewMidState(s State) *MidState

NewMidState constructs a MidState initialized to the provided base state.

func (*MidState) ApplyBlock

func (ms *MidState) ApplyBlock(b types.Block, bs V1BlockSupplement)

ApplyBlock applies a block to the MidState.

func (*MidState) ApplyTransaction

func (ms *MidState) ApplyTransaction(txn types.Transaction, ts V1TransactionSupplement)

ApplyTransaction applies a transaction to the MidState.

func (*MidState) ApplyV2Transaction

func (ms *MidState) ApplyV2Transaction(txn types.V2Transaction)

ApplyV2Transaction applies a v2 transaction to the MidState.

type Network

type Network struct {
	Name string `json:"name"`

	InitialCoinbase types.Currency `json:"initialCoinbase"`
	MinimumCoinbase types.Currency `json:"minimumCoinbase"`
	InitialTarget   types.BlockID  `json:"initialTarget"`
	BlockInterval   time.Duration  `json:"blockInterval"`
	MaturityDelay   uint64         `json:"maturityDelay"`

	HardforkDevAddr struct {
		Height     uint64        `json:"height"`
		OldAddress types.Address `json:"oldAddress"`
		NewAddress types.Address `json:"newAddress"`
	} `json:"hardforkDevAddr"`
	HardforkTax struct {
		Height uint64 `json:"height"`
	} `json:"hardforkTax"`
	HardforkStorageProof struct {
		Height uint64 `json:"height"`
	} `json:"hardforkStorageProof"`
	HardforkOak struct {
		Height           uint64    `json:"height"`
		FixHeight        uint64    `json:"fixHeight"`
		GenesisTimestamp time.Time `json:"genesisTimestamp"`
	} `json:"hardforkOak"`
	//nolint:tagliatelle
	HardforkASIC struct {
		Height    uint64        `json:"height"`
		OakTime   time.Duration `json:"oakTime"`
		OakTarget types.BlockID `json:"oakTarget"`
	} `json:"hardforkASIC"`
	HardforkFoundation struct {
		Height          uint64        `json:"height"`
		PrimaryAddress  types.Address `json:"primaryAddress"`
		FailsafeAddress types.Address `json:"failsafeAddress"`
	} `json:"hardforkFoundation"`
	HardforkV2 struct {
		AllowHeight   uint64 `json:"allowHeight"`
		RequireHeight uint64 `json:"requireHeight"`
	} `json:"hardforkV2"`
}

A Network specifies the fixed parameters of a Bigfile blockchain.

func (*Network) GenesisState

func (n *Network) GenesisState() State

GenesisState returns the state to which the genesis block should be applied.

type RevertUpdate

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

A RevertUpdate represents the effects of reverting to a prior state. These are the same effects seen as when applying the block, but should be processed inversely. For example, if BigfileElementDiffs reports an element with the Created flag set, it means the block created that element when it was applied; thus, when the block is reverted, the element no longer exists.

Furthermore, the order of all diffs is reversed: if the block first created a bigfile element, then later spent it, BigfileElementDiffs will show the element being spent, then later created. This simplifies diff processing.

func RevertBlock

func RevertBlock(s State, b types.Block, bs V1BlockSupplement) RevertUpdate

RevertBlock reverts b, producing the effects undone by the block.

func (RevertUpdate) BigfileElementDiffs added in v1.0.9

func (ru RevertUpdate) BigfileElementDiffs() []BigfileElementDiff

BigfileElementDiffs returns the bigfile element diffs related to the applied block.

func (RevertUpdate) BigfundElementDiffs added in v1.0.4

func (ru RevertUpdate) BigfundElementDiffs() []BigfundElementDiff

BigfundElementDiffs returns the bigfund element diffs related to the applied block.

func (RevertUpdate) ChainIndexElement added in v1.0.8

func (ru RevertUpdate) ChainIndexElement() types.ChainIndexElement

ChainIndexElement returns the chain index element related to the applied block.

func (RevertUpdate) FileContractElementDiffs added in v0.0.2

func (ru RevertUpdate) FileContractElementDiffs() []FileContractElementDiff

FileContractElementDiffs returns the file contract element diffs related to the applied block.

func (RevertUpdate) ForEachTreeNode

func (ru RevertUpdate) ForEachTreeNode(fn func(row, col uint64, h types.Hash256))

ForEachTreeNode calls fn on each node in the accumulator affected by ru.

func (RevertUpdate) MarshalJSON

func (ru RevertUpdate) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*RevertUpdate) UnmarshalJSON

func (ru *RevertUpdate) UnmarshalJSON(b []byte) error

UnmarshalJSON implments json.Unmarshaler.

func (RevertUpdate) UpdateElementProof

func (ru RevertUpdate) UpdateElementProof(e *types.StateElement)

UpdateElementProof updates the Merkle proof of the supplied element to incorporate the changes made to the accumulator. The element's proof must be up-to-date; if it is not, UpdateElementProof may panic.

func (RevertUpdate) V2FileContractElementDiffs added in v0.0.2

func (ru RevertUpdate) V2FileContractElementDiffs() []V2FileContractElementDiff

V2FileContractElementDiffs returns the v2 file contract element diffs related to the applied block.

type State

type State struct {
	Network *Network `json:"-"` // network parameters are not encoded

	Index             types.ChainIndex `json:"index"`
	PrevTimestamps    [11]time.Time    `json:"prevTimestamps"` // newest -> oldest
	Depth             types.BlockID    `json:"depth"`
	ChildTarget       types.BlockID    `json:"childTarget"`
	BigfundTaxRevenue types.Currency   `json:"bigfundTaxRevenue"`

	// Oak hardfork state
	OakTime   time.Duration `json:"oakTime"`
	OakTarget types.BlockID `json:"oakTarget"`
	// Foundation hardfork state
	FoundationSubsidyAddress    types.Address `json:"foundationSubsidyAddress"`
	FoundationManagementAddress types.Address `json:"foundationManagementAddress"`
	// v2 hardfork state
	TotalWork    Work               `json:"totalWork"`
	Difficulty   Work               `json:"difficulty"`
	OakWork      Work               `json:"oakWork"`
	Elements     ElementAccumulator `json:"elements"`
	Attestations uint64             `json:"attestations"`
}

State represents the state of the chain as of a particular block.

func ApplyHeader added in v1.0.8

func ApplyHeader(s State, bh types.BlockHeader, targetTimestamp time.Time) State

ApplyHeader applies the work of bh to s, returning the resulting state. Only the PoW-related fields are updated.

func (State) AncestorDepth

func (s State) AncestorDepth() uint64

AncestorDepth is the depth used to determine the target timestamp in the pre-Oak difficulty adjustment algorithm.

func (State) AttestationSigHash

func (s State) AttestationSigHash(a types.Attestation) types.Hash256

AttestationSigHash returns the hash that must be signed for an attestation.

func (State) BigfundCount added in v1.0.4

func (s State) BigfundCount() uint64

BigfundCount is the number of bigfunds in existence.

func (State) BlockInterval

func (s State) BlockInterval() time.Duration

BlockInterval is the expected wall clock time between consecutive blocks.

func (State) BlockReward

func (s State) BlockReward() types.Currency

BlockReward returns the reward for mining a child block.

func (State) Commitment

func (s State) Commitment(minerAddr types.Address, txns []types.Transaction, v2txns []types.V2Transaction) types.Hash256

Commitment computes the commitment hash for a child block with the given transactions and miner address.

func (State) ContractSigHash

func (s State) ContractSigHash(fc types.V2FileContract) types.Hash256

ContractSigHash returns the hash that must be signed for a v2 contract revision.

func (*State) DecodeFrom

func (s *State) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (State) EncodeTo

func (s State) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

func (State) FileContractTax

func (s State) FileContractTax(fc types.FileContract) types.Currency

FileContractTax computes the tax levied on a given contract.

func (State) FoundationSubsidy

func (s State) FoundationSubsidy() (bigo types.BigfileOutput, exists bool)

FoundationSubsidy returns the Foundation subsidy output for the child block.

func (State) InputSigHash

func (s State) InputSigHash(txn types.V2Transaction) types.Hash256

InputSigHash returns the hash that must be signed for each v2 transaction input.

func (State) MaturityHeight

func (s State) MaturityHeight() uint64

MaturityHeight is the height at which various outputs created in the child block will "mature" (become spendable).

func (State) MaxBlockWeight

func (s State) MaxBlockWeight() uint64

MaxBlockWeight is the maximum "weight" of a valid child block.

func (State) MaxFutureTimestamp

func (s State) MaxFutureTimestamp(currentTime time.Time) time.Time

MaxFutureTimestamp returns a reasonable maximum value for a child block's timestamp. Note that this is not a consensus rule.

func (State) MerkleLeafHash added in v1.0.8

func (s State) MerkleLeafHash(minerAddr types.Address) types.Hash256

MerkleLeafHash computes the hash of the state to be used as the first leaf in the Commitment Merkle tree.

func (State) NonceFactor

func (s State) NonceFactor() uint64

NonceFactor is the factor by which all block nonces must be divisible.

func (State) PartialSigHash

func (s State) PartialSigHash(txn types.Transaction, cf types.CoveredFields) types.Hash256

PartialSigHash computes the hash of the transaction data specified by cf. It panics if cf references fields not present in txn.

func (State) RenewalSigHash

func (s State) RenewalSigHash(fcr types.V2FileContractRenewal) types.Hash256

RenewalSigHash returns the hash that must be signed for a file contract renewal.

func (State) StorageProofLeafHash

func (s State) StorageProofLeafHash(leaf []byte) types.Hash256

StorageProofLeafHash computes the leaf hash of file contract data. If len(leaf) < 64, it will be extended with zeros.

func (State) StorageProofLeafIndex

func (s State) StorageProofLeafIndex(filesize uint64, windowID types.BlockID, fcid types.FileContractID) uint64

StorageProofLeafIndex returns the leaf index used when computing or validating a storage proof.

func (State) SufficientlyHeavierThan

func (s State) SufficientlyHeavierThan(t State) bool

SufficientlyHeavierThan returns whether s is sufficiently heavier than t. Nodes should use this method rather than directly comparing the Depth or TotalWork fields. Note that this is not a consensus rule.

func (State) TransactionWeight

func (s State) TransactionWeight(txn types.Transaction) uint64

TransactionWeight computes the weight of a txn.

func (State) V2FileContractTax

func (s State) V2FileContractTax(fc types.V2FileContract) types.Currency

V2FileContractTax computes the tax levied on a given v2 contract.

func (State) V2TransactionWeight

func (s State) V2TransactionWeight(txn types.V2Transaction) uint64

V2TransactionWeight computes the weight of a txn.

func (State) WholeSigHash

func (s State) WholeSigHash(txn types.Transaction, parentID types.Hash256, pubkeyIndex uint64, timelock uint64, coveredSigs []uint64) types.Hash256

WholeSigHash computes the hash of transaction data covered by the WholeTransaction flag.

type V1BlockSupplement

type V1BlockSupplement struct {
	Transactions          []V1TransactionSupplement
	ExpiringFileContracts []types.FileContractElement
}

A V1BlockSupplement contains elements that are associated with a v1 block, but not included in the block. This includes supplements for each v1 transaction, as well as any file contracts that expired at the block's height.

func (*V1BlockSupplement) DecodeFrom

func (bs *V1BlockSupplement) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (V1BlockSupplement) EncodeTo

func (bs V1BlockSupplement) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type V1StorageProofSupplement

type V1StorageProofSupplement struct {
	FileContract types.FileContractElement
	WindowID     types.BlockID
}

A V1StorageProofSupplement pairs a file contract with the block ID used to derive its storage proof leaf index.

func (*V1StorageProofSupplement) DecodeFrom

func (sps *V1StorageProofSupplement) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (V1StorageProofSupplement) EncodeTo

func (sps V1StorageProofSupplement) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type V1TransactionSupplement

type V1TransactionSupplement struct {
	BigfileInputs        []types.BigfileElement
	BigfundInputs        []types.BigfundElement
	RevisedFileContracts []types.FileContractElement
	StorageProofs        []V1StorageProofSupplement
}

A V1TransactionSupplement contains elements that are associated with a v1 transaction, but not included in the transaction. For example, v1 transactions reference the ID of each BigfileOutput they spend, but do not contain the output itself. Consequently, in order to validate the transaction, those outputs must be loaded from a Store. Collecting these elements into an explicit struct allows us to preserve them even after the Store has been mutated.

func (*V1TransactionSupplement) DecodeFrom

func (ts *V1TransactionSupplement) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (V1TransactionSupplement) EncodeTo

func (ts V1TransactionSupplement) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type V2FileContractElementDiff added in v0.0.2

type V2FileContractElementDiff struct {
	V2FileContractElement types.V2FileContractElement
	Created               bool
	// Non-nil if the contract was revised. If the contract was revised multiple
	// times, this is the revision with the highest revision number.
	Revision *types.V2FileContract
	// Non-nil if the contract was resolved.
	Resolution types.V2FileContractResolutionType
}

A V2FileContractElementDiff is a V2FileContractElement that was created, revised, and/or resolved within a block. Note that, within a block, a v2 contract may be both created and revised, or revised and resolved, but not created and resolved.

func (V2FileContractElementDiff) MarshalJSON added in v1.0.8

func (diff V2FileContractElementDiff) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*V2FileContractElementDiff) UnmarshalJSON added in v1.0.8

func (diff *V2FileContractElementDiff) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (V2FileContractElementDiff) V2RevisionElement added in v0.0.2

func (diff V2FileContractElementDiff) V2RevisionElement() (types.V2FileContractElement, bool)

V2RevisionElement returns the revision, if present, as a V2FileContractElement. It returns a boolean indicating whether the revision exists or not. The element's memory is shared.

type Work

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

Work represents a quantity of work.

func (Work) Cmp

func (w Work) Cmp(v Work) int

Cmp compares two work values.

func (*Work) DecodeFrom

func (w *Work) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (Work) EncodeTo

func (w Work) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

func (Work) MarshalJSON

func (w Work) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Work) MarshalText

func (w Work) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Work) String

func (w Work) String() string

String implements fmt.Stringer.

func (*Work) UnmarshalJSON

func (w *Work) UnmarshalJSON(b []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*Work) UnmarshalText

func (w *Work) UnmarshalText(b []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

Jump to

Keyboard shortcuts

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