bor

package
v0.0.21 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2022 License: GPL-3.0 Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxTotalVotingPower      = int64(math.MaxInt64) / 8
	PriorityWindowSizeFactor = 2
)

Variables

View Source
var (

	// ErrInvalidTimestamp is returned if the timestamp of a block is lower than
	// the previous block's timestamp + the minimum block period.
	ErrInvalidTimestamp = errors.New("invalid timestamp")
)

Various error messages to mark blocks invalid. These should be private to prevent engine specific errors from being referenced in the remainder of the codebase, inherently breaking if the engine is swapped out. Please put common error types into the consensus package.

View Source
var (
	// MaxCheckpointLength is the maximum number of blocks that can be requested for constructing a checkpoint root hash
	MaxCheckpointLength = uint64(math.Pow(2, 15))
)

Functions

func BorRLP

func BorRLP(header *types.Header, c *params.BorConfig) []byte

BorRLP returns the rlp bytes which needs to be signed for the bor sealing. The RLP to sign consists of the entire header apart from the 65 byte signature contained at the end of the extra data.

Note, the method requires the extra data to be at least 65 bytes, otherwise it panics. This is done to avoid accidentally using both forms (signature present or not), which could be abused to produce different hashes for the same header.

func CalcProducerDelay

func CalcProducerDelay(number uint64, succession int, c *params.BorConfig) uint64

CalcProducerDelay is the block delay algorithm based on block time, period, producerDelay and turn-ness of a signer

func IsErrTooMuchChange

func IsErrTooMuchChange(err error) bool

func SealHash

func SealHash(header *types.Header, c *params.BorConfig) (hash common.Hash)

SealHash returns the hash of a block prior to it being sealed.

func ValidatorListString

func ValidatorListString(vals []*Validator) string

ValidatorListString returns a prettified validator list for logging purposes.

Types

type API

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

API is a user facing RPC API to allow controlling the signer and voting mechanisms of the proof-of-authority scheme.

func (*API) GetAuthor

func (api *API) GetAuthor(number *rpc.BlockNumber) (*common.Address, error)

GetAuthor retrieves the author a block.

func (*API) GetCurrentProposer

func (api *API) GetCurrentProposer() (common.Address, error)

GetCurrentProposer gets the current proposer

func (*API) GetCurrentValidators

func (api *API) GetCurrentValidators() ([]*Validator, error)

GetCurrentValidators gets the current validators

func (*API) GetRootHash

func (api *API) GetRootHash(start uint64, end uint64) (string, error)

GetRootHash returns the merkle root of the start to end block headers

func (*API) GetSigners

func (api *API) GetSigners(number *rpc.BlockNumber) ([]common.Address, error)

GetSigners retrieves the list of authorized signers at the specified block.

func (*API) GetSignersAtHash

func (api *API) GetSignersAtHash(hash common.Hash) ([]common.Address, error)

GetSignersAtHash retrieves the list of authorized signers at the specified block.

func (*API) GetSnapshot

func (api *API) GetSnapshot(number *rpc.BlockNumber) (*Snapshot, error)

GetSnapshot retrieves the state snapshot at a given block.

func (*API) GetSnapshotAtHash

func (api *API) GetSnapshotAtHash(hash common.Hash) (*Snapshot, error)

GetSnapshotAtHash retrieves the state snapshot at a given block.

type BlockTooSoonError

type BlockTooSoonError struct {
	Number     uint64
	Succession int
}

func (*BlockTooSoonError) Error

func (e *BlockTooSoonError) Error() string

type Bor

type Bor struct {
	GenesisContractsClient *GenesisContractsClient

	HeimdallClient  IHeimdallClient
	WithoutHeimdall bool
	// contains filtered or unexported fields
}

Bor is the matic-bor consensus engine

func New

func New(
	chainConfig *params.ChainConfig,
	db ethdb.Database,
	ethAPI *ethapi.PublicBlockChainAPI,
	heimdallURL string,
	withoutHeimdall bool,
) *Bor

New creates a Matic Bor consensus engine.

func (*Bor) APIs

func (c *Bor) APIs(chain consensus.ChainHeaderReader) []rpc.API

APIs implements consensus.Engine, returning the user facing RPC API to allow controlling the signer voting.

func (*Bor) Author

func (c *Bor) Author(header *types.Header) (common.Address, error)

