polybft

package
v0.7.3-beta3 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2023 License: Apache-2.0 Imports: 52 Imported by: 1

README

Polybft consensus protocol

Polybft is a consensus protocol, which runs go-ibft consensus engine.

It has native support for running bridge, which enables running cross-chain transactions with Ethereum-compatible blockchains.

Setup local testing environment

Precondition
  1. Build binary

    go build -o polygon-edge .
    
  2. Init secrets - this command is used to generate account secrets (ECDSA, BLS as well as P2P networking node id). --data-dir denotes folder prefix names and --num how many accounts need to be created. This command is for testing purposes only.

    polygon-edge polybft-secrets --data-dir test-chain- --num 4
    
  3. Start rootchain server - rootchain server is a Geth instance running in dev mode, which simulates Ethereum network. This command is for testing purposes only.

    polygon-edge rootchain server
    
  4. Generate manifest file - manifest file contains public validator information as well as bridge configuration. It is intermediary file, which is later used for genesis specification generation as well as rootchain contracts deployment.

    There are two ways to provide validators information:

    • all the validators information are present in local storage of single host and therefore directory if provided using --validators-path flag and validators folder prefix names using --validators-prefix flag

      polygon-edge manifest [--validators-path ./] [--validators-prefix test-chain-]
      [--path ./manifest.json] [--premine-validators 100]
      
    • validators information are scafollded on multiple hosts and therefore necessary information are supplied using --validators flag. Validator information needs to be supplied in the strictly following format: <multi address>:<public ECDSA address>:<public BLS key>:<BLS signature>. Note: when specifying validators via validators flag, entire multi address must be specified.

      polygon-edge manifest 
      --validators /ip4/127.0.0.1/tcp/30301/p2p/16Uiu2HAmV5hqAp77untfJRorxqKmyUxgaVn8YHFjBJm9gKMms3mr:0xDcBe0024206ec42b0Ef4214Ac7B71aeae1A11af0:1cf134e02c6b2afb2ceda50bf2c9a01da367ac48f7783ee6c55444e1cab418ec0f52837b90a4d8cf944814073fc6f2bd96f35366a3846a8393e3cb0b19197cde23e2b40c6401fa27ff7d0c36779d9d097d1393cab6fc1d332f92fb3df850b78703b2989d567d1344e219f0667a1863f52f7663092276770cf513f9704b5351c4:11b18bde524f4b02258a8d196b687f8d8e9490d536718666dc7babca14eccb631c238fb79aa2b44a5a4dceccad2dd797f537008dda185d952226a814c1acf7c2
      [--validators /ip4/127.0.0.1/tcp/30302/p2p/16Uiu2HAmGmidRQY5BGJPGVRF8p1pYFdfzuf1StHzXGLDizuxJxex:0x2da750eD4AE1D5A7F7c996Faec592F3d44060e90:088d92c25b5f278750534e8a902da604a1aa39b524b4511f5f47c3a386374ca3031b667beb424faef068a01cee3428a1bc8c1c8bab826f30a1ee03fbe90cb5f01abcf4abd7af3bbe83eaed6f82179b9cbdc417aad65d919b802d91c2e1aaefec27ba747158bc18a0556e39bfc9175c099dd77517a85731894bbea3d191a622bc:08dc3006352fdc01b331907fd3a68d4d68ed40329032598c1c0faa260421d66720965ace3ba29c6d6608ec1facdbf4624bca72df36c34afd4bdd753c4dfe049c]
      [--path ./manifest.json] [--premine-validators 100]
      
  5. Deploy and initialize rootchain contracts - this command deploys rootchain smart contracts and initializes them. It also updates manifest configuration with rootchain contract addresses and rootchain default sender address.

    polygon-edge rootchain init-contracts 
    --data-dir <local_storage_secrets_path> | [--config <cloud_secrets_manager_config_path>] 
    [--manifest ./manifest.json]
    [--json-rpc http://127.0.0.1:8545]
    [--test]
    
  6. Create chain configuration - this command creates chain configuration, which is needed to run a blockchain

    polygon-edge genesis --block-gas-limit 10000000 --epoch-size 10
    [--consensus polybft] [--bridge-json-rpc <rootchain_ip_address>] [--manifest ./manifest.json]
    
  7. Fund validators on rootchain - in order for validators to be able to send transactions to Ethereum, they need to be funded in order to be able to cover gas cost. This command is for testing purposes only.

    polygon-edge rootchain fund --data-dir test-chain- --num 4
    
  8. Run (child chain) cluster, consisting of 4 Edge clients in this particular example

    polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :5001 --libp2p :30301 --jsonrpc :9545 --seal --log-level DEBUG
    
    polygon-edge server --data-dir ./test-chain-2 --chain genesis.json --grpc-address :5002 --libp2p :30302 --jsonrpc :10002 --seal --log-level DEBUG
    
    polygon-edge server --data-dir ./test-chain-3 --chain genesis.json --grpc-address :5003 --libp2p :30303 --jsonrpc :10003 --seal --log-level DEBUG
    
    polygon-edge server --data-dir ./test-chain-4 --chain genesis.json --grpc-address :5004 --libp2p :30304 --jsonrpc :10004 --seal --log-level DEBUG
    

    It is possible to run child chain nodes in "relayer" mode. It allows automatic execution of deposit events on behalf of users. In order to start node in relayer mode, it is necessary to supply --relayer flag:

    polygon-edge server --data-dir ./test-chain-1 --chain genesis.json --grpc-address :5001 --libp2p :30301 --jsonrpc :9545 --seal --log-level DEBUG --relayer
    

Documentation

Overview

Package polybft implements PBFT consensus algorithm integration and bridge feature

Index

Constants

View Source
const (
	// ExtraVanity represents a fixed number of extra-data bytes reserved for proposer vanity
	ExtraVanity = 32

	// ExtraSeal represents the fixed number of extra-data bytes reserved for proposer seal
	ExtraSeal = 65
)

Variables

View Source
var (
	ExitEventABI           = contractsapi.L2StateSender.Abi.Events["L2StateSynced"]
	ExitEventInputsABIType = ExitEventABI.Inputs
)
View Source
var PolyBFTMixDigest = types.StringToHash("adce6e5230abe012342a44e4e9b6d05997d6f015387ae0e59be924afc7ec70c1")

PolyBFTMixDigest represents a hash of "PolyBFT Mix" to identify whether the block is from PolyBFT consensus engine

Functions

func Factory

func Factory(params *consensus.Params) (consensus.Consensus, error)

Factory is the factory function to create a discovery consensus

func GenesisPostHookFactory

func GenesisPostHookFactory(config *chain.Chain, engineName string) func(txn *state.Transition) error

func GetIbftExtraClean

func GetIbftExtraClean(extraRaw []byte) ([]byte, error)

GetIbftExtraClean returns unmarshaled extra field from the passed in header, but without signatures for the given header (it only includes signatures for the parent block)

func NewStateProvider

func NewStateProvider(transition *state.Transition) contract.Provider

NewStateProvider initializes EVM against given state and chain config and returns stateProvider instance which is an abstraction for smart contract calls

func NewStateSyncManager

func NewStateSyncManager(logger hclog.Logger, state *State, config *stateSyncConfig) (*stateSyncManager, error)

NewStateSyncManager creates a new instance of state sync manager

func NewValidatorSet

func NewValidatorSet(valz AccountSet, logger hclog.Logger) *validatorSet

NewValidatorSet creates a new validator set.

Types

type AccountSet

type AccountSet []*ValidatorMetadata

AccountSet is a type alias for slice of ValidatorMetadata instances

func (AccountSet) ApplyDelta

func (as AccountSet) ApplyDelta(validatorsDelta *ValidatorSetDelta) (AccountSet, error)

ApplyDelta receives ValidatorSetDelta and applies it to the values from the current AccountSet (removes the ones marked for deletion and adds the one which are being added by delta) Function returns new AccountSet with old and new data merged. AccountSet is immutable!

func (AccountSet) ContainsAddress

func (as AccountSet) ContainsAddress(address types.Address) bool

ContainsAddress checks whether ValidatorMetadata with given address is present in the AccountSet

func (AccountSet) ContainsNodeID

func (as AccountSet) ContainsNodeID(nodeID string) bool

ContainsNodeID checks whether ValidatorMetadata with given nodeID is present in the AccountSet

func (AccountSet) Copy

func (as AccountSet) Copy() AccountSet

Copy returns deep copy of AccountSet

func (AccountSet) Equals

func (as AccountSet) Equals(other AccountSet) bool

Equals compares checks if two AccountSet instances are equal (ordering is important)

func (AccountSet) GetAddresses

func (as AccountSet) GetAddresses() []types.Address

GetAddresses aggregates addresses for given AccountSet

func (AccountSet) GetAddressesAsSet

func (as AccountSet) GetAddressesAsSet() map[types.Address]struct{}

GetAddresses aggregates addresses as map for given AccountSet

func (AccountSet) GetBlsKeys

func (as AccountSet) GetBlsKeys() []*bls.PublicKey

GetBlsKeys aggregates public BLS keys for given AccountSet

func (AccountSet) GetFilteredValidators

func (as AccountSet) GetFilteredValidators(bitmap bitmap.Bitmap) (AccountSet, error)

GetFilteredValidators returns filtered validators based on provided bitmap. Filtered validators will contain validators whose index corresponds to the position in bitmap which has value set to 1.

func (*AccountSet) GetTotalVotingPower

func (as *AccountSet) GetTotalVotingPower() *big.Int

GetTotalVotingPower calculates sum of voting power for each validator in the AccountSet

func (AccountSet) GetValidatorMetadata

func (as AccountSet) GetValidatorMetadata(address types.Address) *ValidatorMetadata

GetValidatorMetadata tries to retrieve validator account metadata by given address from the account set. It returns nil if such account is not found.

func (AccountSet) Hash

func (as AccountSet) Hash() (types.Hash, error)

Hash returns hash value of the AccountSet

func (AccountSet) Index

func (as AccountSet) Index(addr types.Address) int

Index returns index of the given ValidatorMetadata, identified by address within the AccountSet. If given ValidatorMetadata is not present, it returns -1.

func (AccountSet) Len

func (as AccountSet) Len() int

Len returns length of AccountSet

func (AccountSet) Marshal

func (as AccountSet) Marshal() ([]byte, error)

Marshal marshals AccountSet to JSON

func (AccountSet) String

func (as AccountSet) String() string

fmt.Stringer implementation

func (AccountSet) ToAPIBinding

func (as AccountSet) ToAPIBinding() []*contractsapi.Validator

ToAPIBinding converts AccountSet to slice of contract api stubs to be encoded

func (*AccountSet) Unmarshal

func (as *AccountSet) Unmarshal(b []byte) error

Unmarshal unmarshals AccountSet from JSON

type BlockBuilder

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

func NewBlockBuilder

func NewBlockBuilder(params *BlockBuilderParams) *BlockBuilder

func (*BlockBuilder) Block

func (b *BlockBuilder) Block() *types.Block

Block returns the built block if nil, it is not built yet

func (*BlockBuilder) Build

func (b *BlockBuilder) Build(handler func(h *types.Header)) (*types.FullBlock, error)

Build creates the state and the final block

func (*BlockBuilder) Fill

func (b *BlockBuilder) Fill()

Fill fills the block with transactions from the txpool

func (*BlockBuilder) GetState

func (b *BlockBuilder) GetState() *state.Transition

GetState returns Transition reference

func (*BlockBuilder) Receipts

func (b *BlockBuilder) Receipts() []*types.Receipt

Receipts returns the collection of transaction receipts for given block

func (*BlockBuilder) Reset

func (b *BlockBuilder) Reset() error

Init initializes block builder before adding transactions and actual block building

func (*BlockBuilder) WriteTx

func (b *BlockBuilder) WriteTx(tx *types.Transaction) error

WriteTx applies given transaction to the state. If transaction apply fails, it reverts the saved snapshot.

type BlockBuilderParams

type BlockBuilderParams struct {
	// Parent block
	Parent *types.Header

	// Executor
	Executor *state.Executor

	// Coinbase that is signing the block
	Coinbase types.Address

	// GasLimit is the gas limit for the block
	GasLimit uint64

	// duration for one block
	BlockTime time.Duration

	// Logger
	Logger hcf.Logger

	// txPoolInterface implementation
	TxPool txPoolInterface
}

BlockBuilderParams are fields for the block that cannot be changed

type BridgeConfig

type BridgeConfig struct {
	BridgeAddr              types.Address            `json:"stateSenderAddr"`
	CheckpointAddr          types.Address            `json:"checkpointAddr"`
	RootERC20PredicateAddr  types.Address            `json:"rootERC20PredicateAddr"`
	RootNativeERC20Addr     types.Address            `json:"rootNativeERC20Addr"`
	JSONRPCEndpoint         string                   `json:"jsonRPCEndpoint"`
	EventTrackerStartBlocks map[types.Address]uint64 `json:"eventTrackerStartBlocks"`
}

BridgeConfig is the rootchain bridge configuration

type BridgeTransport

type BridgeTransport interface {
	Multicast(msg interface{})
}

BridgeTransport is an abstraction of network layer for a bridge

type CheckpointData

type CheckpointData struct {
	BlockRound            uint64
	EpochNumber           uint64
	CurrentValidatorsHash types.Hash
	NextValidatorsHash    types.Hash
	EventRoot             types.Hash
}

CheckpointData represents data needed for checkpointing mechanism

func (*CheckpointData) Copy

func (c *CheckpointData) Copy() *CheckpointData

Copy returns deep copy of CheckpointData instance

func (*CheckpointData) Hash

func (c *CheckpointData) Hash(chainID uint64, blockNumber uint64, blockHash types.Hash) (types.Hash, error)

Hash calculates keccak256 hash of the CheckpointData. CheckpointData is ABI encoded and then hashed.

func (*CheckpointData) MarshalRLPWith

func (c *CheckpointData) MarshalRLPWith(ar *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith defines the marshal function implementation for CheckpointData

func (*CheckpointData) UnmarshalRLPWith

func (c *CheckpointData) UnmarshalRLPWith(v *fastrlp.Value) error

UnmarshalRLPWith unmarshals CheckpointData object from the RLP format

func (*CheckpointData) Validate

func (c *CheckpointData) Validate(parentCheckpoint *CheckpointData,
	currentValidators AccountSet, nextValidators AccountSet) error

Validate encapsulates validation logic for checkpoint data (with regards to current and next epoch validators)

func (*CheckpointData) ValidateBasic

func (c *CheckpointData) ValidateBasic(parentCheckpoint *CheckpointData) error

ValidateBasic encapsulates basic validation logic for checkpoint data. It only checks epoch numbers validity and whether validators hashes are non-empty.

type CheckpointManager

type CheckpointManager interface {
	PostBlock(req *PostBlockRequest) error
	BuildEventRoot(epoch uint64) (types.Hash, error)
	GenerateExitProof(exitID uint64) (types.Proof, error)
}

type CheckpointStore

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

Bolt DB schema:

exit events/ |--> (id+epoch+blockNumber) -> *ExitEvent (json marshalled) |--> (exitEventID) -> epochNumber

type CommitmentMessageSigned

type CommitmentMessageSigned struct {
	Message      *contractsapi.StateSyncCommitment
	AggSignature Signature
	PublicKeys   [][]byte
}

CommitmentMessageSigned encapsulates commitment message with aggregated signatures

func (*CommitmentMessageSigned) ContainsStateSync

func (cm *CommitmentMessageSigned) ContainsStateSync(stateSyncID uint64) bool

ContainsStateSync checks if commitment contains given state sync event

func (*CommitmentMessageSigned) DecodeAbi

func (cm *CommitmentMessageSigned) DecodeAbi(txData []byte) error

DecodeAbi contains logic for decoding given ABI data

func (*CommitmentMessageSigned) EncodeAbi

func (cm *CommitmentMessageSigned) EncodeAbi() ([]byte, error)

EncodeAbi contains logic for encoding arbitrary data into ABI format

func (*CommitmentMessageSigned) Hash

func (cm *CommitmentMessageSigned) Hash() (types.Hash, error)

Hash calculates hash value for commitment object.

func (*CommitmentMessageSigned) VerifyStateSyncProof

func (cm *CommitmentMessageSigned) VerifyStateSyncProof(proof []types.Hash,
	stateSync *contractsapi.StateSyncedEvent) error

VerifyStateSyncProof validates given state sync proof against merkle tree root hash contained in the CommitmentMessage

type EpochStore

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

type ExitEvent

type ExitEvent struct {
	// ID is the decoded 'index' field from the event
	ID uint64 `abi:"id"`
	// Sender is the decoded 'sender' field from the event
	Sender ethgo.Address `abi:"sender"`
	// Receiver is the decoded 'receiver' field from the event
	Receiver ethgo.Address `abi:"receiver"`
	// Data is the decoded 'data' field from the event
	Data []byte `abi:"data"`
	// EpochNumber is the epoch number in which exit event was added
	EpochNumber uint64 `abi:"-"`
	// BlockNumber is the block in which exit event was added
	BlockNumber uint64 `abi:"-"`
}

ExitEvent is an event emitted by Exit contract

type Extra

type Extra struct {
	Validators *ValidatorSetDelta
	Seal       []byte
	Parent     *Signature
	Committed  *Signature
	Checkpoint *CheckpointData
}

Extra defines the structure of the extra field for Istanbul

func GetIbftExtra

func GetIbftExtra(extraB []byte) (*Extra, error)

GetIbftExtra returns the istanbul extra data field from the passed in header

func (*Extra) MarshalRLPTo

func (i *Extra) MarshalRLPTo(dst []byte) []byte

MarshalRLPTo defines the marshal function wrapper for Extra

func (*Extra) MarshalRLPWith

func (i *Extra) MarshalRLPWith(ar *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith defines the marshal function implementation for Extra

func (*Extra) UnmarshalRLP

func (i *Extra) UnmarshalRLP(input []byte) error

UnmarshalRLP defines the unmarshal function wrapper for Extra

func (*Extra) UnmarshalRLPWith

func (i *Extra) UnmarshalRLPWith(v *fastrlp.Value) error

UnmarshalRLPWith defines the unmarshal implementation for Extra

func (*Extra) ValidateDelta

func (i *Extra) ValidateDelta(oldValidators AccountSet, newValidators AccountSet) error

ValidateDelta validates validator set delta provided in the Extra with the one being calculated by the validator itself

func (*Extra) ValidateFinalizedData

func (i *Extra) ValidateFinalizedData(header *types.Header, parent *types.Header, parents []*types.Header,
	chainID uint64, consensusBackend polybftBackend, domain []byte, logger hclog.Logger) error

ValidateFinalizedData contains extra data validations for finalized headers

func (*Extra) ValidateParentSignatures

func (i *Extra) ValidateParentSignatures(blockNumber uint64, consensusBackend polybftBackend, parents []*types.Header,
	parent *types.Header, parentExtra *Extra, chainID uint64, domain []byte, logger hclog.Logger) error

ValidateParentSignatures validates signatures for parent block

type IBFTConsensusWrapper

type IBFTConsensusWrapper struct {
	*core.IBFT
}

IBFTConsensusWrapper is a convenience wrapper for the go-ibft package

type Manifest

type Manifest struct {
	GenesisValidators []*Validator     `json:"validators"`
	RootchainConfig   *RootchainConfig `json:"rootchain"`
	ChainID           int64            `json:"chainID"`
}

Manifest holds metadata, such as genesis validators and rootchain configuration

func LoadManifest

func LoadManifest(metadataFile string) (*Manifest, error)

LoadManifest deserializes Manifest instance

func (*Manifest) Save

func (m *Manifest) Save(manifestPath string) error

Save marshals RootchainManifest instance to json and persists it to given location

type MessageSignature

type MessageSignature struct {
	// Signer of the vote
	From string
	// Signature of the message
	Signature []byte
}

MessageSignature encapsulates sender identifier and its signature

type PendingCommitment

type PendingCommitment struct {
	*contractsapi.StateSyncCommitment
	MerkleTree *merkle.MerkleTree
	Epoch      uint64
}

PendingCommitment holds merkle trie of bridge transactions accompanied by epoch number

func NewPendingCommitment

func NewPendingCommitment(epoch uint64, stateSyncEvents []*contractsapi.StateSyncedEvent) (*PendingCommitment, error)

NewPendingCommitment creates a new commitment object

func (*PendingCommitment) Hash

func (cm *PendingCommitment) Hash() (types.Hash, error)

Hash calculates hash value for commitment object.

type PolyBFTConfig

type PolyBFTConfig struct {
	// InitialValidatorSet are the genesis validators
	InitialValidatorSet []*Validator `json:"initialValidatorSet"`

	// Bridge is the rootchain bridge configuration
	Bridge *BridgeConfig `json:"bridge"`

	// EpochSize is size of epoch
	EpochSize uint64 `json:"epochSize"`

	// EpochReward is assigned to validators for blocks sealing
	EpochReward uint64 `json:"epochReward"`

	// SprintSize is size of sprint
	SprintSize uint64 `json:"sprintSize"`

	// BlockTime is target frequency of blocks production
	BlockTime time.Duration `json:"blockTime"`

	// Governance is the initial governance address
	Governance types.Address `json:"governance"`

	// TODO: Remove these two addresses as they are hardcoded and known in advance
	// Address of the system contracts, as of now (testing) this is populated automatically during genesis
	ValidatorSetAddr  types.Address `json:"validatorSetAddr"`
	StateReceiverAddr types.Address `json:"stateReceiverAddr"`
}

PolyBFTConfig is the configuration file for the Polybft consensus protocol.

func GetPolyBFTConfig

func GetPolyBFTConfig(chainConfig *chain.Chain) (PolyBFTConfig, error)

GetPolyBFTConfig deserializes provided chain config and returns PolyBFTConfig

func (*PolyBFTConfig) IsBridgeEnabled

func (p *PolyBFTConfig) IsBridgeEnabled() bool

type Polybft

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

func (*Polybft) Close

func (p *Polybft) Close() error

Close closes the connection

func (*Polybft) GetBlockCreator

func (p *Polybft) GetBlockCreator(h *types.Header) (types.Address, error)

GetBlockCreator retrieves the block creator (or signer) given the block header

func (*Polybft) GetBridgeProvider

func (p *Polybft) GetBridgeProvider() consensus.BridgeDataProvider

GetBridgeProvider returns an instance of BridgeDataProvider

func (*Polybft) GetSyncProgression

func (p *Polybft) GetSyncProgression() *progress.Progression

GetSyncProgression retrieves the current sync progression, if any

func (*Polybft) GetValidators

func (p *Polybft) GetValidators(blockNumber uint64, parents []*types.Header) (AccountSet, error)

func (*Polybft) Initialize

func (p *Polybft) Initialize() error

Initialize initializes the consensus (e.g. setup data)

func (*Polybft) Multicast

func (p *Polybft) Multicast(msg *ibftProto.Message)

Multicast is implementation of core.Transport interface

func (*Polybft) PreCommitState

func (p *Polybft) PreCommitState(_ *types.Header, _ *state.Transition) error

PreCommitState a hook to be called before finalizing state transition on inserting block

func (*Polybft) ProcessHeaders

func (p *Polybft) ProcessHeaders(_ []*types.Header) error

ProcessHeaders updates the snapshot based on the verified headers

func (*Polybft) Start

func (p *Polybft) Start() error

Start starts the consensus and servers

func (*Polybft) VerifyHeader

func (p *Polybft) VerifyHeader(header *types.Header) error

VerifyHeader implements consensus.Engine and checks whether a header conforms to the consensus rules

type PostBlockRequest

type PostBlockRequest struct {
	// FullBlock is a reference of the executed block
	FullBlock *types.FullBlock
	// Epoch is the epoch number of the executed block
	Epoch uint64
	// IsEpochEndingBlock indicates if this was the last block of given epoch
	IsEpochEndingBlock bool
}

type PostEpochRequest

type PostEpochRequest struct {
	// NewEpochID is the id of the new epoch
	NewEpochID uint64

	// FirstBlockOfEpoch is the number of the epoch beginning block
	FirstBlockOfEpoch uint64

	// SystemState is the state of the governance smart contracts
	// after this block
	SystemState SystemState

	// ValidatorSet is the validator set for the new epoch
	ValidatorSet *validatorSet
}

type PrioritizedValidator

type PrioritizedValidator struct {
	Metadata         *ValidatorMetadata
	ProposerPriority *big.Int
}

PrioritizedValidator holds ValidatorMetadata together with priority

type ProposerCalculator

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

func NewProposerCalculator

func NewProposerCalculator(config *runtimeConfig, logger hclog.Logger) (*ProposerCalculator, error)

NewProposerCalculator creates a new proposer calculator object

func NewProposerCalculatorFromSnapshot

func NewProposerCalculatorFromSnapshot(pcs *ProposerSnapshot, config *runtimeConfig,
	logger hclog.Logger) *ProposerCalculator

NewProposerCalculator creates a new proposer calculator object

func (*ProposerCalculator) GetSnapshot

func (pc *ProposerCalculator) GetSnapshot() (*ProposerSnapshot, bool)

Get copy of the proposers' snapshot

func (*ProposerCalculator) PostBlock

func (pc *ProposerCalculator) PostBlock(req *PostBlockRequest) error

PostBlock is called on every insert of finalized block (either from consensus or syncer) It will update priorities and save the updated snapshot to db

type ProposerSnapshot

type ProposerSnapshot struct {
	Height     uint64
	Round      uint64
	Proposer   *PrioritizedValidator
	Validators []*PrioritizedValidator
}

ProposerSnapshot represents snapshot of one proposer calculation

func NewProposerSnapshot

func NewProposerSnapshot(height uint64, validators []*ValidatorMetadata) *ProposerSnapshot

NewProposerSnapshot creates ProposerSnapshot with height and validators with all priorities set to zero

func NewProposerSnapshotFromState

func NewProposerSnapshotFromState(config *runtimeConfig) (*ProposerSnapshot, error)

NewProposerSnapshotFromState create ProposerSnapshot from state if possible or from genesis block

func (*ProposerSnapshot) CalcProposer

func (pcs *ProposerSnapshot) CalcProposer(round, height uint64) (types.Address, error)

CalcProposer calculates next proposer

func (*ProposerSnapshot) Copy

func (pcs *ProposerSnapshot) Copy() *ProposerSnapshot

Copy Returns copy of current ProposerSnapshot object

func (*ProposerSnapshot) GetLatestProposer

func (pcs *ProposerSnapshot) GetLatestProposer(round, height uint64) (types.Address, error)

GetLatestProposer returns latest calculated proposer if any

func (ProposerSnapshot) GetTotalVotingPower

func (pcs ProposerSnapshot) GetTotalVotingPower() *big.Int

GetTotalVotingPower returns total voting power from all the validators

type ProposerSnapshotStore

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

type RootchainConfig

type RootchainConfig struct {
	StateSenderAddress        types.Address `json:"stateSenderAddress"`
	CheckpointManagerAddress  types.Address `json:"checkpointManagerAddress"`
	BLSAddress                types.Address `json:"blsAddress"`
	BN256G2Address            types.Address `json:"bn256G2Address"`
	ExitHelperAddress         types.Address `json:"exitHelperAddress"`
	RootERC20PredicateAddress types.Address `json:"rootERC20PredicateAddress"`
	RootNativeERC20Address    types.Address `json:"rootNativeERC20Address"`
	ERC20TemplateAddress      types.Address `json:"erc20TemplateAddress"`
}

RootchainConfig contains information about rootchain contract addresses as well as rootchain admin account address

func (*RootchainConfig) ToBridgeConfig

func (r *RootchainConfig) ToBridgeConfig() *BridgeConfig

ToBridgeConfig creates BridgeConfig instance

type Signature

type Signature struct {
	AggregatedSignature []byte
	Bitmap              []byte
}

Signature represents aggregated signatures of signers accompanied with a bitmap (in order to be able to determine identities of each signer)

func (*Signature) MarshalRLPWith

func (s *Signature) MarshalRLPWith(ar *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith marshals Signature object into RLP format

func (*Signature) UnmarshalRLPWith

func (s *Signature) UnmarshalRLPWith(v *fastrlp.Value) error

UnmarshalRLPWith unmarshals Signature object from the RLP format

func (*Signature) Verify

func (s *Signature) Verify(validators AccountSet, hash types.Hash, domain []byte, logger hclog.Logger) error

Verify is used to verify aggregated signature based on current validator set, message hash and domain

type State

type State struct {
	StateSyncStore        *StateSyncStore
	CheckpointStore       *CheckpointStore
	EpochStore            *EpochStore
	ProposerSnapshotStore *ProposerSnapshotStore
	// contains filtered or unexported fields
}

State represents a persistence layer which persists consensus data off-chain

type StateSyncManager

type StateSyncManager interface {
	Init() error
	Close()
	Commitment() (*CommitmentMessageSigned, error)
	GetStateSyncProof(stateSyncID uint64) (types.Proof, error)
	PostBlock(req *PostBlockRequest) error
	PostEpoch(req *PostEpochRequest) error
}

StateSyncManager is an interface that defines functions for state sync workflow

type StateSyncProof

type StateSyncProof struct {
	Proof     []types.Hash
	StateSync *contractsapi.StateSyncedEvent
}

type StateSyncStore

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

type SystemState

type SystemState interface {
	// GetValidatorSet retrieves current validator set from the smart contract
	GetValidatorSet() (AccountSet, error)
	// GetEpoch retrieves current epoch number from the smart contract
	GetEpoch() (uint64, error)
	// GetNextCommittedIndex retrieves next committed bridge state sync index
	GetNextCommittedIndex() (uint64, error)
}

SystemState is an interface to interact with the consensus system contracts in the chain

type SystemStateImpl

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

SystemStateImpl is implementation of SystemState interface

func NewSystemState

func NewSystemState(config *PolyBFTConfig, provider contract.Provider) *SystemStateImpl

NewSystemState initializes new instance of systemState which abstracts smart contracts functions

func (*SystemStateImpl) GetEpoch

func (s *SystemStateImpl) GetEpoch() (uint64, error)

GetEpoch retrieves current epoch number from the smart contract

func (*SystemStateImpl) GetNextCommittedIndex

func (s *SystemStateImpl) GetNextCommittedIndex() (uint64, error)

GetNextCommittedIndex retrieves next committed bridge state sync index

func (*SystemStateImpl) GetValidatorSet

func (s *SystemStateImpl) GetValidatorSet() (AccountSet, error)

GetValidatorSet retrieves current validator set from the smart contract

type TransportMessage

type TransportMessage struct {
	// Hash is encoded data
	Hash []byte
	// Message signature
	Signature []byte
	// From is the address of the message signer
	From string
	// Number of epoch
	EpochNumber uint64
}

TransportMessage represents the payload which is gossiped across the network

type Validator

type Validator struct {
	Address       types.Address
	BlsPrivateKey *bls.PrivateKey
	BlsKey        string
	BlsSignature  string
	Balance       *big.Int
	MultiAddr     string
}

Validator represents public information about validator accounts which are the part of genesis

func (*Validator) MarshalJSON

func (v *Validator) MarshalJSON() ([]byte, error)

func (Validator) ToValidatorInitAPIBinding

func (v Validator) ToValidatorInitAPIBinding() (*contractsapi.ValidatorInit, error)

ToValidatorInitAPIBinding converts Validator to instance of contractsapi.ValidatorInit

func (*Validator) ToValidatorMetadata

func (v *Validator) ToValidatorMetadata() (*ValidatorMetadata, error)

ToValidatorMetadata creates ValidatorMetadata instance

func (*Validator) UnmarshalBLSPublicKey

func (v *Validator) UnmarshalBLSPublicKey() (*bls.PublicKey, error)

UnmarshalBLSPublicKey unmarshals the hex encoded BLS public key

func (*Validator) UnmarshalBLSSignature

func (v *Validator) UnmarshalBLSSignature() (*bls.Signature, error)

UnmarshalBLSSignature unmarshals the hex encoded BLS signature

func (*Validator) UnmarshalJSON

func (v *Validator) UnmarshalJSON(data []byte) error

type ValidatorInfo

type ValidatorInfo struct {
	Address             ethgo.Address
	Stake               *big.Int
	TotalStake          *big.Int
	Commission          *big.Int
	WithdrawableRewards *big.Int
	Active              bool
}

ValidatorInfo is data transfer object which holds validator information, provided by smart contract

type ValidatorMetadata

type ValidatorMetadata struct {
	Address     types.Address
	BlsKey      *bls.PublicKey
	VotingPower *big.Int
}

ValidatorMetadata represents a validator metadata (its public identity)

func (*ValidatorMetadata) Copy

Copy returns a deep copy of ValidatorMetadata

func (*ValidatorMetadata) EqualAddressAndBlsKey

func (v *ValidatorMetadata) EqualAddressAndBlsKey(b *ValidatorMetadata) bool

EqualAddressAndBlsKey checks ValidatorMetadata equality against Address and BlsKey fields

func (*ValidatorMetadata) Equals

Equals checks ValidatorMetadata equality

func (*ValidatorMetadata) MarshalRLPWith

func (v *ValidatorMetadata) MarshalRLPWith(ar *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith marshals ValidatorMetadata to the RLP format

func (*ValidatorMetadata) String

func (v *ValidatorMetadata) String() string

fmt.Stringer implementation

func (*ValidatorMetadata) UnmarshalRLPWith

func (v *ValidatorMetadata) UnmarshalRLPWith(val *fastrlp.Value) error

UnmarshalRLPWith unmarshals ValidatorMetadata from the RLP format

type ValidatorSet

type ValidatorSet interface {
	// Includes check if given address is among the current validator set
	Includes(address types.Address) bool

	// Len returns the size of the validator set
	Len() int

	// Accounts returns the list of the ValidatorMetadata
	Accounts() AccountSet

	// checks if submitted signers have reached quorum
	HasQuorum(signers map[types.Address]struct{}) bool
}

ValidatorSet interface of the current validator set

type ValidatorSetDelta

type ValidatorSetDelta struct {
	// Added is the slice of added validators
	Added AccountSet
	// Updated is the slice of updated valiadtors
	Updated AccountSet
	// Removed is a bitmap of the validators removed from the set
	Removed bitmap.Bitmap
}

ValidatorSetDelta holds information about added and removed validators compared to the previous epoch

func (*ValidatorSetDelta) Copy

Copy creates deep copy of ValidatorSetDelta

func (*ValidatorSetDelta) Equals

func (d *ValidatorSetDelta) Equals(other *ValidatorSetDelta) bool

Equals checks validator set delta equality

func (*ValidatorSetDelta) IsEmpty

func (d *ValidatorSetDelta) IsEmpty() bool

IsEmpty returns indication whether delta is empty (namely added, updated slices and removed bitmap are empty)

func (*ValidatorSetDelta) MarshalRLPWith

func (d *ValidatorSetDelta) MarshalRLPWith(ar *fastrlp.Arena) *fastrlp.Value

MarshalRLPWith marshals ValidatorSetDelta to RLP format

func (*ValidatorSetDelta) String

func (d *ValidatorSetDelta) String() string

fmt.Stringer interface implementation

func (*ValidatorSetDelta) UnmarshalRLPWith

func (d *ValidatorSetDelta) UnmarshalRLPWith(v *fastrlp.Value) error

UnmarshalRLPWith unmarshals ValidatorSetDelta from RLP format

Directories

Path Synopsis
Code generated by scapi/gen.
Code generated by scapi/gen.

Jump to

Keyboard shortcuts

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