core

package
v0.0.0-...-77960fc Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2018 License: GPL-3.0 Imports: 41 Imported by: 0

Documentation

Overview

Package core implements the Ethereum consensus protocol.

Index

Constants

View Source
const (
	DepositEventName         = "Deposit"
	ExitedStartEventName     = "ExistedStart"
	BlockSubmittedEventName  = "BlockSubmitted"
	SubmitBlockMethodName    = "submitBlock"
	FromBlockKey             = "RootChain.FromBlock"
	CurrentBlockEventDataKey = "RootChain.CurrentBlockEventData"
)
View Source
const (

	// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
	BlockChainVersion = 3
)

Variables

View Source
var (
	// ErrKnownBlock is returned when a block to import is already known locally.
	ErrKnownBlock = errors.New("block already known")

	// ErrBlacklistedHash is returned if a block to import is on the blacklist.
	ErrBlacklistedHash = errors.New("blacklisted hash")

	// ErrNonceTooHigh is returned if the nonce of a transaction is higher than the
	// next one expected based on the local chain.
	ErrNonceTooHigh = errors.New("nonce too high")

	// ErrInvalidSender is returned if the transaction contains an invalid signature.
	ErrInvalidSender = errors.New("invalid sender")

	// ErrInsufficientFunds is returned if the total cost of executing a transaction
	ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")

	// ErrNegativeValue is a sanity error to ensure noone is able to specify a
	// transaction with a negative value.
	ErrNegativeValue = errors.New("negative value")

	// ErrOversizedData is returned if the input data of a transaction is greater
	// than some meaningful limit a user might use. This is not a consensus error
	// making the transaction invalid, rather a DOS protection.
	ErrOversizedData = errors.New("oversized data")

	// ErrTxInNotFound is returned if the tx in is not found by in index
	ErrTxInNotFound = errors.New("tx in not found")

	// ErrTxOutNotFound is returned if the tx out is not found by out index
	ErrTxOutNotFound = errors.New("tx out not found")

	// ErrTxOutNotOwned is returned if the tx out to be used is not owned by the tx sender
	ErrTxOutNotOwned = errors.New("tx out not owned")

	// ErrTxTotalAmountNotEqual is returned if the total amount of tx in and out not equal
	ErrTxTotalAmountNotEqual = errors.New("total amount of tx ins and outs not equal")

	// ErrAlreadySpent returns if the utxo as tx in has been spent already
	ErrAlreadySpent = errors.New("utxo already spent")
	// ErrNotEnoughTxFee is returned if the tx fee is not bigger than zero
	ErrNotEnoughTxFee = errors.New("not enough tx fee")

	// ErrDuplicateSpent returns if the duplicate spent is detected
	ErrDuplicateSpent = errors.New("duplicate spent")

	// ErrInvalidOutputAmount returns if the tx output has an amount less than 0
	ErrInvalidOutputAmount = errors.New("invalid tx output amount, it should be bigger than zero")
)
View Source
var DefaultTxPoolConfig = TxPoolConfig{
	Journal:   "transactions.rlp",
	Rejournal: time.Hour,

	PriceLimit: 1,
	PriceBump:  10,

	AccountSlots: 16,
	GlobalSlots:  4096,
	AccountQueue: 64,
	GlobalQueue:  1024,

	Lifetime: 3 * time.Hour,
}

DefaultTxPoolConfig contains the default configurations for the transaction pool.

View Source
var (

	// ErrNoGenesis returns when no genesis block found
	ErrNoGenesis = errors.New("Genesis not found in chain")
)

Functions

func GenesisBlockForTesting

func GenesisBlockForTesting(db store.Database, addr common.Address, balance *big.Int) *types.Block

GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.

func SetupGenesisBlock

func SetupGenesisBlock(db store.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error)

SetupGenesisBlock writes or updates the genesis block in db. The block that will be used is:

                     genesis == nil       genesis != nil
                  +------------------------------------------
db has no genesis |  main-net default  |  genesis
db has genesis    |  from DB           |  genesis (if compatible)

The stored chain configuration will be updated if it is compatible (i.e. does not specify a fork block below the local head block). In case of a conflict, the error is a *params.ConfigCompatError and the new, unwritten config is returned.

The returned chain configuration is never nil.

Types

type BlockChain

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

BlockChain represents the canonical chain given a database with a genesis block. The Blockchain manages chain imports, reverts, chain reorganisations.

