consensus

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2025 License: MIT Imports: 13 Imported by: 53

Documentation

Overview

Package consensus implements the Sia consensus algorithms.

Index

Constants

This section is empty.

Variables

This section is empty.

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

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 ValidateOrphan added in v0.1.8

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

ValidateOrphan validates b in the context of s.

func ValidateTransaction added in v0.1.11

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

ValidateTransaction validates txn within the context of ms and store.

func ValidateV2Transaction added in v0.1.12

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

ValidateV2Transaction validates txn within the context of ms.

Types

type ApplyUpdate added in v0.1.12

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

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

func (ApplyUpdate) ChainIndexElement added in v0.1.12

func (au ApplyUpdate) ChainIndexElement() types.ChainIndexElement

ChainIndexElement returns the chain index element for the applied block.

func (ApplyUpdate) FileContractElementDiffs added in v0.10.0

func (au ApplyUpdate) FileContractElementDiffs() []FileContractElementDiff

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

func (ApplyUpdate) ForEachTreeNode added in v0.1.12

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

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

MarshalJSON implements json.Marshaler.

func (ApplyUpdate) SiacoinElementDiffs added in v0.10.0

func (au ApplyUpdate) SiacoinElementDiffs() []SiacoinElementDiff

SiacoinElementDiffs returns the siacoin element diffs related to the applied block.

func (ApplyUpdate) SiafundElementDiffs added in v0.10.0

func (au ApplyUpdate) SiafundElementDiffs() []SiafundElementDiff

SiafundElementDiffs returns the siafund element diffs related to the applied block.

func (*ApplyUpdate) UnmarshalJSON added in v0.4.0

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

UnmarshalJSON implements json.Unmarshaler.

func (ApplyUpdate) UpdateElementProof added in v0.1.12

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.10.0

func (au ApplyUpdate) V2FileContractElementDiffs() []V2FileContractElementDiff

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

type ElementAccumulator added in v0.1.12

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

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

DecodeFrom implements types.DecoderFrom.

func (ElementAccumulator) EncodeTo added in v0.1.12

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

EncodeTo implements types.EncoderTo.

func (ElementAccumulator) MarshalJSON added in v0.1.12

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

MarshalJSON implements json.Marshaler.

func (*ElementAccumulator) UnmarshalJSON added in v0.1.12

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

UnmarshalJSON implements json.Unmarshaler.

type FileContractElementDiff added in v0.10.0

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.

type MidState added in v0.1.11

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

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

func NewMidState added in v0.1.11

func NewMidState(s State) *MidState

NewMidState constructs a MidState initialized to the provided base state.

func (*MidState) ApplyBlock added in v0.1.12

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

ApplyBlock applies a block to the MidState.

func (*MidState) ApplyTransaction added in v0.1.11

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

ApplyTransaction applies a transaction to the MidState.

func (*MidState) ApplyV2Transaction added in v0.1.12

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

ApplyV2Transaction applies a v2 transaction to the MidState.

type Network added in v0.1.11

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 Sia blockchain.

func (*Network) GenesisState added in v0.1.11

func (n *Network) GenesisState() State

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

type RevertUpdate added in v0.1.12

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 SiacoinElementDiffs 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 siacoin element, then later spent it, SiacoinElementDiffs will show the element being spent, then later created. This simplifies diff processing.

func RevertBlock added in v0.1.12

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

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

func (RevertUpdate) FileContractElementDiffs added in v0.10.0

func (ru RevertUpdate) FileContractElementDiffs() []FileContractElementDiff

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

func (RevertUpdate) ForEachTreeNode added in v0.1.12

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

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

MarshalJSON implements json.Marshaler.

func (RevertUpdate) SiacoinElementDiffs added in v0.10.0

func (ru RevertUpdate) SiacoinElementDiffs() []SiacoinElementDiff

SiacoinElementDiffs returns the siacoin element diffs related to the applied block.

func (RevertUpdate) SiafundElementDiffs added in v0.10.0

func (ru RevertUpdate) SiafundElementDiffs() []SiafundElementDiff

SiafundElementDiffs returns the siafund element diffs related to the applied block.

func (*RevertUpdate) UnmarshalJSON added in v0.4.0

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