Author implements consensus.Engine, returning the Ethereum address recovered from the signature in the header's extra-data section.

func (*Bor) Authorize

func (c *Bor) Authorize(signer common.Address, signFn SignerFn)

Authorize injects a private key into the consensus engine to mint new blocks with.

func (*Bor) CalcDifficulty

func (c *Bor) CalcDifficulty(chain consensus.ChainHeaderReader, time uint64, parent *types.Header) *big.Int

CalcDifficulty is the difficulty adjustment algorithm. It returns the difficulty that a new block should have based on the previous blocks in the chain and the current signer.

func (*Bor) Close

func (c *Bor) Close() error

Close implements consensus.Engine. It's a noop for bor as there are no background threads.

func (*Bor) CommitStates

func (c *Bor) CommitStates(
	state *state.StateDB,
	header *types.Header,
	chain chainContext,
) ([]*types.StateSyncData, error)

CommitStates commit states

func (*Bor) Finalize

func (c *Bor) Finalize(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header)

Finalize implements consensus.Engine, ensuring no uncles are set, nor block rewards given.

func (*Bor) FinalizeAndAssemble

func (c *Bor) FinalizeAndAssemble(chain consensus.ChainHeaderReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, uncles []*types.Header, receipts []*types.Receipt) (*types.Block, error)

FinalizeAndAssemble implements consensus.Engine, ensuring no uncles are set, nor block rewards given, and returns the final block.

func (*Bor) GetCurrentSpan

func (c *Bor) GetCurrentSpan(headerHash common.Hash) (*Span, error)

GetCurrentSpan get current span from contract

func (*Bor) GetCurrentValidators

func (c *Bor) GetCurrentValidators(headerHash common.Hash, blockNumber uint64) ([]*Validator, error)

GetCurrentValidators get current validators

func (*Bor) Prepare

func (c *Bor) Prepare(chain consensus.ChainHeaderReader, header *types.Header) error

Prepare implements consensus.Engine, preparing all the consensus fields of the header for running the transactions on top.

func (*Bor) Seal

func (c *Bor) Seal(chain consensus.ChainHeaderReader, block *types.Block, results chan<- *types.Block, stop <-chan struct{}) error

Seal implements consensus.Engine, attempting to create a sealed block using the local signing credentials.

func (*Bor) SealHash

func (c *Bor) SealHash(header *types.Header) common.Hash

SealHash returns the hash of a block prior to it being sealed.

func (*Bor) SetHeimdallClient

func (c *Bor) SetHeimdallClient(h IHeimdallClient)

func (*Bor) VerifyHeader

func (c *Bor) VerifyHeader(chain consensus.ChainHeaderReader, header *types.Header, seal bool) error

VerifyHeader checks whether a header conforms to the consensus rules.

func (*Bor) VerifyHeaders

func (c *Bor) VerifyHeaders(chain consensus.ChainHeaderReader, headers []*types.Header, seals []bool) (chan<- struct{}, <-chan error)

VerifyHeaders is similar to VerifyHeader, but verifies a batch of headers. The method returns a quit channel to abort the operations and a results channel to retrieve the async verifications (the order is that of the input slice).

func (*Bor) VerifySeal

func (c *Bor) VerifySeal(chain consensus.ChainHeaderReader, header *types.Header) error

VerifySeal implements consensus.Engine, checking whether the signature contained in the header satisfies the consensus protocol requirements.

func (*Bor) VerifyUncles

func (c *Bor) VerifyUncles(chain consensus.ChainReader, block *types.Block) error

VerifyUncles implements consensus.Engine, always returning an error for any uncles as this consensus mechanism doesn't permit uncles.

type EventRecord

type EventRecord struct {
	ID       uint64         `json:"id" yaml:"id"`
	Contract common.Address `json:"contract" yaml:"contract"`
	Data     hexutil.Bytes  `json:"data" yaml:"data"`
	TxHash   common.Hash    `json:"tx_hash" yaml:"tx_hash"`
	LogIndex uint64         `json:"log_index" yaml:"log_index"`
	ChainID  string         `json:"bor_chain_id" yaml:"bor_chain_id"`
}

EventRecord represents state record

type EventRecordWithTime

type EventRecordWithTime struct {
	EventRecord
	Time time.Time `json:"record_time" yaml:"record_time"`
}