Importing blocks in to the block chain happens according to the set of rules defined by the two stage Validator. Processing of blocks is done using the Processor which processes the included transaction. The validation of the state is done in the second part of the Validator. Failing results in aborting of the import.

The BlockChain also helps in returning blocks from **any** chain included in the database as well as blocks that represents the canonical chain. It's important to note that GetBlock can return any block and does not need to be included in the canonical one where as GetBlockByNumber always represents the canonical chain.

func NewBlockChain

func NewBlockChain(db store.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine) (*BlockChain, error)

NewBlockChain returns a fully initialised block chain using information available in the database. It initialises the default Ethereum Validator and Processor.

func (*BlockChain) BadBlocks

func (bc *BlockChain) BadBlocks() []*types.Block

BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network

func (*BlockChain) Config

func (bc *BlockChain) Config() *params.ChainConfig

Config retrieves the blockchain's chain configuration.

func (*BlockChain) CurrentBlock

func (bc *BlockChain) CurrentBlock() *types.Block

CurrentBlock retrieves the current head block of the canonical chain. The block is retrieved from the blockchain's internal cache.

func (*BlockChain) CurrentFastBlock

func (bc *BlockChain) CurrentFastBlock() *types.Block

CurrentFastBlock retrieves the current fast-sync head block of the canonical chain. The block is retrieved from the blockchain's internal cache.

func (*BlockChain) CurrentHeader

func (bc *BlockChain) CurrentHeader() *types.Header

CurrentHeader retrieves the current head header of the canonical chain. The header is retrieved from the HeaderChain's internal cache.

func (*BlockChain) Engine

func (bc *BlockChain) Engine() consensus.Engine

Engine retrieves the blockchain's consensus engine.

func (*BlockChain) Export

func (bc *BlockChain) Export(w io.Writer) error

Export writes the active chain to the given writer.

func (*BlockChain) ExportN

func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error

ExportN writes a subset of the active chain to the given writer.

func (*BlockChain) FastSyncCommitHead

func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error

FastSyncCommitHead sets the current head block to the one defined by the hash irrelevant what the chain contents were prior.

func (*BlockChain) Genesis

func (bc *BlockChain) Genesis() *types.Block

Genesis retrieves the chain's genesis block.

func (*BlockChain) GetAncestor

func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64)

GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the number of blocks to be individually checked before we reach the canonical chain.

Note: ancestor == 0 returns the same block, 1 returns its parent and so on.

func (*BlockChain) GetBlock

func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block

GetBlock retrieves a block from the database by hash and number, caching it if found.

func (*BlockChain) GetBlockByHash

func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block

GetBlockByHash retrieves a block from the database by hash, caching it if found.

func (*BlockChain) GetBlockByNumber

func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block

GetBlockByNumber retrieves a block from the database by number, caching it (associated with its hash) if found.

func (*BlockChain) GetBlockHashesFromHash

func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash

GetBlockHashesFromHash retrieves a number of block hashes starting at a given hash, fetching towards the genesis block.

func (*BlockChain) GetBlocksFromHash

func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block)

GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors. [deprecated by eth/62]

func (*BlockChain) GetBody

func (bc *BlockChain) GetBody(hash common.Hash) *types.Body

GetBody retrieves a block body (transactions and uncles) from the database by hash, caching it if found.

func (*BlockChain) GetBodyRLP

func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue

GetBodyRLP retrieves a block body in RLP encoding from the database by hash, caching it if found.

func (*BlockChain) GetHeader

func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header

GetHeader retrieves a block header from the database by hash and number, caching it if found.

func (*BlockChain) GetHeaderByHash

func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header

GetHeaderByHash retrieves a block header from the database by hash, caching it if found.

func (*BlockChain) GetHeaderByNumber

func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header

GetHeaderByNumber retrieves a block header from the database by number, caching it (associated with its hash) if found.

func (*BlockChain) HasBlock

func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool

HasBlock checks if a block is fully present in the database or not, caching it if present.

func (*BlockChain) HasHeader

func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool

HasHeader checks if a block header is present in the database or not, caching it if present.

func (*BlockChain) InsertChain

func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error)

InsertChain attempts to insert the given batch of blocks in to the canonical chain or, otherwise, create a fork. If an error is returned it will return the index number of the failing block as well an error describing what went wrong.

After insertion is done, all accumulated events will be fired.

func (*BlockChain) PostChainEvents

