core

package
v0.12.10-wip-bloom-met... Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: GPL-3.0, LGPL-3.0 Imports: 46 Imported by: 52

README

Core Package

The core package maintains the backend for the blockchain, transaction pool, and maintains the required indexes for blocks, transactions, logs, and transaction receipts.

Blockchain

The BlockChain struct handles the insertion of blocks into the maintained chain. It maintains a "canonical chain", which is essentially the preferred chain (the chain that ends with the block preferred by the AvalancheGo consensus engine).

When the consensus engine verifies blocks as they are ready to be issued into consensus, it calls Verify() on the ChainVM Block interface implemented here. This calls InsertBlockManual on the BlockChain struct implemented in this package, which is the first entrypoint of a block into the blockchain.

InsertBlockManual verifies the block, inserts it into the state manager to track the merkle trie for the block, and adds it to the canonical chain if it extends the currently preferred chain.

Coreth adds functions for Accept and Reject, which take care of marking a block as finalized and performing garbage collection where possible.

The consensus engine can also call SetPreference on a VM to tell the VM that a specific block is preferred by the consensus engine to be accepted. This triggers a call to reorg the blockchain and set the newly preferred block as the preferred chain.

Transaction Pool

The transaction pool maintains the set of transactions that need to be issued into a new block. The VM exposes APIs that allow clients to issue transactions into the transaction pool and also performs gossip across the network in order to send and receive pending transactions that need to be issued into a new block. The transaction pool asynchronously follows the preferred block of the BlockChain struct by subscribing to new head events and updating its state accordingly. When the transaction pool updates, it ensures that any transactions it contains are still valid to be issued on top of the new preferred block.

State Manager

The State Manager manages the TrieDB. The TrieDB tracks a merkle forest of all of the merkle tries for the last accepted block and processing blocks. When a block is processed, the state transition results in a new merkle trie added to the merkle forest. The State Manager can operate in either archival or pruning mode.

Archival Mode

In archival mode, every merkle trie is written to disk so that the node maintains a complete history of all the blocks that it has processed.

Pruning Mode

In pruning mode, the State Manager keeps a reference to merkle tries of processing blocks. When a block gets accepted, it stays in memory. When a block gets rejected, the state manager can dereference and clean up the no longer needed merkle trie. The State Manager does not immediately write the merkle trie to disk of a block when it gets accepted. Instead, at a regular interval (~4096 blocks) it writes the merkle trie to disk, so that it does not add the overhead of storing every accepted block's merkle trie to disk.

Documentation

Overview

Package core implements the Ethereum consensus protocol.

Package core implements the Ethereum consensus protocol.

Index

Examples

Constants

View Source
const (

	// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
	//
	// Changelog:
	//
	// - Version 4
	//   The following incompatible database changes were added:
	//   * the `BlockNumber`, `TxHash`, `TxIndex`, `BlockHash` and `Index` fields of log are deleted
	//   * the `Bloom` field of receipt is deleted
	//   * the `BlockIndex` and `TxIndex` fields of txlookup are deleted
	// - Version 5
	//  The following incompatible database changes were added:
	//    * the `TxHash`, `GasCost`, and `ContractAddress` fields are no longer stored for a receipt
	//    * the `TxHash`, `GasCost`, and `ContractAddress` fields are computed by looking up the
	//      receipts' corresponding block
	// - Version 6
	//  The following incompatible database changes were added:
	//    * Transaction lookup information stores the corresponding block number instead of block hash
	// - Version 7
	//  The following incompatible database changes were added:
	//    * Use freezer as the ancient database to maintain all ancient data
	// - Version 8
	//  The following incompatible database changes were added:
	//    * New scheme for contract code in order to separate the codes and trie nodes
	BlockChainVersion uint64 = 8
)

Variables

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

	// ErrNoGenesis is returned when there is no Genesis Block.
	ErrNoGenesis = errors.New("genesis not found in chain")
)
View Source
var (
	// ErrNonceTooLow is returned if the nonce of a transaction is lower than the
	// one present in the local chain.
	ErrNonceTooLow = errors.New("nonce too low")

	// 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")

	// ErrNonceMax is returned if the nonce of a transaction sender account has
	// maximum allowed value and would become invalid if incremented.
	ErrNonceMax = errors.New("nonce has max value")

	// ErrGasLimitReached is returned by the gas pool if the amount of gas required
	// by a transaction is higher than what's left in the block.
	ErrGasLimitReached = errors.New("gas limit reached")

	// ErrInsufficientFundsForTransfer is returned if the transaction sender doesn't
	// have enough funds for transfer(topmost call only).
	ErrInsufficientFundsForTransfer = errors.New("insufficient funds for transfer")

	// ErrMaxInitCodeSizeExceeded is returned if creation transaction provides the init code bigger
	// than init code size limit.
	ErrMaxInitCodeSizeExceeded = errors.New("max initcode size exceeded")

	// ErrInsufficientFunds is returned if the total cost of executing a transaction
	// is higher than the balance of the user's account.
	ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")

	// ErrGasUintOverflow is returned when calculating gas usage.
	ErrGasUintOverflow = errors.New("gas uint64 overflow")

	// ErrIntrinsicGas is returned if the transaction is specified to use less gas
	// than required to start the invocation.
	ErrIntrinsicGas = errors.New("intrinsic gas too low")

	// ErrTxTypeNotSupported is returned if a transaction is not supported in the
	// current network configuration.
	ErrTxTypeNotSupported = types.ErrTxTypeNotSupported

	// ErrTipAboveFeeCap is a sanity error to ensure no one is able to specify a
	// transaction with a tip higher than the total fee cap.
	ErrTipAboveFeeCap = errors.New("max priority fee per gas higher than max fee per gas")

	// ErrTipVeryHigh is a sanity error to avoid extremely big numbers specified
	// in the tip field.
	ErrTipVeryHigh = errors.New("max priority fee per gas higher than 2^256-1")

	// ErrFeeCapVeryHigh is a sanity error to avoid extremely big numbers specified
	// in the fee cap field.
	ErrFeeCapVeryHigh = errors.New("max fee per gas higher than 2^256-1")

	// ErrFeeCapTooLow is returned if the transaction fee cap is less than the
	// base fee of the block.
	ErrFeeCapTooLow = errors.New("max fee per gas less than block base fee")

	// ErrSenderNoEOA is returned if the sender of a transaction is a contract.
	ErrSenderNoEOA = errors.New("sender not an eoa")
)

List of evm-call-message pre-checking errors. All state transition messages will be pre-checked before execution. If any invalidation detected, the corresponding error should be returned which is defined here.

- If the pre-checking happens in the miner, then the transaction won't be packed. - If the pre-checking happens in the block processing procedure, then a "BAD BLOCk" error should be emitted.