func (*EventRecordWithTime) BuildEventRecord

func (e *EventRecordWithTime) BuildEventRecord() *EventRecord

func (*EventRecordWithTime) String

func (e *EventRecordWithTime) String(gasUsed uint64) string

String returns the string representation of EventRecord

type GenesisContractsClient

type GenesisContractsClient struct {
	ValidatorContract     string
	StateReceiverContract string
	// contains filtered or unexported fields
}

func NewGenesisContractsClient

func NewGenesisContractsClient(
	chainConfig *params.ChainConfig,
	validatorContract,
	stateReceiverContract string,
	ethAPI *ethapi.PublicBlockChainAPI,
) *GenesisContractsClient

func (*GenesisContractsClient) CommitState

func (gc *GenesisContractsClient) CommitState(
	event *EventRecordWithTime,
	state *state.StateDB,
	header *types.Header,
	chCtx chainContext,
) (uint64, error)

func (*GenesisContractsClient) LastStateId

func (gc *GenesisContractsClient) LastStateId(snapshotNumber uint64) (*big.Int, error)

type HeimdallClient

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

func NewHeimdallClient

func NewHeimdallClient(urlString string) (*HeimdallClient, error)

func (*HeimdallClient) Close

func (h *HeimdallClient) Close()

Close sends a signal to stop the running process

func (*HeimdallClient) Fetch

func (h *HeimdallClient) Fetch(rawPath string, rawQuery string) (*ResponseWithHeight, error)

Fetch fetches response from heimdall

func (*HeimdallClient) FetchStateSyncEvents

func (h *HeimdallClient) FetchStateSyncEvents(fromID uint64, to int64) ([]*EventRecordWithTime, error)

func (*HeimdallClient) FetchWithRetry

func (h *HeimdallClient) FetchWithRetry(rawPath string, rawQuery string) (*ResponseWithHeight, error)

FetchWithRetry returns data from heimdall with retry

type HeimdallSpan

type HeimdallSpan struct {
	Span
	ValidatorSet      ValidatorSet `json:"validator_set" yaml:"validator_set"`
	SelectedProducers []Validator  `json:"selected_producers" yaml:"selected_producers"`
	ChainID           string       `json:"bor_chain_id" yaml:"bor_chain_id"`
}

HeimdallSpan represents span from heimdall APIs

type IHeimdallClient

type IHeimdallClient interface {
	Fetch(path string, query string) (*ResponseWithHeight, error)
	FetchWithRetry(path string, query string) (*ResponseWithHeight, error)
	FetchStateSyncEvents(fromID uint64, to int64) ([]*EventRecordWithTime, error)
	Close()
}

type InvalidStartEndBlockError

type InvalidStartEndBlockError struct {
	Start         uint64
	End           uint64
	CurrentHeader uint64
}

func (*InvalidStartEndBlockError) Error

func (e *InvalidStartEndBlockError) Error() string

type InvalidStateReceivedError

type InvalidStateReceivedError struct {
	Number      uint64
	LastStateID uint64
	To          *time.Time
	Event       *EventRecordWithTime
}

func (*InvalidStateReceivedError) Error

func (e *InvalidStateReceivedError) Error() string

type MaxCheckpointLengthExceededError

type MaxCheckpointLengthExceededError struct {
	Start uint64
	End   uint64
}

func (*MaxCheckpointLengthExceededError) Error

type MinimalVal

type MinimalVal struct {
	ID          uint64         `json:"ID"`
	VotingPower uint64         `json:"power"` // TODO add 10^-18 here so that we dont overflow easily
	Signer      common.Address `json:"signer"`
}

MinimalVal is the minimal validator representation Used to send validator information to bor validator contract

func SortMinimalValByAddress

func SortMinimalValByAddress(a []MinimalVal) []MinimalVal

SortMinimalValByAddress sorts validators

func ValidatorsToMinimalValidators

func ValidatorsToMinimalValidators(vals []Validator) (minVals []MinimalVal)

ValidatorsToMinimalValidators converts array of validators to minimal validators

type MismatchingValidatorsError

type MismatchingValidatorsError struct {
	Number             uint64
	ValidatorSetSnap   []byte
	ValidatorSetHeader []byte
}

MismatchingValidatorsError is returned if a last block in sprint contains a list of validators different from the one that local node calculated

func (*MismatchingValidatorsError) Error