UnmarshalJSON implments json.Unmarshaler.

func (RevertUpdate) UpdateElementProof added in v0.1.12

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.10.0

func (ru RevertUpdate) V2FileContractElementDiffs() []V2FileContractElementDiff

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

type SiacoinElementDiff added in v0.10.0

type SiacoinElementDiff struct {
	SiacoinElement types.SiacoinElement `json:"siacoinElement"`
	Created        bool                 `json:"created"`
	Spent          bool                 `json:"spent"`
}

A SiacoinElementDiff is a SiacoinElement 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 SiafundElementDiff added in v0.10.0

type SiafundElementDiff struct {
	SiafundElement types.SiafundElement `json:"siafundElement"`
	Created        bool                 `json:"created"`
	Spent          bool                 `json:"spent"`
}

A SiafundElementDiff is a SiafundElement 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 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"`
	SiafundTaxRevenue types.Currency   `json:"siafundTaxRevenue"`

	// 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 ApplyOrphan added in v0.1.12

func ApplyOrphan(s State, b types.Block, targetTimestamp time.Time) State

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

func (State) AncestorDepth added in v0.1.12

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

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

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

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

func (s State) Commitment(txnsHash types.Hash256, minerAddr types.Address) types.Hash256

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

func (State) ContractSigHash added in v0.1.12

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() (sco types.SiacoinOutput, exists bool)

FoundationSubsidy returns the Foundation subsidy output for the child block.

func (State) InputSigHash added in v0.1.12

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

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) 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 added in v0.1.12

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

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

func (State) SiafundCount

func (s State) SiafundCount() uint64

SiafundCount is the number of siafunds in existence.

func (State) StorageProofLeafHash added in v0.1.12

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

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) TransactionsCommitment added in v0.1.12

func (s State) TransactionsCommitment(txns []types.Transaction, v2txns []types.V2Transaction) types.Hash256

TransactionsCommitment returns the commitment hash covering the transactions that comprise a child block.

func (State) V2FileContractTax added in v0.1.12

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

V2FileContractTax computes the tax levied on a given v2 contract.

func (State) V2TransactionWeight added in v0.1.12

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

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

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

DecodeFrom implements types.DecoderFrom.

func (V1BlockSupplement) EncodeTo added in v0.1.12

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

EncodeTo implements types.EncoderTo.

type V1StorageProofSupplement added in v0.4.7

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

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

DecodeFrom implements types.DecoderFrom.

func (V1StorageProofSupplement) EncodeTo added in v0.4.7

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

EncodeTo implements types.EncoderTo.

type V1TransactionSupplement added in v0.1.12

type V1TransactionSupplement struct {
	SiacoinInputs        []types.SiacoinElement
	SiafundInputs        []types.SiafundElement
	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 SiacoinOutput 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 added in v0.1.12

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

DecodeFrom implements types.DecoderFrom.

func (V1TransactionSupplement) EncodeTo added in v0.1.12

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

EncodeTo implements types.EncoderTo.

type V2FileContractElementDiff added in v0.10.0

type V2FileContractElementDiff struct {
	V2FileContractElement types.V2FileContractElement `json:"v2FileContractElement"`
	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.V2FileContract `json:"revision"`
	// Non-nil if the contract was resolved.
	Resolution types.V2FileContractResolutionType `json:"resolution"`
}

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.

type Work added in v0.1.12

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

Work represents a quantity of work.

func (Work) Cmp added in v0.1.12

func (w Work) Cmp(v Work) int

Cmp compares two work values.

func (*Work) DecodeFrom added in v0.1.12

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

DecodeFrom implements types.DecoderFrom.

func (Work) EncodeTo added in v0.1.12

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

EncodeTo implements types.EncoderTo.

func (Work) MarshalJSON added in v0.1.12

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

MarshalJSON implements json.Marshaler.

func (Work) MarshalText added in v0.1.12

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

MarshalText implements encoding.TextMarshaler.

func (Work) String added in v0.1.12

func (w Work) String() string

String implements fmt.Stringer.

func (*Work) UnmarshalJSON added in v0.1.12

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

UnmarshalJSON implements json.Unmarshaler.

func (*Work) UnmarshalText added in v0.1.12

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