func (bc *BlockChain) PostChainEvents(events []interface{})

PostChainEvents iterates over the events generated by a chain insertion and posts them into the event feed. TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.

func (*BlockChain) Processor

func (bc *BlockChain) Processor() Processor

Processor returns the current processor.

func (*BlockChain) ReplaceHead

func (bc *BlockChain) ReplaceHead(block *types.Block) (err error)

ReplaceHead replace currentBlock

func (*BlockChain) Rollback

func (bc *BlockChain) Rollback(chain []common.Hash)

Rollback is designed to remove a chain of links from the database that aren't certain enough to be valid.

func (*BlockChain) SetProcessor

func (bc *BlockChain) SetProcessor(processor Processor)

SetProcessor sets the processor required for making state modifications.

func (*BlockChain) SetValidator

func (bc *BlockChain) SetValidator(validator BlockValidator)

SetValidator sets the validator which is used to validate incoming blocks.

func (*BlockChain) Stop

func (bc *BlockChain) Stop()

Stop stops the blockchain service. If any imports are currently in progress it will abort them using the procInterrupt.

func (*BlockChain) WriteBlock

func (bc *BlockChain) WriteBlock(block *types.Block) (err error)

WriteBlock writes only the block and its metadata to the database, The block body will be validated first.

func (*BlockChain) WriteDepositBlock

func (bc *BlockChain) WriteDepositBlock(block *types.Block) (err error)

WriteDepositBlock writes only the block and its metadata to the database,

type BlockReader

type BlockReader interface {
	HasBlock(hash common.Hash, blockNum uint64) bool
	CurrentBlock() *types.Block
	GetBlock(hash common.Hash, number uint64) *types.Block
	GetBlockByNumber(number uint64) *types.Block
}

BlockReader is an interface for block reading

type BlockSubmiittedEventHandler

type BlockSubmiittedEventHandler func(lastDepositBlockNum, currentBlockNum *big.Int) error

type BlockSubmittedEvent

type BlockSubmittedEvent struct {
	Root                [32]byte
	LastDepositBlockNum *big.Int
	SubmittedBlockNum   *big.Int
	Time                *big.Int
}

type BlockValidator

type BlockValidator interface {
	// ValidateBody validates the given block's content.
	ValidateBody(block *types.Block) error
}

BlockValidator is an interface which defines the standard for block validation. It is only responsible for validating block contents, as the header validation is done by the specific consensus engines.

type CacheConfig

type CacheConfig struct {
	Disabled      bool          // Whether to disable trie write caching (archive node)
	TrieNodeLimit int           // Memory limit (MB) at which to flush the current in-memory trie to disk
	TrieTimeLimit time.Duration // Time limit after which to flush the current in-memory trie to disk
}

CacheConfig contains the configuration values for the trie caching/pruning that's resident in a blockchain.

type ChainEvent

type ChainEvent struct {
	Block *types.Block
	Hash  common.Hash
}

type ChainHeadEvent

type ChainHeadEvent struct{ Block *types.Block }

type ChainSideEvent

type ChainSideEvent struct {
	Block *types.Block
}

type CurrentBlockEventData

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

func (*CurrentBlockEventData) DelLastBlockEventHash

func (self *CurrentBlockEventData) DelLastBlockEventHash(chainDb store.Database)

type DeleteCallback

type DeleteCallback func(rawdb.DatabaseDeleter, common.Hash, uint64)

DeleteCallback is a callback function that is called by SetHead before each header is deleted.

type DepositEvent

type DepositEvent struct {
	Depositor    common.Address
	DepositBlock *big.Int
	Token        common.Address
	Amount       *big.Int
	Raw          ethtypes.Log // Blockchain specific contextual infos
}

type DepositEventHandler

type DepositEventHandler func(depositBlockNum *big.Int, depositor, token common.Address, amount *big.Int) error

type Genesis

type Genesis struct {
	Config    *params.ChainConfig `json:"config"`
	Nonce     uint64              `json:"nonce"`
	Timestamp uint64              `json:"timestamp"`
	ExtraData []byte              `json:"extraData"`
	Coinbase  common.Address      `json:"coinbase"`
	Alloc     GenesisAlloc        `json:"alloc"      gencodec:"required"`

	// These fields are used for consensus tests. Please don't use them
	// in actual genesis blocks.
	Number     uint64      `json:"number"`
	ParentHash common.Hash `json:"parentHash"`
}