type ResponseWithHeight

type ResponseWithHeight struct {
	Height string          `json:"height"`
	Result json.RawMessage `json:"result"`
}

ResponseWithHeight defines a response object type that wraps an original response with a height.

type SignerFn

type SignerFn func(accounts.Account, string, []byte) ([]byte, error)

SignerFn is a signer callback function to request a header to be signed by a backing account.

type Snapshot

type Snapshot struct {
	Number       uint64                    `json:"number"`       // Block number where the snapshot was created
	Hash         common.Hash               `json:"hash"`         // Block hash where the snapshot was created
	ValidatorSet *ValidatorSet             `json:"validatorSet"` // Validator set at this moment
	Recents      map[uint64]common.Address `json:"recents"`      // Set of recent signers for spam protections
	// contains filtered or unexported fields
}

Snapshot is the state of the authorization voting at a given point in time.

func (*Snapshot) Difficulty

func (s *Snapshot) Difficulty(signer common.Address) uint64

Difficulty returns the difficulty for a particular signer at the current snapshot number

func (*Snapshot) GetSignerSuccessionNumber

func (s *Snapshot) GetSignerSuccessionNumber(signer common.Address) (int, error)

GetSignerSuccessionNumber returns the relative position of signer in terms of the in-turn proposer

type Span

type Span struct {
	ID         uint64 `json:"span_id" yaml:"span_id"`
	StartBlock uint64 `json:"start_block" yaml:"start_block"`
	EndBlock   uint64 `json:"end_block" yaml:"end_block"`
}

Span represents a current bor span

type TotalVotingPowerExceededError

type TotalVotingPowerExceededError struct {
	Sum        int64
	Validators []*Validator
}

TotalVotingPowerExceededError is returned when the maximum allowed total voting power is exceeded

func (*TotalVotingPowerExceededError) Error

type UnauthorizedProposerError

type UnauthorizedProposerError struct {
	Number   uint64
	Proposer []byte
}

UnauthorizedProposerError is returned if a header is [being] signed by an unauthorized entity.

func (*UnauthorizedProposerError) Error

func (e *UnauthorizedProposerError) Error() string

type UnauthorizedSignerError

type UnauthorizedSignerError struct {
	Number uint64
	Signer []byte
}

UnauthorizedSignerError is returned if a header is [being] signed by an unauthorized entity.

func (*UnauthorizedSignerError) Error

func (e *UnauthorizedSignerError) Error() string

type Validator

type Validator struct {
	ID               uint64         `json:"ID"`
	Address          common.Address `json:"signer"`
	VotingPower      int64          `json:"power"`
	ProposerPriority int64          `json:"accum"`
}

Validator represets Volatile state for each Validator

func NewValidator

func NewValidator(address common.Address, votingPower int64) *Validator

NewValidator creates new validator

func ParseValidators

func ParseValidators(validatorsBytes []byte) ([]*Validator, error)

ParseValidators returns validator set bytes

func (*Validator) Cmp

func (v *Validator) Cmp(other *Validator) *Validator

Cmp returns the one validator with a higher ProposerPriority. If ProposerPriority is same, it returns the validator with lexicographically smaller address

func (*Validator) Copy

func (v *Validator) Copy() *Validator

Copy creates a new copy of the validator so we can mutate ProposerPriority. Panics if the validator is nil.

func (*Validator) HeaderBytes

func (v *Validator) HeaderBytes() []byte

HeaderBytes return header bytes

func (*Validator) MinimalVal

func (v *Validator) MinimalVal() MinimalVal

MinimalVal returns block number of last validator update

func (*Validator) PowerBytes

func (v *Validator) PowerBytes() []byte

PowerBytes return power bytes

func (*Validator) String

func (v *Validator) String() string

type ValidatorSet

type ValidatorSet struct {
	// NOTE: persisted via reflect, must be exported.
	Validators []*Validator `json:"validators"`
	Proposer   *Validator   `json:"proposer"`
	// contains filtered or unexported fields
}

ValidatorSet represent a set of *Validator at a given height. The validators can be fetched by address or index. The index is in order of .Address, so the indices are fixed for all rounds of a given blockchain height - ie. the validators are sorted by their address. On the other hand, the .ProposerPriority of each validator and the designated .GetProposer() of a set changes every round, upon calling .IncrementProposerPriority(). NOTE: Not goroutine-safe. NOTE: All get/set to validators should copy the value for safety.