View Source
var DefaultCacheConfig = &CacheConfig{
	TrieCleanLimit:            256,
	TrieDirtyLimit:            256,
	TrieDirtyCommitTarget:     20,
	TriePrefetcherParallelism: 16,
	Pruning:                   true,
	CommitInterval:            4096,
	AcceptorQueueLimit:        64,
	SnapshotLimit:             256,
	AcceptedCacheSize:         32,
}
View Source
var ErrMissingPredicateContext = errors.New("missing predicate context")
View Source
var (
	ErrRefuseToCorruptArchiver = errors.New("node has operated with pruning disabled, shutting down to prevent missing tries")
)
View Source
var TestCallbacks = dummy.ConsensusCallbacks{
	OnExtraStateChange: func(block *types.Block, sdb *state.StateDB) (*big.Int, *big.Int, error) {
		sdb.SetBalanceMultiCoin(common.HexToAddress("0xdeadbeef"), common.HexToHash("0xdeadbeef"), big.NewInt(block.Number().Int64()))
		return nil, nil, nil
	},
	OnFinalizeAndAssemble: func(header *types.Header, sdb *state.StateDB, txs []*types.Transaction) ([]byte, *big.Int, *big.Int, error) {
		sdb.SetBalanceMultiCoin(common.HexToAddress("0xdeadbeef"), common.HexToHash("0xdeadbeef"), big.NewInt(header.Number.Int64()))
		return nil, nil, nil, nil
	},
}

Functions

func ApplyPrecompileActivations added in v0.12.10

func ApplyPrecompileActivations(c *params.ChainConfig, parentTimestamp *uint64, blockContext contract.ConfigurationBlockContext, statedb *state.StateDB) error

ApplyPrecompileActivations checks if any of the precompiles specified by the chain config are enabled or disabled by the block transition from [parentTimestamp] to the timestamp set in [blockContext]. If this is the case, it calls [Configure] to apply the necessary state transitions for the upgrade. This function is called within genesis setup to configure the starting state for precompiles enabled at genesis. In block processing and building, ApplyUpgrades is called instead which also applies state upgrades.

func ApplyTransaction

func ApplyTransaction(config *params.ChainConfig, bc ChainContext, blockContext vm.BlockContext, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, error)

ApplyTransaction attempts to apply a transaction to the given state database and uses the input parameters for its environment. It returns the receipt for the transaction, gas used and an error if the transaction failed, indicating the block was invalid.

func ApplyUpgrades added in v0.12.10

func ApplyUpgrades(c *params.ChainConfig, parentTimestamp *uint64, blockContext contract.ConfigurationBlockContext, statedb *state.StateDB) error

ApplyUpgrades checks if any of the precompile or state upgrades specified by the chain config are activated by the block transition from [parentTimestamp] to the timestamp set in [header]. If this is the case, it calls [Configure] to apply the necessary state transitions for the upgrade. This function is called: - in block processing to update the state when processing a block. - in the miner to apply the state upgrades when producing a block.

func CalcGasLimit

func CalcGasLimit(parentGasUsed, parentGasLimit, gasFloor, gasCeil uint64) uint64

CalcGasLimit computes the gas limit of the next block after parent. It aims to keep the baseline gas above the provided floor, and increase it towards the ceil if the blocks are full. If the ceil is exceeded, it will always decrease the gas allowance.

func CanTransfer

func CanTransfer(db vm.StateDB, addr common.Address, amount *big.Int) bool

CanTransfer checks whether there are enough funds in the address' account to make a transfer. This does not take the necessary gas in to account to make the transfer valid.

func CanTransferMC added in v0.2.9

func CanTransferMC(db vm.StateDB, addr common.Address, to common.Address, coinID common.Hash, amount *big.Int) bool

func CheckPredicates added in v0.12.10

func CheckPredicates(rules params.Rules, predicateContext *precompileconfig.PredicateContext, tx *types.Transaction) (map[common.Address][]byte, error)

CheckPredicates verifies the predicates of [tx] and returns the result. Returning an error invalidates the block.

func GenerateChain added in v0.5.0

func GenerateChain(config *params.ChainConfig, parent *types.Block, engine consensus.Engine, db ethdb.Database, n int, gap uint64, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts, error)

GenerateChain creates a chain of n blocks. The first block's parent will be the provided parent. db is used to store intermediate states and should contain the parent's state trie.

The generator function is called with a new block generator for every block. Any transactions and uncles added to the generator become part of the block. If gen is nil, the blocks will be empty and their coinbase will be the zero address.

Blocks created by GenerateChain do not contain valid proof of work values. Inserting them into BlockChain requires use of FakePow or a similar non-validating proof of work implementation.

Example
var (
	key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
	key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a")
	key3, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")
	addr1   = crypto.PubkeyToAddress(key1.PublicKey)
	addr2   = crypto.PubkeyToAddress(key2.PublicKey)
	addr3   = crypto.PubkeyToAddress(key3.PublicKey)
	db      = rawdb.NewMemoryDatabase()
)

// Ensure that key1 has some funds in the genesis block.
gspec := &Genesis{
	Config: &params.ChainConfig{HomesteadBlock: new(big.Int)},
	Alloc:  GenesisAlloc{addr1: {Balance: big.NewInt(1000000)}},
}

// This call generates a chain of 3 blocks. The function runs for
// each block and adds different features to gen based on the
// block index.
signer := types.HomesteadSigner{}
_, chain, _, err := GenerateChainWithGenesis(gspec, dummy.NewFaker(), 3, 10, func(i int, gen *BlockGen) {
	switch i {
	case 0:
		// In block 1, addr1 sends addr2 some ether.
		tx, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(10000), params.TxGas, nil, nil), signer, key1)
		gen.AddTx(tx)
	case 1:
		// In block 2, addr1 sends some more ether to addr2.
		// addr2 passes it on to addr3.
		tx1, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr1), addr2, big.NewInt(1000), params.TxGas, nil, nil), signer, key1)
		gen.AddTx(tx1)
	case 2:
		tx2, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
		gen.AddTx(tx2)
	}
})
if err != nil {
	panic(err)
}

// Import the chain. This runs all block validation rules.
blockchain, _ := NewBlockChain(db, DefaultCacheConfig, gspec, dummy.NewFaker(), vm.Config{}, common.Hash{}, false)
defer blockchain.Stop()

if i, err := blockchain.InsertChain(chain); err != nil {
	fmt.Printf("insert error (block %d): %v\n", chain[i].NumberU64(), err)
	return
}