Genesis specifies the header fields, state of a genesis block. It also defines hard fork switch-over blocks through the chain configuration.

func DefaultGenesisBlock

func DefaultGenesisBlock() *Genesis

DefaultGenesisBlock returns the Ethereum main net genesis block.

func DefaultRinkebyGenesisBlock

func DefaultRinkebyGenesisBlock() *Genesis

DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.

func DefaultTestnetGenesisBlock

func DefaultTestnetGenesisBlock() *Genesis

DefaultTestnetGenesisBlock returns the Ropsten network genesis block.

func DeveloperGenesisBlock

func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis

DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must be seeded with the

func (*Genesis) Commit

func (g *Genesis) Commit(db store.Database) (*types.Block, error)

Commit writes the block and state of a genesis specification to the database. The block is committed as the canonical head block.

func (*Genesis) MustCommit

func (g *Genesis) MustCommit(db store.Database) *types.Block

MustCommit writes the genesis block and state to db, panicking on error. The block is committed as the canonical head block.

func (*Genesis) ToBlock

func (g *Genesis) ToBlock(db store.Database) *types.Block

ToBlock creates the genesis block and writes state of a genesis specification to the given database (or discards it if nil).

type GenesisAccount

type GenesisAccount struct {
	Code       []byte                      `json:"code,omitempty"`
	Storage    map[common.Hash]common.Hash `json:"storage,omitempty"`
	Balance    *big.Int                    `json:"balance" gencodec:"required"`
	Nonce      uint64                      `json:"nonce,omitempty"`
	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
}

GenesisAccount is an account in the state of the genesis block.

type GenesisAlloc

type GenesisAlloc map[common.Address]GenesisAccount

GenesisAlloc specifies the initial state that is part of the genesis block.

func (*GenesisAlloc) UnmarshalJSON

func (ga *GenesisAlloc) UnmarshalJSON(data []byte) error

UnmarshalJSON fills this obj with data from json

type GenesisMismatchError

type GenesisMismatchError struct {
	Stored, New common.Hash
}

GenesisMismatchError is raised when trying to overwrite an existing genesis block with an incompatible one.

func (*GenesisMismatchError) Error

func (e *GenesisMismatchError) Error() string

type HeaderChain

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

HeaderChain implements the basic block header chain logic that is shared by core.BlockChain and light.LightChain. It is not usable in itself, only as a part of either structure. It is not thread safe either, the encapsulating chain structures should do the necessary mutex locking/unlocking.

func NewHeaderChain

func NewHeaderChain(chainDb store.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error)

NewHeaderChain creates a new HeaderChain structure.

getValidator should return the parent's validator
procInterrupt points to the parent's interrupt semaphore
wg points to the parent's shutdown wait group

func (*HeaderChain) Config

func (hc *HeaderChain) Config() *params.ChainConfig

Config retrieves the header chain's chain configuration.

func (*HeaderChain) CurrentHeader

func (hc *HeaderChain) CurrentHeader() *types.Header

CurrentHeader retrieves the current head header of the canonical chain. The header is retrieved from the HeaderChain's internal cache.

func (*HeaderChain) Engine

func (hc *HeaderChain) Engine() consensus.Engine

Engine retrieves the header chain's consensus engine.

func (*HeaderChain) GetAncestor

func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64)

GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the number of blocks to be individually checked before we reach the canonical chain.

Note: ancestor == 0 returns the same block, 1 returns its parent and so on.

func (*HeaderChain) GetBlock

func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block

GetBlock implements consensus.ChainReader, and returns nil for every input as a header chain does not have blocks available for retrieval.

func (*HeaderChain) GetBlockHashesFromHash

func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash

GetBlockHashesFromHash retrieves a number of block hashes starting at a given hash, fetching towards the genesis block.

func (*HeaderChain) GetBlockNumber

func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64

GetBlockNumber retrieves the block number belonging to the given hash from the cache or database

func (*HeaderChain) GetHeader

func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header

GetHeader retrieves a block header from the database by hash and number, caching it if found.

func (*HeaderChain) GetHeaderByHash

func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header

GetHeaderByHash retrieves a block header from the database by hash, caching it if found.

func (*HeaderChain) GetHeaderByNumber

func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header

GetHeaderByNumber retrieves a block header from the database by number, caching it (associated with its hash) if found.

func (*HeaderChain) HasHeader

func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool

HasHeader checks if a block header is present in the database or not.

func (*HeaderChain) InsertHeaderChain

func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error)

InsertHeaderChain attempts to insert the given header chain in to the local chain, possibly creating a reorg. If an error is returned, it will return the index number of the failing header as well an error describing what went wrong.

The verify parameter can be used to fine tune whether nonce verification should be done or not. The reason behind the optional check is because some of the header retrieval mechanisms already need to verfy nonces, as well as because nonces can be verified sparsely, not needing to check each.

func (*HeaderChain) SetCurrentHeader

func (hc *HeaderChain) SetCurrentHeader(head *types.Header)

SetCurrentHeader sets the current head header of the canonical chain.

func (*HeaderChain) SetGenesis

func (hc *HeaderChain) SetGenesis(head *types.Header)

SetGenesis sets a new genesis block header for the chain

func (*HeaderChain) ValidateHeaderChain

func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error)

func (*HeaderChain) WriteHeader

func (hc *HeaderChain) WriteHeader(header *types.Header) (err error)

WriteHeader writes a header into the local chain, given that its parent is already known.

Note: This method is not concurrent-safe with inserting blocks simultaneously into the chain, as side effects caused by reorganisations cannot be emulated without the real blocks. Hence, writing headers directly should only be done in two scenarios: pure-header mode of operation (light clients), or properly separated header/block phases (non-archive clients).

type MerkleTree

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

MerkleTree represents a Merkle tree

func NewMerkleTree

func NewMerkleTree(hashs [][]byte) *MerkleTree

NewMerkleTree create a merkle tree from the given hash values Note:

if an odd length of hash values passed in, an extra empty hash value (32 bytes) will be used for padding (as the last leaf)

func (MerkleTree) Proof

func (mt MerkleTree) Proof(leafIdx int) [][]byte

Proof returns the hash values for a merkle proof of a leaf Params:

leafIdx: the index of leaf; using the same order with the order of hash values buiding the merkle tree

func (MerkleTree) Verify

func (mt MerkleTree) Verify(leafHash, rootHash []byte, leafIdx int, proof [][]byte) bool

Verify check whether the merkle proof is valid. This method can be used on an empty Merkle Tree, as we have passed all the data needed.

type NewMinedBlockEvent

type NewMinedBlockEvent struct{ Block *types.Block }

NewMinedBlockEvent is posted when a block has been imported.

type NewTxsEvent

type NewTxsEvent struct{ Txs []*types.Transaction }

NewTxsEvent is posted when a batch of transactions enter the transaction pool.

type Operator

type Operator struct {
	Addr common.Address

	TxsCh chan types.Transactions
	// contains filtered or unexported fields
}

Operator a key element in plasma 1. seal a block 2. commit a block hash

func NewOperator

func NewOperator(chain *BlockChain, pool *TxPool, privateKey *ecdsa.PrivateKey, utxoRD UtxoReaderWriter, rootchain *RootChain) *Operator

NewOperator creates a new operator

func (*Operator) AddTxs

func (o *Operator) AddTxs(txs types.Transactions)

func (*Operator) ProcessRemoteBlock

func (o *Operator) ProcessRemoteBlock(block *types.Block)

func (*Operator) ProcessRemoteTxs

func (o *Operator) ProcessRemoteTxs(txs types.Transactions)

func (*Operator) Seal

func (o *Operator) Seal(txs types.Transactions) error

Seal get txs from txpool and construct block, then seal the block Non-Deposit block will not be broadcasted to p2p network immediately, instead we need to wait for `BlockSubmittedEvent` and `completeBlockSubmit`

func (*Operator) SealDeposit

func (o *Operator) SealDeposit(depositBlockNum *big.Int, tx *types.Transaction) error

SealDeposit get txs from txpool and construct block, then seal the block

func (*Operator) SetOperbase

func (o *Operator) SetOperbase(operbase common.Address)

SetOperbase changes operator's current address

func (*Operator) Start

func (o *Operator) Start()

Start the operator to do mining

func (*Operator) Stop

func (o *Operator) Stop()

Stop sends a sigal to stop the operator

func (*Operator) SubmitBlock

func (o *Operator) SubmitBlock(block *types.Block) error

SubmitBlock write block hash to root chain

func (*Operator) SubscribeNewBlockCh

func (o *Operator) SubscribeNewBlockCh(ch chan *types.Block)

func (*Operator) WriteBlock