func NewValidatorSet

func NewValidatorSet(valz []*Validator) *ValidatorSet

NewValidatorSet initializes a ValidatorSet by copying over the values from `valz`, a list of Validators. If valz is nil or empty, the new ValidatorSet will have an empty list of Validators. The addresses of validators in `valz` must be unique otherwise the function panics.

func (*ValidatorSet) Copy

func (vals *ValidatorSet) Copy() *ValidatorSet

Copy each validator into a new ValidatorSet.

func (*ValidatorSet) CopyIncrementProposerPriority

func (vals *ValidatorSet) CopyIncrementProposerPriority(times int) *ValidatorSet

Increment ProposerPriority and update the proposer on a copy, and return it.

func (*ValidatorSet) GetByAddress

func (vals *ValidatorSet) GetByAddress(address common.Address) (index int, val *Validator)

GetByAddress returns an index of the validator with address and validator itself if found. Otherwise, -1 and nil are returned.

func (*ValidatorSet) GetByIndex

func (vals *ValidatorSet) GetByIndex(index int) (address []byte, val *Validator)

GetByIndex returns the validator's address and validator itself by index. It returns nil values if index is less than 0 or greater or equal to len(ValidatorSet.Validators).

func (*ValidatorSet) GetProposer

func (vals *ValidatorSet) GetProposer() (proposer *Validator)

GetProposer returns the current proposer. If the validator set is empty, nil is returned.

func (*ValidatorSet) HasAddress

func (vals *ValidatorSet) HasAddress(address []byte) bool

HasAddress returns true if address given is in the validator set, false - otherwise.

func (*ValidatorSet) IncrementProposerPriority

func (vals *ValidatorSet) IncrementProposerPriority(times int)

IncrementProposerPriority increments ProposerPriority of each validator and updates the proposer. Panics if validator set is empty. `times` must be positive.

func (*ValidatorSet) IsNilOrEmpty

func (vals *ValidatorSet) IsNilOrEmpty() bool

Nil or empty validator sets are invalid.

func (*ValidatorSet) Iterate

func (vals *ValidatorSet) Iterate(fn func(index int, val *Validator) bool)

Iterate will run the given function over the set.

func (*ValidatorSet) RescalePriorities

func (vals *ValidatorSet) RescalePriorities(diffMax int64)

func (*ValidatorSet) Size

func (vals *ValidatorSet) Size() int

Size returns the length of the validator set.

func (*ValidatorSet) String

func (vals *ValidatorSet) String() string

func (*ValidatorSet) StringIndented

func (vals *ValidatorSet) StringIndented(indent string) string

func (*ValidatorSet) TotalVotingPower

func (vals *ValidatorSet) TotalVotingPower() int64

TotalVotingPower returns the sum of the voting powers of all validators. It recomputes the total voting power if required.

func (*ValidatorSet) UpdateWithChangeSet

func (vals *ValidatorSet) UpdateWithChangeSet(changes []*Validator) error

UpdateWithChangeSet attempts to update the validator set with 'changes'. It performs the following steps:

  • validates the changes making sure there are no duplicates and splits them in updates and deletes
  • verifies that applying the changes will not result in errors
  • computes the total voting power BEFORE removals to ensure that in the next steps the priorities across old and newly added validators are fair
  • computes the priorities of new validators against the final set
  • applies the updates against the validator set
  • applies the removals against the validator set
  • performs scaling and centering of priority values

If an error is detected during verification steps, it is returned and the validator set is not changed.

type ValidatorsByAddress

type ValidatorsByAddress []*Validator

Sort validators by address.

func (ValidatorsByAddress) Len

func (valz ValidatorsByAddress) Len() int

func (ValidatorsByAddress) Less

func (valz ValidatorsByAddress) Less(i, j int) bool

func (ValidatorsByAddress) Swap

func (valz ValidatorsByAddress) Swap(i, j int)

type WrongDifficultyError

type WrongDifficultyError struct {
	Number   uint64
	Expected uint64
	Actual   uint64
	Signer   []byte
}

WrongDifficultyError is returned if the difficulty of a block doesn't match the turn of the signer.

func (*WrongDifficultyError) Error

func (e *WrongDifficultyError) Error() string

Jump to

Keyboard shortcuts

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