state, _ := blockchain.State()
fmt.Printf("last block: #%d\n", blockchain.CurrentBlock().Number)
fmt.Println("balance of addr1:", state.GetBalance(addr1))
fmt.Println("balance of addr2:", state.GetBalance(addr2))
fmt.Println("balance of addr3:", state.GetBalance(addr3))
// Expected output has been modified since uncle blocks and block rewards have
// been removed from the original test.
Output:

last block: #3
balance of addr1: 989000
balance of addr2: 10000
balance of addr3: 1000

func GenerateChainWithGenesis added in v0.12.0

func GenerateChainWithGenesis(genesis *Genesis, engine consensus.Engine, n int, gap uint64, gen func(int, *BlockGen)) (ethdb.Database, []*types.Block, []types.Receipts, error)

GenerateChainWithGenesis is a wrapper of GenerateChain which will initialize genesis block to database first according to the provided genesis specification then generate chain on top.

func GenesisBlockForTesting added in v0.2.9

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

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

func GetHashFn

func GetHashFn(ref *types.Header, chain ChainContext) func(n uint64) common.Hash

GetHashFn returns a GetHashFunc which retrieves header hashes by number

func IntrinsicGas

func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation bool, rules params.Rules) (uint64, error)

IntrinsicGas computes the 'intrinsic gas' for a message with the given data.

func NewEVMBlockContext added in v0.5.0

func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common.Address) vm.BlockContext

NewEVMBlockContext creates a new context for use in the EVM.

func NewEVMBlockContextWithPredicateResults added in v0.12.10

func NewEVMBlockContextWithPredicateResults(header *types.Header, chain ChainContext, author *common.Address, predicateResults *predicate.Results) vm.BlockContext

NewEVMBlockContextWithPredicateResults creates a new context for use in the EVM with an override for the predicate results that is not present in header.Extra. This function is used to create a BlockContext when the header Extra data is not fully formed yet and it's more efficient to pass in predicateResults directly rather than re-encode the latest results when executing each individaul transaction.

func NewEVMTxContext added in v0.5.0

func NewEVMTxContext(msg *Message) vm.TxContext

NewEVMTxContext creates a new transaction context for a single transaction.

func ReadBlockByHash added in v0.11.0

func ReadBlockByHash(db ethdb.Reader, hash common.Hash) *types.Block

ReadBlockByHash reads the block with the given hash from the database.

func SetupGenesisBlock