func (o *Operator) WriteBlock(block *types.Block) error

type Processor

type Processor interface {
	Process(block *types.Block) (uint64, error)
}

Processor is an interface for processing blocks using a given initial state.

Process takes the block to be processed and the statedb upon which the initial state is based. It should return the receipts generated, amount of gas used in the process and return an error if any of the internal rules failed.

type RootChain

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

func NewRootChain

func NewRootChain(url string, abiStr string, cxAddr string, chainDb store.Database) (*RootChain, error)

chain

func (*RootChain) GetCurrentChildBlock

func (rc *RootChain) GetCurrentChildBlock() (*big.Int, error)

func (*RootChain) GetCurrentDepositBlock

func (rc *RootChain) GetCurrentDepositBlock() (*big.Int, error)

func (*RootChain) GetFromBlock

func (rc *RootChain) GetFromBlock() (*big.Int, error)

GetFromBlock get fromBlock from db. if not exist, get it from config.

func (*RootChain) GetOperatorAddress

func (rc *RootChain) GetOperatorAddress() (common.Address, error)

func (*RootChain) GetRootChainBlockByBlockNum

func (rc *RootChain) GetRootChainBlockByBlockNum(blockNum int64) ([32]byte, error)

func (*RootChain) PubKeyToAddress

func (rc *RootChain) PubKeyToAddress(privateKey *ecdsa.PrivateKey) []byte

func (*RootChain) PutFromBlock

func (rc *RootChain) PutFromBlock(fromBlock *big.Int) error

PutFromBlock save fromBlock to db

func (*RootChain) RegisterBlockSubmittedEventHandler

func (rc *RootChain) RegisterBlockSubmittedEventHandler(handler BlockSubmiittedEventHandler)

func (*RootChain) RegisterDepositEventHandler

func (rc *RootChain) RegisterDepositEventHandler(handler DepositEventHandler)

func (*RootChain) SubmitBlock

func (rc *RootChain) SubmitBlock(block *types.Block, privateKey *ecdsa.PrivateKey) error

type TxPool

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

TxPool contains all currently known transactions. Transactions enter the pool when they are received from the network or submitted locally. They exit the pool when they are included in the blockchain.

The pool separates processable transactions (which can be applied to the current state) and future transactions. Transactions move between those two states over time as they are received and processed.

func NewTxPool

func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain BlockReader, validator TxValidator) *TxPool

NewTxPool creates a new transaction pool to gather, sort and filter inbound transactions from the network.

func (*TxPool) AddLocal

func (pool *TxPool) AddLocal(tx *types.Transaction) error

AddLocal enqueues a single transaction into the pool if it is valid, marking the sender as a local one in the mean time, ensuring it goes around the local pricing constraints.

func (*TxPool) AddLocals

func (pool *TxPool) AddLocals(txs []*types.Transaction) []error

AddLocals enqueues a batch of transactions into the pool if they are valid, marking the senders as a local ones in the mean time, ensuring they go around the local pricing constraints.

func (*TxPool) AddRemote

func (pool *TxPool) AddRemote(tx *types.Transaction) error

AddRemote enqueues a single transaction into the pool if it is valid. If the sender is not among the locally tracked ones, full pricing constraints will apply.

func (*TxPool) AddRemotes

func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error

AddRemotes enqueues a batch of transactions into the pool if they are valid. If the senders are not among the locally tracked ones, full pricing constraints will apply.

func (*TxPool) Content

func (pool *TxPool) Content() types.Transactions

Content retrieves the data content of the transaction pool, returning all queued transactions

func (*TxPool) Get

func (pool *TxPool) Get(hash common.Hash) *types.Transaction

Get returns a transaction if it is contained in the pool and nil otherwise.

func (*TxPool) Stats

func (pool *TxPool) Stats() int

Stats retrieves the current pool stats, namely the number of queued

func (*TxPool) Stop

func (pool *TxPool) Stop()

Stop terminates the transaction pool.

func (*TxPool) SubscribeNewTxsCh

func (pool *TxPool) SubscribeNewTxsCh(ch chan types.Transactions)

func (*TxPool) SubscribeNewTxsEvent

func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription

SubscribeNewTxsEvent registers a subscription of NewTxsEvent and starts sending event to the given channel.

type TxPoolConfig