func SetupGenesisBlock(
	db ethdb.Database, triedb *trie.Database, genesis *Genesis, lastAcceptedHash common.Hash, skipChainConfigCheckCompatible bool,
) (*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.

func TestAcceptBlockIdenticalStateRoot added in v0.5.6

func TestAcceptBlockIdenticalStateRoot(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

Insert two different chains that result in the identical state root. Once we accept one of the chains, we insert and accept A3 on top of the shared state root

  G   (genesis)
 / \
A1  B1
|   |
A2  B2 (A2 and B2 represent two different paths to the identical state trie)
|
A3

func TestAcceptNonCanonicalBlock added in v0.5.4

func TestAcceptNonCanonicalBlock(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestBuildOnVariousStages added in v0.5.4

func TestBuildOnVariousStages(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestEmptyBlocks added in v0.5.4

func TestEmptyBlocks(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestGenerateChainInvalidBlockFee added in v0.7.0

func TestGenerateChainInvalidBlockFee(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestInsertChainAcceptSingleBlock added in v0.5.4

func TestInsertChainAcceptSingleBlock(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestInsertChainInvalidBlockFee added in v0.7.0

func TestInsertChainInvalidBlockFee(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestInsertChainValidBlockFee added in v0.7.0

func TestInsertChainValidBlockFee(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestInsertLongForkedChain added in v0.5.4

func TestInsertLongForkedChain(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestReorgReInsert added in v0.5.4

func TestReorgReInsert(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func TestReprocessAcceptBlockIdenticalStateRoot added in v0.5.6

func TestReprocessAcceptBlockIdenticalStateRoot(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

Insert two different chains that result in the identical state root. Once we insert both of the chains, we restart, insert both the chains again, and then we accept one of the chains and accept A3 on top of the shared state root

  G   (genesis)
 / \
A1  B1
|   |
A2  B2 (A2 and B2 represent two different paths to the identical state trie)
|
A3

func TestSetPreferenceRewind added in v0.5.4

func TestSetPreferenceRewind(t *testing.T, create func(db ethdb.Database, gspec *Genesis, lastAcceptedHash common.Hash) (*BlockChain, error))

func Transfer

func Transfer(db vm.StateDB, sender, recipient common.Address, amount *big.Int)

Transfer subtracts amount from sender and adds amount to recipient using the given Db

func TransferMultiCoin added in v0.2.9

func TransferMultiCoin(db vm.StateDB, sender, recipient common.Address, coinID common.Hash, amount *big.Int)

Transfer subtracts amount from sender and adds amount to recipient using the given Db

Types

type BadBlockReason added in v0.10.0

type BadBlockReason struct {
	ChainConfig *params.ChainConfig `json:"chainConfig"`
	Receipts    types.Receipts      `json:"receipts"`
	Number      uint64              `json:"number"`
	Hash        common.Hash         `json:"hash"`
	Error       string              `json:"error"`
}

func (*BadBlockReason) String added in v0.10.0

func (b *BadBlockReason) String() string

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 ethdb.Database, cacheConfig *CacheConfig, genesis *Genesis, engine consensus.Engine,
	vmConfig vm.Config, lastAcceptedHash common.Hash, skipChainConfigCheckCompatible bool,
) (*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) Accept added in v0.3.25

func (bc *BlockChain) Accept(block *types.Block) error

Accept sets a minimum height at which no reorg can pass. Additionally, this function may trigger a reorg if the block being accepted is not in the canonical chain.

Assumes [bc.chainmu] is not held by the caller.

func (*BlockChain) BadBlocks

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

BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network and the BadBlockReason that caused each to be reported as a bad block. BadBlocks ensures that the length of the blocks and the BadBlockReason slice have the same length.

func (*BlockChain) CacheConfig added in v0.12.10

func (bc *BlockChain) CacheConfig() *CacheConfig

CacheConfig returns a reference to [bc.cacheConfig]

This is used by [miner] to set prefetch parallelism during block building.

func (*BlockChain) CleanBlockRootsAboveLastAccepted added in v0.8.5

func (bc *BlockChain) CleanBlockRootsAboveLastAccepted() error

CleanBlockRootsAboveLastAccepted gathers the blocks that may have previously been in processing above the last accepted block and wipes their block roots from disk to mark their tries as inaccessible. This is used prior to pruning to ensure that all of the tries that may still be in processing are marked as inaccessible and mirrors the handling of middle roots in the geth offline pruning implementation. This is not strictly necessary, but maintains a soft assumption.

func (*BlockChain) Config

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

Config retrieves the chain's fork configuration.

func (*BlockChain) CurrentBlock

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

CurrentBlock retrieves the current 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) DrainAcceptorQueue added in v0.8.11

func (bc *BlockChain) DrainAcceptorQueue()

DrainAcceptorQueue blocks until all items in [acceptorQueue] have been processed.

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

func (bc *BlockChain) ExportCallback(callback func(block *types.Block) error, first uint64, last uint64) error

ExportCallback invokes [callback] for every block from [first] to [last] in order.

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) GasLimit

func (bc *BlockChain) GasLimit() uint64

GasLimit returns the gas limit of the current HEAD block.

func (*BlockChain) Genesis

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

Genesis retrieves the chain's genesis block.

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

func (bc *BlockChain) GetCanonicalHash(number uint64) common.Hash

GetCanonicalHash returns the canonical hash for a given block number

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

func (bc *BlockChain) GetLogs(hash common.Hash, number uint64) [][]*types.Log

GetLogs fetches all logs from a given block.

func (*BlockChain) GetReceiptsByHash

func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts

GetReceiptsByHash retrieves the receipts for all transactions in a given block.

func (*BlockChain) GetTransactionLookup

func (bc *BlockChain) GetTransactionLookup(hash common.Hash) *rawdb.LegacyTxLookupEntry

GetTransactionLookup retrieves the lookup associate with the given transaction hash from the cache or database.

func (*BlockChain) GetVMConfig

func (bc *BlockChain) GetVMConfig() *vm.Config

GetVMConfig returns the block chain VM config.

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.

func (*BlockChain) HasBlockAndState

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

HasBlockAndState checks if a block and associated state trie is fully present in the database or not, caching it if present.

func (*BlockChain) HasFastBlock

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

HasFastBlock checks if a fast block is fully present in the database or not.

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) HasState

func (bc *BlockChain) HasState(hash common.Hash) bool

HasState checks if state trie is fully present in the database or not.

func (*BlockChain) InitializeSnapshots added in v0.8.10

func (bc *BlockChain) InitializeSnapshots()

func (*BlockChain) InsertBlock added in v0.5.4

func (bc *BlockChain) InsertBlock(block *types.Block) error

func (*BlockChain) InsertBlockManual added in v0.5.6

func (bc *BlockChain) InsertBlockManual(block *types.Block, writes bool) error

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

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

LastAcceptedBlock returns the last block to be marked as accepted and is processed.

Note: During initialization, [acceptorTip] is equal to [lastAccepted].

func (*BlockChain) LastConsensusAcceptedBlock added in v0.8.11

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

LastAcceptedBlock returns the last block to be marked as accepted. It may or may not yet be processed.

func (*BlockChain) Processor

func (bc *BlockChain) Processor() Processor

Processor returns the current processor.

func (*BlockChain) Reject added in v0.5.4

func (bc *BlockChain) Reject(block *types.Block) error

func (*BlockChain) RemoveRejectedBlocks added in v0.5.4

func (bc *BlockChain) RemoveRejectedBlocks(start, end uint64) error

func (*BlockChain) ResetToStateSyncedBlock added in v0.11.1

func (bc *BlockChain) ResetToStateSyncedBlock(block *types.Block) error

ResetToStateSyncedBlock reinitializes the state of the blockchain to the trie represented by [block.Root()] after updating in-memory and on disk current block pointers to [block]. Only should be called after state sync has completed.

func (*BlockChain) SenderCacher added in v0.7.0

func (bc *BlockChain) SenderCacher() *TxSenderCacher

SenderCacher returns the *TxSenderCacher used within the core package.

func (*BlockChain) SetPreference added in v0.3.25

func (bc *BlockChain) SetPreference(block *types.Block) error

SetPreference attempts to update the head block to be the provided block and emits a ChainHeadEvent if successful. This function will handle all reorg side effects, if necessary.

Note: This function should ONLY be called on blocks that have already been inserted into the chain.

Assumes [bc.chainmu] is not held by the caller.

func (*BlockChain) Snapshots added in v0.5.0

func (bc *BlockChain) Snapshots() *snapshot.Tree

Snapshots returns the blockchain snapshot tree.

func (*BlockChain) State

func (bc *BlockChain) State() (*state.StateDB, error)

State returns a new mutable state based on the current HEAD block.

func (*BlockChain) StateAt

func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error)

StateAt returns a new mutable state based on a particular point in time.

func (*BlockChain) StateCache

func (bc *BlockChain) StateCache() state.Database

StateCache returns the caching database underpinning the blockchain instance.

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

func (bc *BlockChain) SubscribeAcceptedLogsEvent(ch chan<- []*types.Log) event.Subscription

SubscribeAcceptedLogsEvent registers a subscription of accepted []*types.Log.

func (*BlockChain) SubscribeAcceptedTransactionEvent added in v0.5.0

func (bc *BlockChain) SubscribeAcceptedTransactionEvent(ch chan<- NewTxsEvent) event.Subscription

SubscribeAcceptedTransactionEvent registers a subscription of accepted transactions

func (*BlockChain) SubscribeBlockProcessingEvent

func (bc *BlockChain) SubscribeBlockProcessingEvent(ch chan<- bool) event.Subscription

SubscribeBlockProcessingEvent registers a subscription of bool where true means block processing has started while false means it has stopped.

func (*BlockChain) SubscribeChainAcceptedEvent added in v0.4.2

func (bc *BlockChain) SubscribeChainAcceptedEvent(ch chan<- ChainEvent) event.Subscription

SubscribeChainAcceptedEvent registers a subscription of ChainEvent.

func (*BlockChain) SubscribeChainEvent

func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription

SubscribeChainEvent registers a subscription of ChainEvent.

func (*BlockChain) SubscribeChainHeadEvent

func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription

SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.

func (*BlockChain) SubscribeChainSideEvent

func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription

SubscribeChainSideEvent registers a subscription of ChainSideEvent.

func (*BlockChain) SubscribeLogsEvent

func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription

SubscribeLogsEvent registers a subscription of []*types.Log.

func (*BlockChain) SubscribeRemovedLogsEvent

func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription

SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.

func (*BlockChain) TrieDB added in v0.12.3

func (bc *BlockChain) TrieDB() *trie.Database

TrieDB retrieves the low level trie database used for data storage.

func (*BlockChain) TrieNode

func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error)

TrieNode retrieves a blob of data associated with a trie node either from ephemeral in-memory cache, or from persistent storage.

func (*BlockChain) ValidateCanonicalChain added in v0.3.20

func (bc *BlockChain) ValidateCanonicalChain() error

ValidateCanonicalChain confirms a canonical chain is well-formed.

func (*BlockChain) Validator

func (bc *BlockChain) Validator() Validator

Validator returns the current validator.

type BlockGen added in v0.5.0

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

BlockGen creates blocks for testing. See GenerateChain for a detailed explanation.

func (*BlockGen) AddTx added in v0.5.0

func (b *BlockGen) AddTx(tx *types.Transaction)

AddTx adds a transaction to the generated block. If no coinbase has been set, the block's coinbase is set to the zero address.

AddTx panics if the transaction cannot be executed. In addition to the protocol-imposed limitations (gas limit, etc.), there are some further limitations on the content of transactions that can be added. Notably, contract code relying on the BLOCKHASH instruction will panic during execution.

func (*BlockGen) AddTxWithChain added in v0.5.0

func (b *BlockGen) AddTxWithChain(bc *BlockChain, tx *types.Transaction)

AddTxWithChain adds a transaction to the generated block. If no coinbase has been set, the block's coinbase is set to the zero address.

AddTxWithChain panics if the transaction cannot be executed. In addition to the protocol-imposed limitations (gas limit, etc.), there are some further limitations on the content of transactions that can be added. If contract code relies on the BLOCKHASH instruction, the block in chain will be returned.

func (*BlockGen) AddTxWithVMConfig added in v0.12.3

func (b *BlockGen) AddTxWithVMConfig(tx *types.Transaction, config vm.Config)

AddTxWithVMConfig adds a transaction to the generated block. If no coinbase has been set, the block's coinbase is set to the zero address. The evm interpreter can be customized with the provided vm config.

func (*BlockGen) AddUncheckedReceipt added in v0.5.0

func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt)

AddUncheckedReceipt forcefully adds a receipts to the block without a backing transaction.

AddUncheckedReceipt will cause consensus failures when used during real chain processing. This is best used in conjunction with raw block insertion.

func (*BlockGen) AddUncheckedTx added in v0.5.0

func (b *BlockGen) AddUncheckedTx(tx *types.Transaction)

AddUncheckedTx forcefully adds a transaction to the block without any validation.

AddUncheckedTx will cause consensus failures when used during real chain processing. This is best used in conjunction with raw block insertion.

func (*BlockGen) AddUncle added in v0.5.0

func (b *BlockGen) AddUncle(h *types.Header)

AddUncle adds an uncle header to the generated block.

func (*BlockGen) AppendExtra added in v0.12.10

func (b *BlockGen) AppendExtra(data []byte)

AppendExtra appends data to the extra data field of the generated block.

func (*BlockGen) BaseFee added in v0.6.0

func (b *BlockGen) BaseFee() *big.Int

BaseFee returns the EIP-1559 base fee of the block being generated.

func (*BlockGen) GetBalance added in v0.5.0

func (b *BlockGen) GetBalance(addr common.Address) *big.Int

GetBalance returns the balance of the given address at the generated block.

func (*BlockGen) Number added in v0.5.0

func (b *BlockGen) Number() *big.Int

Number returns the block number of the block being generated.

func (*BlockGen) OffsetTime added in v0.5.0

func (b *BlockGen) OffsetTime(seconds int64)

OffsetTime modifies the time instance of a block, implicitly changing its associated difficulty. It's useful to test scenarios where forking is not tied to chain length directly.

func (*BlockGen) PrevBlock added in v0.5.0

func (b *BlockGen) PrevBlock(index int) *types.Block

PrevBlock returns a previously generated block by number. It panics if num is greater or equal to the number of the block being generated. For index -1, PrevBlock returns the parent block given to GenerateChain.

func (*BlockGen) SetCoinbase added in v0.5.0

func (b *BlockGen) SetCoinbase(addr common.Address)

SetCoinbase sets the coinbase of the generated block. It can be called at most once.

func (*BlockGen) SetDifficulty added in v0.5.0

func (b *BlockGen) SetDifficulty(diff *big.Int)

SetDifficulty sets the difficulty field of the generated block. This method is useful for Clique tests where the difficulty does not depend on time. For the ethash tests, please use OffsetTime, which implicitly recalculates the diff.

func (*BlockGen) SetExtra added in v0.5.0

func (b *BlockGen) SetExtra(data []byte)

SetExtra sets the extra data field of the generated block.

func (*BlockGen) SetNonce added in v0.5.0

func (b *BlockGen) SetNonce(nonce types.BlockNonce)

SetNonce sets the nonce field of the generated block.

func (*BlockGen) SetOnBlockGenerated added in v0.8.10

func (b *BlockGen) SetOnBlockGenerated(onBlockGenerated func(*types.Block))

SetOnBlockGenerated sets a callback function to be invoked after each block is generated

func (*BlockGen) Timestamp added in v0.12.3

func (b *BlockGen) Timestamp() uint64

Timestamp returns the timestamp of the block being generated.

func (*BlockGen) TxNonce added in v0.5.0

func (b *BlockGen) TxNonce(addr common.Address) uint64

TxNonce returns the next valid transaction nonce for the account at addr. It panics if the account does not exist.

type BlockValidator

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

BlockValidator is responsible for validating block headers, uncles and processed state.

BlockValidator implements Validator.

func NewBlockValidator

func NewBlockValidator(config *params.ChainConfig, blockchain *BlockChain, engine consensus.Engine) *BlockValidator

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

func (*BlockValidator) ValidateBody

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

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

func (*BlockValidator) ValidateState

func (v *BlockValidator) ValidateState(block *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error

ValidateState validates the various changes that happen after a state transition, such as amount of used gas, the receipt roots and the state root itself.

type BloomIndexer added in v0.5.0

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

BloomIndexer implements a core.ChainIndexer, building up a rotated bloom bits index for the Ethereum header bloom filters, permitting blazing fast filtering.

func (*BloomIndexer) Commit added in v0.5.0

func (b *BloomIndexer) Commit() error

Commit implements core.ChainIndexerBackend, finalizing the bloom section and writing it out into the database.

func (*BloomIndexer) Process added in v0.5.0

func (b *BloomIndexer) Process(ctx context.Context, header *types.Header) error

Process implements core.ChainIndexerBackend, adding a new header's bloom into the index.

func (*BloomIndexer) Prune added in v0.5.0

func (b *BloomIndexer) Prune(threshold uint64) error

Prune returns an empty error since we don't support pruning here.

func (*BloomIndexer) Reset added in v0.5.0

func (b *BloomIndexer) Reset(ctx context.Context, section uint64, lastSectionHead common.Hash) error

Reset implements core.ChainIndexerBackend, starting a new bloombits index section.

type BoundedBuffer added in v0.8.11

type BoundedBuffer[K any] struct {
	// contains filtered or unexported fields
}

BoundedBuffer keeps [size] entries of type [K] in a buffer and calls [callback] on any item that is overwritten. This is typically used for dereferencing old roots during block processing.

BoundedBuffer is not thread-safe and requires the caller synchronize usage.

func NewBoundedBuffer added in v0.8.11

func NewBoundedBuffer[K any](size int, callback func(K) error) *BoundedBuffer[K]

NewBoundedBuffer creates a new BoundedBuffer.

func (*BoundedBuffer[K]) Insert added in v0.8.11

func (b *BoundedBuffer[K]) Insert(h K) error

Insert adds a new value to the buffer. If the buffer is full, the oldest value will be overwritten and [callback] will be invoked.

func (*BoundedBuffer[K]) Last added in v0.8.11

func (b *BoundedBuffer[K]) Last() (K, bool)

Last retrieves the last item added to the buffer.

If no items have been added to the buffer, Last returns the default value of [K] and [false].

type BufferFIFOCache added in v0.11.4

type BufferFIFOCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func (*BufferFIFOCache[K, V]) Get added in v0.11.4

func (f *BufferFIFOCache[K, V]) Get(key K) (V, bool)

func (*BufferFIFOCache[K, V]) Put added in v0.11.4

func (f *BufferFIFOCache[K, V]) Put(key K, val V)

type CacheConfig

type CacheConfig struct {
	TrieCleanLimit                  int           // Memory allowance (MB) to use for caching trie nodes in memory
	TrieCleanJournal                string        // Disk journal for saving clean cache entries.
	TrieCleanRejournal              time.Duration // Time interval to dump clean cache to disk periodically
	TrieDirtyLimit                  int           // Memory limit (MB) at which to block on insert and force a flush of dirty trie nodes to disk
	TrieDirtyCommitTarget           int           // Memory limit (MB) to target for the dirties cache before invoking commit
	TriePrefetcherParallelism       int           // Max concurrent disk reads trie prefetcher should perform at once
	CommitInterval                  uint64        // Commit the trie every [CommitInterval] blocks.
	Pruning                         bool          // Whether to disable trie write caching and GC altogether (archive node)
	AcceptorQueueLimit              int           // Blocks to queue before blocking during acceptance
	PopulateMissingTries            *uint64       // If non-nil, sets the starting height for re-generating historical tries.
	PopulateMissingTriesParallelism int           // Number of readers to use when trying to populate missing tries.
	AllowMissingTries               bool          // Whether to allow an archive node to run with pruning enabled
	SnapshotDelayInit               bool          // Whether to initialize snapshots on startup or wait for external call
	SnapshotLimit                   int           // Memory allowance (MB) to use for caching snapshot entries in memory
	SnapshotVerify                  bool          // Verify generated snapshots
	Preimages                       bool          // Whether to store preimage of trie key to the disk
	AcceptedCacheSize               int           // Depth of accepted headers cache and accepted logs cache at the accepted tip
	TxLookupLimit                   uint64        // Number of recent blocks for which to maintain transaction lookup indices
	SkipTxIndexing                  bool          // Whether to skip transaction indexing

	SnapshotNoBuild bool // Whether the background generation is allowed
	SnapshotWait    bool // Wait for snapshot construction on startup. TODO(karalabe): This is a dirty hack for testing, nuke it
}

CacheConfig contains the configuration values for the trie database that's resident in a blockchain.

type ChainContext

type ChainContext interface {
	// Engine retrieves the chain's consensus engine.
	Engine() consensus.Engine

	// GetHeader returns the header corresponding to the hash/number argument pair.
	GetHeader(common.Hash, uint64) *types.Header
}

ChainContext supports retrieving headers and consensus parameters from the current blockchain to be used during transaction processing.

type ChainEvent

type ChainEvent struct {
	Block *types.Block
	Hash  common.Hash
	Logs  []*types.Log
}

type ChainHeadEvent

type ChainHeadEvent struct{ Block *types.Block }

type ChainIndexer

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

ChainIndexer does a post-processing job for equally sized sections of the canonical chain (like BlooomBits and CHT structures). A ChainIndexer is connected to the blockchain through the event system by starting a ChainHeadEventLoop in a goroutine.

Further child ChainIndexers can be added which use the output of the parent section indexer. These child indexers receive new head notifications only after an entire section has been finished or in case of rollbacks that might affect already finished sections.

func NewBloomIndexer added in v0.5.0

func NewBloomIndexer(db ethdb.Database, size, confirms uint64) *ChainIndexer

NewBloomIndexer returns a chain indexer that generates bloom bits data for the canonical chain for fast logs filtering.

func NewChainIndexer

func NewChainIndexer(chainDb ethdb.Database, indexDb ethdb.Database, backend ChainIndexerBackend, section, confirm uint64, throttling time.Duration, kind string) *ChainIndexer

NewChainIndexer creates a new chain indexer to do background processing on chain segments of a given size after certain number of confirmations passed. The throttling parameter might be used to prevent database thrashing.

func (*ChainIndexer) AddCheckpoint

func (c *ChainIndexer) AddCheckpoint(section uint64, shead common.Hash)

AddCheckpoint adds a checkpoint. Sections are never processed and the chain is not expected to be available before this point. The indexer assumes that the backend has sufficient information available to process subsequent sections.

Note: knownSections == 0 and storedSections == checkpointSections until syncing reaches the checkpoint

func (*ChainIndexer) AddChildIndexer

func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer)

AddChildIndexer adds a child ChainIndexer that can use the output of this one

func (*ChainIndexer) Close

func (c *ChainIndexer) Close() error

Close tears down all goroutines belonging to the indexer and returns any error that might have occurred internally.

func (*ChainIndexer) Prune added in v0.3.1

func (c *ChainIndexer) Prune(threshold uint64) error

Prune deletes all chain data older than given threshold.

func (*ChainIndexer) SectionHead

func (c *ChainIndexer) SectionHead(section uint64) common.Hash

SectionHead retrieves the last block hash of a processed section from the index database.

func (*ChainIndexer) Sections

func (c *ChainIndexer) Sections() (uint64, uint64, common.Hash)

Sections returns the number of processed sections maintained by the indexer and also the information about the last header indexed for potential canonical verifications.

func (*ChainIndexer) Start

func (c *ChainIndexer) Start(chain ChainIndexerChain)

Start creates a goroutine to feed chain head events into the indexer for cascading background processing. Children do not need to be started, they are notified about new events by their parents.

type ChainIndexerBackend

type ChainIndexerBackend interface {
	// Reset initiates the processing of a new chain segment, potentially terminating
	// any partially completed operations (in case of a reorg).
	Reset(ctx context.Context, section uint64, prevHead common.Hash) error

	// Process crunches through the next header in the chain segment. The caller
	// will ensure a sequential order of headers.
	Process(ctx context.Context, header *types.Header) error

	// Commit finalizes the section metadata and stores it into the database.
	Commit() error

	// Prune deletes the chain index older than the given threshold.
	Prune(threshold uint64) error
}

ChainIndexerBackend defines the methods needed to process chain segments in the background and write the segment results into the database. These can be used to create filter blooms or CHTs.

type ChainIndexerChain

type ChainIndexerChain interface {
	// CurrentHeader retrieves the latest locally known header.
	CurrentHeader() *types.Header

	// SubscribeChainHeadEvent subscribes to new head header notifications.
	SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
}

ChainIndexerChain interface is used for connecting the indexer to a blockchain

type ChainSideEvent

type ChainSideEvent struct {
	Block *types.Block
}

type ChainTest added in v0.5.4

type ChainTest struct {
	Name string
	// contains filtered or unexported fields
}

type ExecutionResult added in v0.3.1

type ExecutionResult struct {
	UsedGas    uint64 // Total used gas but include the refunded gas
	Err        error  // Any error encountered during the execution(listed in core/vm/errors.go)
	ReturnData []byte // Returned data from evm(function result or data supplied with revert opcode)
}

ExecutionResult includes all output after executing given evm message no matter the execution itself is successful or not.

func ApplyMessage

func ApplyMessage(evm *vm.EVM, msg *Message, gp *GasPool) (*ExecutionResult, error)

ApplyMessage computes the new state by applying the given message against the old state within the environment.

ApplyMessage returns the bytes returned by any EVM execution (if it took place), the gas used (which includes gas refunds) and an error if it failed. An error always indicates a core error meaning that the message would always fail for that particular state and would never be accepted within a block.

func (*ExecutionResult) Failed added in v0.3.1

func (result *ExecutionResult) Failed() bool

Failed returns the indicator whether the execution is successful or not

func (*ExecutionResult) Return added in v0.3.1

func (result *ExecutionResult) Return() []byte

Return is a helper function to help caller distinguish between revert reason and function return. Return returns the data after execution if no error occurs.

func (*ExecutionResult) Revert added in v0.3.1

func (result *ExecutionResult) Revert() []byte

Revert returns the concrete revert reason if the execution is aborted by `REVERT` opcode. Note the reason can be nil if no data supplied with revert opcode.

func (*ExecutionResult) Unwrap added in v0.3.1

func (result *ExecutionResult) Unwrap() error

Unwrap returns the internal evm error which allows us for further analysis outside.

type FIFOCache added in v0.11.4

type FIFOCache[K comparable, V any] interface {
	Put(K, V)
	Get(K) (V, bool)
}

FIFOCache evicts the oldest element added to it after [limit] items are added.

func NewFIFOCache added in v0.11.4

func NewFIFOCache[K comparable, V any](limit int) FIFOCache[K, V]

NewFIFOCache creates a new First-In-First-Out cache of size [limit].

If a [limit] of 0 is passed as an argument, a no-op cache is returned that does nothing.

type GasPool

type GasPool uint64

GasPool tracks the amount of gas available during execution of the transactions in a block. The zero value is a pool with zero gas available.

func (*GasPool) AddGas

func (gp *GasPool) AddGas(amount uint64) *GasPool

AddGas makes gas available for execution.

func (*GasPool) Gas

func (gp *GasPool) Gas() uint64

Gas returns the amount of gas remaining in the pool.

func (*GasPool) SetGas added in v0.12.3

func (gp *GasPool) SetGas(gas uint64)

SetGas sets the amount of gas with the provided number.

func (*GasPool) String

func (gp *GasPool) String() string

func (*GasPool) SubGas

func (gp *GasPool) SubGas(amount uint64) error

SubGas deducts the given amount from the pool if enough gas is available and returns an error otherwise.

type Genesis

type Genesis struct {
	Config     *params.ChainConfig `json:"config"`
	Nonce      uint64              `json:"nonce"`
	Timestamp  uint64              `json:"timestamp"`
	ExtraData  []byte              `json:"extraData"`
	GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
	Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
	Mixhash    common.Hash         `json:"mixHash"`
	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"`
	GasUsed    uint64      `json:"gasUsed"`
	ParentHash common.Hash `json:"parentHash"`
	BaseFee    *big.Int    `json:"baseFeePerGas"`
}

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

func (*Genesis) Commit added in v0.2.9

func (g *Genesis) Commit(db ethdb.Database, triedb *trie.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) MarshalJSON added in v0.2.9

func (g Genesis) MarshalJSON() ([]byte, error)

MarshalJSON marshals as JSON.

func (*Genesis) MustCommit added in v0.2.9

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

MustCommit writes the genesis block and state to db, panicking on error. The block is committed as the canonical head block. Note the state changes will be committed in hash-based scheme, use Commit if path-scheme is preferred.

func (*Genesis) ToBlock added in v0.2.9

func (g *Genesis) ToBlock() *types.Block

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

func (*Genesis) UnmarshalJSON added in v0.2.9

func (g *Genesis) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals from JSON.

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"`
	MCBalance  GenesisMultiCoinBalance     `json:"mcbalance,omitempty"`
	Nonce      uint64                      `json:"nonce,omitempty"`
	PrivateKey []byte                      `json:"secretKey,omitempty"` // for tests
}

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

func (GenesisAccount) MarshalJSON added in v0.2.9

func (g GenesisAccount) MarshalJSON() ([]byte, error)

MarshalJSON marshals as JSON.

func (*GenesisAccount) UnmarshalJSON added in v0.2.9

func (g *GenesisAccount) UnmarshalJSON(input []byte) error

UnmarshalJSON unmarshals from JSON.

type GenesisAlloc

type GenesisAlloc map[common.Address]GenesisAccount

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

func (*GenesisAlloc) UnmarshalJSON added in v0.2.9

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

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

type GenesisMultiCoinBalance map[common.Hash]*big.Int

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.

HeaderChain is responsible for maintaining the header chain including the header query and updating.

The components maintained by headerchain includes: (1) header (2) block hash -> number mapping (3) canonical number -> hash mapping and (4) head header flag.

It is not thread safe either, the encapsulating chain structures should do the necessary mutex locking/unlocking.

func NewHeaderChain

func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, cacheConfig *CacheConfig, engine consensus.Engine) (*HeaderChain, error)

NewHeaderChain creates a new HeaderChain structure. ProcInterrupt points to the parent's interrupt semaphore.

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

func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash

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. In theory, if header is present in the database, all relative components like td and hash->number should be present too.

func (*HeaderChain) SetCurrentHeader

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

SetCurrentHeader sets the in-memory head header marker of the canonical chan as the given header.

func (*HeaderChain) SetGenesis

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

SetGenesis sets a new genesis block header for the chain

type Message

type Message struct {
	To         *common.Address
	From       common.Address
	Nonce      uint64
	Value      *big.Int
	GasLimit   uint64
	GasPrice   *big.Int
	GasFeeCap  *big.Int
	GasTipCap  *big.Int
	Data       []byte
	AccessList types.AccessList

	// When SkipAccountChecks is true, the message nonce is not checked against the
	// account nonce in state. It also disables checking that the sender is an EOA.
	// This field will be set to true for operations like RPC eth_call.
	SkipAccountChecks bool
}

A Message contains the data derived from a single transaction that is relevant to state processing.

func TransactionToMessage added in v0.12.3

func TransactionToMessage(tx *types.Transaction, s types.Signer, baseFee *big.Int) (*Message, error)

TransactionToMessage converts a transaction into a Message.

type NewTxPoolHeadEvent

type NewTxPoolHeadEvent struct{ Head *types.Header }

NewTxPoolHeadEvent is posted when the pool receives a request to update its head to [Block].

type NewTxPoolReorgEvent added in v0.5.4

type NewTxPoolReorgEvent struct{ Head *types.Header }

NewTxPoolReorgEvent is posted when the pool head is updated.

type NewTxsEvent

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

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

type NoOpFIFOCache added in v0.11.4

type NoOpFIFOCache[K comparable, V any] struct{}

func (*NoOpFIFOCache[K, V]) Get added in v0.11.4

func (f *NoOpFIFOCache[K, V]) Get(_ K) (V, bool)

func (*NoOpFIFOCache[K, V]) Put added in v0.11.4

func (f *NoOpFIFOCache[K, V]) Put(_ K, _ V)

type Processor

type Processor interface {
	// Process processes the state changes according to the Ethereum rules by running
	// the transaction messages using the statedb and applying any rewards to both
	// the processor (coinbase) and any included uncles.
	Process(block *types.Block, parent *types.Header, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)
}

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

type RemovedLogsEvent

type RemovedLogsEvent struct{ Logs []*types.Log }

RemovedLogsEvent is posted when a reorg happens

type StateProcessor

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

StateProcessor is a basic Processor, which takes care of transitioning state from one point to another.

StateProcessor implements Processor.

func NewStateProcessor

func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *StateProcessor

NewStateProcessor initialises a new StateProcessor.

func (*StateProcessor) Process

func (p *StateProcessor) Process(block *types.Block, parent *types.Header, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)

Process processes the state changes according to the Ethereum rules by running the transaction messages using the statedb and applying any rewards to both the processor (coinbase) and any included uncles.

Process returns the receipts and logs accumulated during the process and returns the amount of gas that was used in the process. If any of the transactions failed to execute due to insufficient gas it will return an error.

type StateTransition

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

StateTransition represents a state transition.

== The State Transitioning Model

A state transition is a change made when a transaction is applied to the current world state. The state transitioning model does all the necessary work to work out a valid new state root.

  1. Nonce handling
  2. Pre pay gas
  3. Create a new state object if the recipient is nil
  4. Value transfer

== If contract creation ==

4a. Attempt to run transaction data
4b. If valid, use result as code for the new state object

== end ==

  1. Run Script section
  2. Derive new state root

func NewStateTransition

func NewStateTransition(evm *vm.EVM, msg *Message, gp *GasPool) *StateTransition

NewStateTransition initialises and returns a new state transition object.

func (*StateTransition) TransitionDb

func (st *StateTransition) TransitionDb() (*ExecutionResult, error)

TransitionDb will transition the state by applying the current message and returning the evm execution result with following fields.

  • used gas: total gas used (including gas being refunded)
  • returndata: the returned data from evm
  • concrete execution error: various EVM errors which abort the execution, e.g. ErrOutOfGas, ErrExecutionReverted

However if any consensus issue encountered, return the error directly with nil evm execution result.

type TrieDB added in v0.6.0

type TrieDB interface {
	Dereference(root common.Hash) error
	Commit(root common.Hash, report bool) error
	Size() (common.StorageSize, common.StorageSize)
	Cap(limit common.StorageSize) error
}

type TrieWriter added in v0.5.4

type TrieWriter interface {
	InsertTrie(block *types.Block) error // Handle inserted trie reference of [root]
	AcceptTrie(block *types.Block) error // Mark [root] as part of an accepted block
	RejectTrie(block *types.Block) error // Notify TrieWriter that the block containing [root] has been rejected
	Shutdown() error
}

func NewTrieWriter added in v0.5.4

func NewTrieWriter(db TrieDB, config *CacheConfig) TrieWriter

type TxSenderCacher added in v0.7.0

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

TxSenderCacher is a helper structure to concurrently ecrecover transaction senders from digital signatures on background threads.

func NewTxSenderCacher added in v0.12.3

func NewTxSenderCacher(threads int) *TxSenderCacher

NewTxSenderCacher creates a new transaction sender background cacher and starts as many processing goroutines as allowed by the GOMAXPROCS on construction.

func (*TxSenderCacher) Recover added in v0.7.0

func (cacher *TxSenderCacher) Recover(signer types.Signer, txs []*types.Transaction)

Recover recovers the senders from a batch of transactions and caches them back into the same data structures. There is no validation being done, nor any reaction to invalid signatures. That is up to calling code later.

func (*TxSenderCacher) Shutdown added in v0.8.8

func (cacher *TxSenderCacher) Shutdown()

Shutdown stops the threads started by newTxSenderCacher

type Validator

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

	// ValidateState validates the given statedb and optionally the receipts and
	// gas used.
	ValidateState(block *types.Block, state *state.StateDB, receipts types.Receipts, usedGas uint64) error
}

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

Directories

Path Synopsis
Package bloombits implements bloom filtering on batches of data.
Package bloombits implements bloom filtering on batches of data.
Package rawdb contains a collection of low level database accessors.
Package rawdb contains a collection of low level database accessors.
Package state provides a caching layer atop the Ethereum state trie.
Package state provides a caching layer atop the Ethereum state trie.
snapshot
Package snapshot implements a journalled, dynamic state dump.
Package snapshot implements a journalled, dynamic state dump.
Package types contains data types related to Ethereum consensus.
Package types contains data types related to Ethereum consensus.
vm
Package vm implements the Ethereum Virtual Machine.
Package vm implements the Ethereum Virtual Machine.
runtime
Package runtime provides a basic execution model for executing EVM code.
Package runtime provides a basic execution model for executing EVM code.

Jump to

Keyboard shortcuts

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