type TxPoolConfig struct {
	NoLocals  bool          // Whether local transaction handling should be disabled
	Journal   string        // Journal of local transactions to survive node restarts
	Rejournal time.Duration // Time interval to regenerate the local transaction journal

	PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
	PriceBump  uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)

	AccountSlots uint64 // Number of executable transaction slots guaranteed per account
	GlobalSlots  uint64 // Maximum number of executable transaction slots for all accounts
	AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
	GlobalQueue  uint64 // Maximum number of non-executable transaction slots for all accounts

	Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
}

TxPoolConfig are the configuration parameters of the transaction pool.

type TxValidator

type TxValidator interface {
	Validate(tx *types.Transaction) error
}

TxValidator is an interface which defines the standard for transaction validation

type UTXOSet

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

UTXOSet is a utxo manager, which implements interface UtxoReaderWriter

func NewUTXOSet

func NewUTXOSet(db store.Database) *UTXOSet

NewUTXOSet connects utxoset to db

func (*UTXOSet) Del

func (us *UTXOSet) Del(id types.UTXOID) error

Del remove a utxo from db

func (*UTXOSet) Get

func (us *UTXOSet) Get(id types.UTXOID) *types.UTXO

Get finds a utxo by id nil, if not found

func (*UTXOSet) Put

func (us *UTXOSet) Put(v *types.UTXO) error

Put saves a utxo into db

type UtxoBlockValidator

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

UtxoBlockValidator is responsible for validating block / UtxoBlockValidator implements BlockValidator.

func NewUtxoBlockValidator

func NewUtxoBlockValidator(s types.Signer, br BlockReader, ur UtxoReader) *UtxoBlockValidator

NewUtxoBlockValidator returns a new block validator which is safe for re-use

func (*UtxoBlockValidator) ValidateBody

func (v *UtxoBlockValidator) ValidateBody(block *types.Block) error

ValidateBody validates the given block's uncles and verifies the the block header's transaction. The headers are assumed to be already validated at this point.

type UtxoReader

type UtxoReader interface {
	Get(id types.UTXOID) *types.UTXO
}

UtxoReader defines an interface to read utxo set data

type UtxoReaderWriter

type UtxoReaderWriter interface {
	UtxoReader
	UtxoWriter
}

UtxoReaderWriter combines both UtxoReader and UtxoDeleter interfaces

type UtxoTxValidator

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

UtxoTxValidator is a validator for transaction including utxo inputs

func NewUtxoTxValidator

func NewUtxoTxValidator(signer types.Signer, ur UtxoReader) *UtxoTxValidator

NewUtxoTxValidator creates a new TxValidator

func (*UtxoTxValidator) Validate

func (v *UtxoTxValidator) Validate(tx *types.Transaction) error

Validate checks whether a transaction is valid according to the consensus rules and adheres to some heuristic limits of the local node (price and size).

type UtxoWriter

type UtxoWriter interface {
	Del(id types.UTXOID) error
	Put(v *types.UTXO) error
}

UtxoWriter defines an interface to delete utxo

type Validator

type Validator struct {
	NewTxsCh chan types.Transactions
	// contains filtered or unexported fields
}

Operator a key element in plasma 1. seal a block 2. commit a block hash

func NewValidator

func NewValidator(chain *BlockChain, utxoRD UtxoReaderWriter, rootchain *RootChain) *Validator

NewOperator creates a new operator

func (*Validator) ProcessRemoteBlock

func (v *Validator) ProcessRemoteBlock(block *types.Block)

ProcessRemoteBlock write block to chain cache the block if block is not sequential

func (*Validator) ProcessRemoteTxs

func (v *Validator) ProcessRemoteTxs(txs types.Transactions)

func (*Validator) Start

func (v *Validator) Start()

Start the operator to do mining

func (*Validator) SubscribeNewBlockCh

func (v *Validator) SubscribeNewBlockCh(ch chan *types.Block)

func (*Validator) WriteBlock

func (v *Validator) WriteBlock(block *types.Block) error

type WhCallback

type WhCallback func(*types.Header) error

WhCallback is a callback function for inserting individual headers. A callback is used for two reasons: first, in a LightChain, status should be processed and light chain events sent, while in a BlockChain this is not necessary since chain events are sent after inserting blocks. Second, the header writes should be protected by the parent chain mutex individually.

Directories

Path Synopsis
Package rawdb contains a collection of low level database accessors.
Package rawdb contains a collection of low level database accessors.

Jump to

Keyboard shortcuts

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