core

package
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: May 17, 2019 License: MIT Imports: 68 Imported by: 99

Documentation

Overview

Package core implements the Matrix consensus protocol.

Index

Examples

Constants

View Source
const (

	// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
	BlockChainVersion = 3
	ModuleName        = "blockchain"
)
View Source
const (
	SendFloodSN
	GetTxbyN
	RecvTxbyN //
	RecvErrTx //
	BroadCast //
	GetConsensusTxbyN
	RecvConsensusTxbyN
)

消息类型

View Source
const (
	RewardFullRate = uint64(10000)
)

Variables

View Source
var (
	ErrNoGenesis = errors.New("Genesis not found in chain")

	SaveSnapPeriod uint64 = 300
	SaveSnapStart  uint64 = 0
	CleanMemFlgNum int    = 0
)
View Source
var (
	SlashCfg                 = mc.BlockProduceSlashCfg{Switcher: true, LowTHR: 1, ProhibitCycleNum: 2}
	ErrWriteSlashCfgStateErr = errors.Errorf("Init Set SlashCfg Err")
	ErrGetSlashCfgStateErr   = errors.Errorf("Get SlashCfg Err")
	ErrStatePtrIsNil         = errors.Errorf("State Ptr Is Null")
	ErrHeaderPtrIsNil        = errors.Errorf("Header Ptr Is Null")
	ErrSlashCfgPtrIsNil      = errors.Errorf("Slash Cfg Ptr Is Null")
)
View Source
var (
	AllGenesisJson = `` /* 25308-byte string literal not displayed */

	DefaultGenesisJson = `` /* 3404-byte string literal not displayed */

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

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

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

	ErrBlackListTx = errors.New("blacklist tx")
)
View Source
var (
	// ErrInvalidSender is returned if the transaction contains an invalid signature.
	ErrInvalidSender = errors.New("invalid sender")

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

	// ErrUnderpriced is returned if a transaction's gas price is below the minimum
	// configured for the transaction pool.
	ErrUnderpriced = errors.New("transaction underpriced")

	// ErrKnownTransaction is returned if a transaction is known or existent.
	ErrKnownTransaction = errors.New("known transaction")

	// ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
	// with a different one without the required price bump.
	ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")

	// 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")
	ErrEntrustInsufficientFunds = errors.New("entrust insufficient funds for gas * price")

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

	// ErrGasLimit is returned if a transaction's requested gas limit exceeds the
	// maximum allowance of the current block.
	ErrGasLimit = errors.New("exceeds block gas limit")

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

	//
	ErrTXCountOverflow = errors.New("transaction quantity spillover")
	ErrTXToNil         = errors.New("transaction`s to(common.address) is nil")
	ErrTXUnknownType   = errors.New("Unknown extra txtype")
	ErrTxToRepeat      = errors.New("contains duplicate transfer accounts")
	ErrTXWrongful      = errors.New("transaction is unlawful")
	ErrTXPoolFull      = errors.New("txpool is full")
	ErrTXNonceSame     = errors.New("the same Nonce transaction exists")
	ErrRepeatEntrust   = errors.New("Repeat Entrust")
	ErrWithoutAuth     = errors.New("gas entrust not set ")
	ErrinterestAmont   = errors.New("Incorrect total interest")
)
View Source
var (
	ErrTxPoolAlreadyExist = errors.New("txpool already exist")
	ErrTxPoolIsNil        = errors.New("txpool is nil")
	ErrTxPoolNonexistent  = errors.New("txpool nonexistent")
)
View Source
var BadHashes = map[common.Hash]bool{
	common.HexToHash("05bef30ef572270f654746da22639a7a0c97dd97a7050b9e252391996aaeb689"): true,
	common.HexToHash("7d05d08cbc596a2e5e4f13b80a743e53e09221b5323c3a61946b20873e58583f"): true,
}

BadHashes represent a set of manually tracked bad hashes (usually hard forks)

View Source
var DefaultTxPoolConfig = TxPoolConfig{
	PriceLimit:   params.TxGasPrice,
	AccountSlots: 16,
	GlobalSlots:  4096 * 5 * 5 * 10,
	AccountQueue: 64 * 1000,
	GlobalQueue:  1024 * 60,
	// contains filtered or unexported fields
}

DefaultTxPoolConfig contains the default configurations for the transaction pool.

Functions

func ApplyMessage

func ApplyMessage(evm *vm.EVM, tx txinterface.Message, gp *GasPool) ([]byte, uint64, bool, []uint, 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 ApplyTransaction

func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDBManage, header *types.Header, tx types.SelfTransaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, []uint, 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 BlackListFilter added in v1.1.1

func BlackListFilter(tx types.SelfTransaction, state *state.StateDBManage, h *big.Int) bool

func CalcGasLimit

func CalcGasLimit(parent *types.Block) uint64

CalcGasLimit computes the gas limit of the next block after parent. This is miner strategy, not consensus protocol.

func CanTransfer

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

CanTransfer checks wether 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 CopyAddressSlice added in v1.1.1

func CopyAddressSlice(Src *[]GenesisAddress) []common.Address

func GenerateChain

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

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      = mandb.NewMemDatabase()
)

// 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)}},
}
genesis := gspec.MustCommit(db)

// This call generates a chain of 5 blocks. The function runs for
// each block and adds different features to gen based on the
// block index.
signer := types.HomesteadSigner{}
chain, _ := GenerateChain(gspec.Config, genesis, manash.NewFaker(), db, 5, func(i int, gen *BlockGen) {
	switch i {
	case 0:
		// In block 1, addr1 sends addr2 some man.
		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 man 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)
		tx2, _ := types.SignTx(types.NewTransaction(gen.TxNonce(addr2), addr3, big.NewInt(1000), params.TxGas, nil, nil), signer, key2)
		gen.AddTx(tx1)
		gen.AddTx(tx2)
	case 2:
		// Block 3 is empty but was mined by addr3.
		gen.SetCoinbase(addr3)
		gen.SetExtra([]byte("yeehaw"))
	case 3:
		// Block 4 includes blocks 2 and 3 as uncle headers (with modified extra data).
		b2 := gen.PrevBlock(1).Header()
		b2.Extra = []byte("foo")
		gen.AddUncle(b2)
		b3 := gen.PrevBlock(2).Header()
		b3.Extra = []byte("foo")
		gen.AddUncle(b3)
	}
})

// Import the chain. This runs all block validation rules.
blockchain, _ := NewBlockChain(db, nil, gspec.Config, manash.NewFaker(), vm.Config{})
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))
Output:

last block: #5
balance of addr1: 989000
balance of addr2: 10000
balance of addr3: 19687500000000001000

func GenesisBlockForTesting

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

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

func GetBroadcastTxMap added in v1.1.1

func GetBroadcastTxMap(bc ChainReader, root []common.CoinRoot, txtype string) (reqVal map[common.Address][]byte, err error)

func GetHashFn

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

Y ====================================end================================ GetHashFn returns a GetHashFunc which retrieves header hashes by number

func GetMatrixCoin added in v1.1.2

func GetMatrixCoin(state *state.StateDBManage) ([]string, error)

func IntrinsicGas

func IntrinsicGas(data []byte) (uint64, error)

IntrinsicGas computes the 'intrinsic gas' for a message with the given data. func IntrinsicGas(data []byte, contractCreation, homestead bool) (uint64, error) {

func NewBlackListMaintainA added in v1.1.4

func NewBlackListMaintainA(list []mc.UserBlockProduceSlash) *blacklistMaintain

func NewBlackListMaintainB added in v1.1.4

func NewBlackListMaintainB(parentHash common.Hash, list []mc.UserBlockProduceSlash) *blacklistMaintain

func NewEVMContext

func NewEVMContext(sender common.Address, gasprice *big.Int, header *types.Header, chain ChainContext, author *common.Address) vm.Context

func ProduceBroadcastIntervalData added in v1.1.1

func ProduceBroadcastIntervalData(block *types.Block, state *state.StateDBManage, readFn PreStateReadFn) (interface{}, error)

func ProduceMatrixStateData added in v1.1.1

func ProduceMatrixStateData(block *types.Block, stateDb *state.StateDBManage, readFn PreStateReadFn) (interface{}, error)

func SetReceiptsData

func SetReceiptsData(config *params.ChainConfig, block *types.Block) error

SetReceiptsData computes all the non-consensus fields of the receipts

func SetupGenesisBlock

func SetupGenesisBlock(db mandb.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.

func TransToCommonElect added in v1.1.1

func TransToCommonElect(elect GenesisElect) common.Elect

func TransToCommonNetTopology added in v1.1.1

func TransToCommonNetTopology(gtopology GenesisNetTopology) common.NetTopology

func Transfer

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

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

Types

type BadBlockArgs

type BadBlockArgs struct {
	Hash   common.Hash   `json:"hash"`
	Header *types.Header `json:"header"`
}

BadBlockArgs represents the entries in the list returned when bad blocks are queried.

type Blacklist added in v1.1.1

type Blacklist struct {
	Bmap map[common.Address]bool
	// contains filtered or unexported fields
}
var SelfBlackList *Blacklist

func NewInitblacklist added in v1.1.1

func NewInitblacklist() *Blacklist

func (*Blacklist) AddBlackAddress added in v1.1.1

func (b *Blacklist) AddBlackAddress(addr common.Address)

func (*Blacklist) FindBlackAddress added in v1.1.1

func (b *Blacklist) FindBlackAddress(addr common.Address) bool

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 mandb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config) (*BlockChain, error)

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

func NewCanonical added in v1.1.1

func NewCanonical(engine consensus.Engine, n int, full bool) (mandb.Database, *BlockChain, error)

newCanonical creates a chain database, and injects a deterministic canonical chain. Depending on the full flag, if creates either a full block chain or a header only chain.

func (*BlockChain) BadBlocks

func (bc *BlockChain) BadBlocks() ([]BadBlockArgs, error)

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) CurrentBlockStore added in v1.1.1

func (bc *BlockChain) CurrentBlockStore(tbc *types.Block)

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

func (bc *BlockChain) DPOSEngine(version []byte) consensus.DPOSEngine

func (*BlockChain) DelLocalBlocks added in v1.1.3

func (bc *BlockChain) DelLocalBlocks(blocks []*mc.BlockInfo) (fails []*mc.BlockInfo, err error)

func (*BlockChain) Engine

func (bc *BlockChain) Engine(version []byte) 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) 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) GetA0AccountFromA1Account added in v1.1.1

func (bc *BlockChain) GetA0AccountFromA1Account(a1Account common.Address, block *types.Block, st *state.StateDBManage) (common.Address, error)

根据A1账户得到A0账户

func (*BlockChain) GetA0AccountFromAnyAccount added in v1.1.1

func (bc *BlockChain) GetA0AccountFromAnyAccount(account common.Address, blockHash common.Hash) (common.Address, common.Address, error)

根据任意账户得到A0和A1账户

func (*BlockChain) GetA0AccountFromAnyAccountAtSignHeight added in v1.1.1

func (bc *BlockChain) GetA0AccountFromAnyAccountAtSignHeight(account common.Address, blockHash common.Hash, signHeight uint64) (common.Address, common.Address, error)

根据任意账户得到A0和A1账户

func (*BlockChain) GetA1AccountFromA0Account added in v1.1.1

func (bc *BlockChain) GetA1AccountFromA0Account(a0Account common.Address, block *types.Block, st *state.StateDBManage) (common.Address, error)

根据A0账户得到A1账户

func (*BlockChain) GetA1AccountFromA2Account added in v1.1.1

func (bc *BlockChain) GetA1AccountFromA2Account(a2Account common.Address, block *types.Block, st *state.StateDBManage) (common.Address, error)

根据A2账户得到A1账户

func (*BlockChain) GetA1AccountFromA2AccountAtSignHeight added in v1.1.1

func (bc *BlockChain) GetA1AccountFromA2AccountAtSignHeight(a2Account common.Address, st *state.StateDBManage, signHeight uint64) (common.Address, error)

根据A2账户得到A1账户

func (*BlockChain) GetA2AccountsFromA0Account added in v1.1.1

func (bc *BlockChain) GetA2AccountsFromA0Account(a0Account common.Address, blockHash common.Hash) ([]common.Address, error)

//根据A2账户得到A0账户

func (bc *BlockChain) GetA0AccountFromA2Account(a2Account common.Address, blockHash common.Hash) (common.Address, error) {
	a1Account, err := bc.GetA1AccountFromA2Account(a2Account, blockHash)
	if err != nil {
		return common.Address{}, err
	}
	a0Account, err := bc.GetA0AccountFromA1Account(a1Account, blockHash)
	if err != nil {
		return common.Address{}, err
	}
	return a0Account, nil
}

根据A0账户得到A2账户集合

func (*BlockChain) GetA2AccountsFromA0AccountAtSignHeight added in v1.1.1

func (bc *BlockChain) GetA2AccountsFromA0AccountAtSignHeight(a0Account common.Address, blockHash common.Hash, signHeight uint64) ([]common.Address, error)

根据A0账户得到A2账户集合

func (*BlockChain) GetA2AccountsFromA1Account added in v1.1.1

func (bc *BlockChain) GetA2AccountsFromA1Account(a1Account common.Address, block *types.Block, st *state.StateDBManage) ([]common.Address, error)

根据A1账户得到A2账户集合

func (*BlockChain) GetA2AccountsFromA1AccountAtSignHeight added in v1.1.1

func (bc *BlockChain) GetA2AccountsFromA1AccountAtSignHeight(a1Account common.Address, block *types.Block, st *state.StateDBManage, signHeight uint64) ([]common.Address, error)

func (*BlockChain) GetAncestorHash added in v1.1.1

func (bc *BlockChain) GetAncestorHash(sonHash common.Hash, ancestorNumber uint64) (common.Hash, error)

func (*BlockChain) GetBlackList added in v1.1.1

func (bc *BlockChain) GetBlackList(state *state.StateDBManage) *mc.BlockProduceSlashBlackList

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) GetBlockSuperAccounts added in v1.1.1

func (bc *BlockChain) GetBlockSuperAccounts(blockHash common.Hash) ([]common.Address, error)

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 man/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) GetBroadcastAccounts added in v1.1.1

func (bc *BlockChain) GetBroadcastAccounts(blockHash common.Hash) ([]common.Address, error)

func (*BlockChain) GetBroadcastInterval added in v1.1.1

func (bc *BlockChain) GetBroadcastInterval() (*mc.BCIntervalInfo, error)

func (*BlockChain) GetBroadcastIntervalByHash added in v1.1.1

func (bc *BlockChain) GetBroadcastIntervalByHash(blockHash common.Hash) (*mc.BCIntervalInfo, error)

func (*BlockChain) GetBroadcastIntervalByNumber added in v1.1.1

func (bc *BlockChain) GetBroadcastIntervalByNumber(number uint64) (*mc.BCIntervalInfo, error)

func (*BlockChain) GetCurrentHash added in v1.1.1

func (bc *BlockChain) GetCurrentHash() common.Hash

func (*BlockChain) GetDB added in v1.1.1

func (bc *BlockChain) GetDB() mandb.Database

func (*BlockChain) GetGraphByHash added in v1.1.1

func (bc *BlockChain) GetGraphByHash(hash common.Hash) (*mc.TopologyGraph, *mc.ElectGraph, error)

func (*BlockChain) GetGraphByState added in v1.1.1

func (bc *BlockChain) GetGraphByState(state matrixstate.StateDB) (*mc.TopologyGraph, *mc.ElectGraph, error)

func (*BlockChain) GetHashByNumber added in v1.1.1

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

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) GetInnerMinerAccounts added in v1.1.1

func (bc *BlockChain) GetInnerMinerAccounts(blockHash common.Hash) ([]common.Address, error)

func (*BlockChain) GetIpfsQMux added in v1.1.3

func (bc *BlockChain) GetIpfsQMux()

func (*BlockChain) GetIpfsQUnMux added in v1.1.3

func (bc *BlockChain) GetIpfsQUnMux()

func (*BlockChain) GetMultiCoinSuperAccounts added in v1.1.1

func (bc *BlockChain) GetMultiCoinSuperAccounts(blockHash common.Hash) ([]common.Address, error)

func (*BlockChain) GetReceiptsByHash

func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) []types.CoinReceipts

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

func (*BlockChain) GetSignAccountPassword added in v1.1.1

func (bc *BlockChain) GetSignAccountPassword(signAccounts []common.Address) (common.Address, string, error)

func (*BlockChain) GetSlashCfg added in v1.1.1

func (bc *BlockChain) GetSlashCfg(state *state.StateDBManage) (*mc.BlockProduceSlashCfg, error)

func (*BlockChain) GetStateCache added in v1.1.1

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

func (*BlockChain) GetStoreBlockInfo added in v1.1.1

func (bc *BlockChain) GetStoreBlockInfo() *prque.Prque

func (*BlockChain) GetSubChainSuperAccounts added in v1.1.1

func (bc *BlockChain) GetSubChainSuperAccounts(blockHash common.Hash) ([]common.Address, error)

func (*BlockChain) GetSuperBlockInfo added in v1.1.1

func (bc *BlockChain) GetSuperBlockInfo() (*mc.SuperBlkCfg, error)

func (*BlockChain) GetSuperBlockNum added in v1.1.1

func (bc *BlockChain) GetSuperBlockNum() (uint64, error)

func (*BlockChain) GetSuperBlockSeq added in v1.1.1

func (bc *BlockChain) GetSuperBlockSeq() (uint64, error)

func (*BlockChain) GetTd

func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int

GetTd retrieves a block's total difficulty in the canonical chain from the database by hash and number, caching it if found.

func (*BlockChain) GetTdByHash

func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int

GetTdByHash retrieves a block's total difficulty in the canonical chain from the database by hash, caching it if found.

func (*BlockChain) GetTopologyStore added in v1.1.1

func (bc *BlockChain) GetTopologyStore() *TopologyStore

func (*BlockChain) GetUnclesInChain

func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header

GetUnclesInChain retrieves all the uncles from a given block backwards until a specific distance is reached.

func (*BlockChain) GetVersionSuperAccounts added in v1.1.1

func (bc *BlockChain) GetVersionSuperAccounts(blockHash common.Hash) ([]common.Address, error)

func (*BlockChain) HandleUpTimeWithSuperBlock added in v1.1.1

func (bc *BlockChain) HandleUpTimeWithSuperBlock(state *state.StateDBManage, accounts []common.Address, blockNum uint64, bcInterval *mc.BCIntervalInfo) (map[common.Address]uint64, error)

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) 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) HasStateRoot added in v1.1.2

func (bc *BlockChain) HasStateRoot(roots []common.CoinRoot) bool

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) InsertChainNotify added in v1.1.1

func (bc *BlockChain) InsertChainNotify(chain types.Blocks, notify bool) (int, error)

func (*BlockChain) InsertHeaderChain

func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (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 verify nonces, as well as because nonces can be verified sparsely, not needing to check each.

func (*BlockChain) InsertReceiptChain

func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks) (int, error)

InsertReceiptChain attempts to complete an already existing header chain with transaction and receipt data.

func (*BlockChain) InsertSuperBlock added in v1.1.1

func (bc *BlockChain) InsertSuperBlock(superBlockGen *Genesis, notify bool) (*types.Block, error)

func (*BlockChain) LoadDumps added in v1.1.2

func (bc *BlockChain) LoadDumps(dumps []state.DumpDB, number int64) bool

func (*BlockChain) PostChainEvents

func (bc *BlockChain) PostChainEvents(events []interface{}, logs []types.CoinLogs)

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) PrintSnapshotAccountMsg added in v1.1.1

func (bc *BlockChain) PrintSnapshotAccountMsg(blockNum uint64, hash string, filePath string)

func (*BlockChain) ProcessBlockGProduceSlash added in v1.1.1

func (bc *BlockChain) ProcessBlockGProduceSlash(version string, state *state.StateDBManage, header *types.Header) error

func (*BlockChain) ProcessMatrixState added in v1.1.1

func (bc *BlockChain) ProcessMatrixState(block *types.Block, preVersion string, state *state.StateDBManage) error

func (*BlockChain) ProcessStateVersion added in v1.1.1

func (bc *BlockChain) ProcessStateVersion(version []byte, st *state.StateDBManage) error

func (*BlockChain) ProcessStateVersionSwitch added in v1.1.4

func (bd *BlockChain) ProcessStateVersionSwitch(num uint64, stateDB *state.StateDBManage) error

func (*BlockChain) ProcessUpTime added in v1.1.1

func (bc *BlockChain) ProcessUpTime(state *state.StateDBManage, header *types.Header) (map[common.Address]uint64, error)

func (*BlockChain) Processor

func (bc *BlockChain) Processor(version []byte) Processor

Processor returns the current processor.

func (*BlockChain) RegisterMatrixStateDataProducer added in v1.1.1

func (bc *BlockChain) RegisterMatrixStateDataProducer(key string, producer ProduceMatrixStateDataFn)

func (*BlockChain) Reset

func (bc *BlockChain) Reset() error

Reset purges the entire blockchain, restoring it to its genesis state.

func (*BlockChain) ResetWithGenesisBlock

func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error

ResetWithGenesisBlock purges the entire blockchain, restoring it to the specified genesis state.

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) SaveSnapshot added in v1.1.1

func (bc *BlockChain) SaveSnapshot(blockNum uint64, period uint64)

func (*BlockChain) SetDposEngine

func (bc *BlockChain) SetDposEngine(version string, dposEngine consensus.DPOSEngine)

func (*BlockChain) SetHead

func (bc *BlockChain) SetHead(head uint64) error

SetHead rewinds the local chain to a new head. In the case of headers, everything above the new head will be deleted and the new one set. In the case of blocks though, the head may be further rewound if block bodies are missing (non-archive nodes after a fast sync).

func (*BlockChain) SetProcessor

func (bc *BlockChain) SetProcessor(version string, processor Processor)

SetProcessor sets the processor required for making state modifications.

func (*BlockChain) SetSnapshotParam added in v1.1.1

func (bc *BlockChain) SetSnapshotParam(period uint64, start uint64)

func (*BlockChain) SetValidator

func (bc *BlockChain) SetValidator(version string, validator Validator)

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

func (*BlockChain) SetbSendIpfsFlg added in v1.1.1

func (bc *BlockChain) SetbSendIpfsFlg(flg bool)

lb ipfs

func (*BlockChain) State

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

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

func (*BlockChain) StateAt

func (bc *BlockChain) StateAt(root []common.CoinRoot) (*state.StateDBManage, error)

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

func (*BlockChain) StateAtBlockHash added in v1.1.1

func (bc *BlockChain) StateAtBlockHash(hash common.Hash) (*state.StateDBManage, error)

func (*BlockChain) StateAtNumber added in v1.1.1

func (bc *BlockChain) StateAtNumber(number uint64) (*state.StateDBManage, error)

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) 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.CoinLogs) 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) SynSnapshot added in v1.1.1

func (bc *BlockChain) SynSnapshot(blockNum uint64, hash string, filePath string) bool

func (*BlockChain) TrieNode

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

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

func (*BlockChain) Validator

func (bc *BlockChain) Validator(version []byte) Validator

Validator returns the current validator.

func (*BlockChain) VerifyHeader

func (bc *BlockChain) VerifyHeader(header *types.Header) error

func (*BlockChain) WriteBlockWithState

func (bc *BlockChain) WriteBlockWithState(block *types.Block, state *state.StateDBManage) (status WriteStatus, err error)

WriteBlockWithState writes the block and all associated state to the database.

func (*BlockChain) WriteBlockWithoutState

func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (err error)

WriteBlockWithoutState writes only the block and its metadata to the database, but does not write any state. This is used to construct competing side forks up to the point where they exceed the canonical total difficulty.

type BlockGen

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

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

func (*BlockGen) AddTx

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

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

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

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

AddUncle adds an uncle header to the generated block.

func (*BlockGen) Number

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

Number returns the block number of the block being generated.

func (*BlockGen) OffsetTime

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

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

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

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

func (*BlockGen) SetExtra

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

SetExtra sets the extra data field of the generated block.

func (*BlockGen) TxNonce

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

func (*BlockValidator) ValidateHeader added in v1.1.1

func (v *BlockValidator) ValidateHeader(header *types.Header) error

ValidateBody validates the given block's uncles and verifies the 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, parent *types.Block, statedb *state.StateDBManage, 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. ValidateState returns a database batch if the validation was a success otherwise nil and an error is returned.

type BroadCastTxPool added in v1.1.1

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

func NewBroadTxPool added in v1.1.1

func NewBroadTxPool(chainconfig *params.ChainConfig, chain blockChainBroadCast, path string) *BroadCastTxPool

func (*BroadCastTxPool) AddTxPool added in v1.1.1

func (bPool *BroadCastTxPool) AddTxPool(tx types.SelfTransaction) (reerr error)

AddTxPool

func (*BroadCastTxPool) GetAllSpecialTxs added in v1.1.1

func (bPool *BroadCastTxPool) GetAllSpecialTxs() map[common.Address][]types.SelfTransaction

GetAllSpecialTxs get BroadCast transaction. (use apply SelfTransaction)

func (*BroadCastTxPool) Pending added in v1.1.1

func (bPool *BroadCastTxPool) Pending() (map[string]map[common.Address]types.SelfTransactions, error)

Pending

func (*BroadCastTxPool) ProcessMsg added in v1.1.1

func (bPool *BroadCastTxPool) ProcessMsg(m NetworkMsgData)

ProcessMsg

func (*BroadCastTxPool) ReturnAllTxsByN added in v1.1.1

func (bPool *BroadCastTxPool) ReturnAllTxsByN(listN []uint32, resqe byte, addr common.Address, retch chan *RetChan_txpool)

func (*BroadCastTxPool) SendMsg added in v1.1.1

func (bPool *BroadCastTxPool) SendMsg(data MsgStruct)

SendMsg

func (*BroadCastTxPool) Stop added in v1.1.1

func (bPool *BroadCastTxPool) Stop()

Stop terminates the transaction pool.

func (*BroadCastTxPool) Type added in v1.1.1

func (bPool *BroadCastTxPool) Type() byte

Type return txpool type.

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 ChainContext

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

	// GetHeader returns the hash corresponding to their hash.
	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.CoinLogs
}

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 ChainEventLoop 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 NewChainIndexer

func NewChainIndexer(chainDb, indexDb mandb.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) AddChildIndexer

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

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

func (*ChainIndexer) AddKnownSectionHead

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

AddKnownSectionHead marks a new section head as known/processed if it is newer than the already known best section head

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) 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(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(header *types.Header)

	// Commit finalizes the section metadata and stores it into the database.
	Commit() 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

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

ChainIndexerChain interface is used for connecting the indexer to a blockchain

type ChainReader added in v1.1.1

type ChainReader interface {
	StateAt(root []common.CoinRoot) (*state.StateDBManage, error)
}

type ChainSideEvent

type ChainSideEvent struct {
	Block *types.Block
}

type CoinPachFilter added in v1.1.2

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

type ConsensusNTx added in v1.1.1

type ConsensusNTx struct {
	Key   uint32
	Value types.SelfTransaction
}

type DeleteCallback

type DeleteCallback func(common.Hash, uint64)

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

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) 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,omitempty"`
	Nonce             uint64              `json:"nonce"`
	Timestamp         uint64              `json:"timestamp"    gencodec:"required"`
	ExtraData         []byte              `json:"extraData"`
	Version           string              `json:"version"    gencodec:"required"`
	VersionSignatures []common.Signature  `json:"versionSignatures"    gencodec:"required"`
	VrfValue          []byte              `json:"vrfvalue"`
	Leader            common.Address      `json:"leader"`
	NextElect         []common.Elect      `json:"nextElect"    gencodec:"required"`
	NetTopology       common.NetTopology  `json:"nettopology"       gencodec:"required"`
	Signatures        []common.Signature  `json:"signatures" gencodec:"required"`

	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"`
	MState     *GenesisMState `json:"mstate"    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"`
	Roots      []common.CoinRoot             `json:"stateRoot"        gencodec:"required"`
	Sharding   []common.Coinbyte             `json:"sharding,omitempty"`
	Currencys  map[string][]Genesiscurrencys `json:"currencys"`
}

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

func DefaultGenesis added in v1.1.1

func DefaultGenesis(genesisFile string) (*Genesis, error)

func DefaultGenesisBlock

func DefaultGenesisBlock() *Genesis

DefaultGenesisBlock returns the Matrix 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 'gman --dev' genesis block. Note, this must be seeded with the

func (*Genesis) Commit

func (g *Genesis) Commit(db mandb.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) GenSuperBlock added in v1.1.1

func (g *Genesis) GenSuperBlock(parentHeader *types.Header, mdb mandb.Database, sdb state.Database, chainCfg *params.ChainConfig) *types.Block

func (Genesis) MarshalJSON

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

func (*Genesis) MustCommit

func (g *Genesis) MustCommit(db mandb.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 mandb.Database) (*types.Block, error)

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

func (*Genesis) ToSuperBlock added in v1.1.3

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

func (*Genesis) UnmarshalJSON

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

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.

func (GenesisAccount) MarshalJSON

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

func (*GenesisAccount) UnmarshalJSON

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

type GenesisAddress added in v1.1.1

type GenesisAddress common.Address

func (GenesisAddress) MarshalText added in v1.1.1

func (a GenesisAddress) MarshalText() ([]byte, error)
func (a *GenesisAddress) MarshalJSON() ([]byte, error) {
	buff := base58.Base58EncodeToString("MAN", common.Address(*a))
	return []byte(buff),nil
}

MarshalText returns the hex representation of a.

func (*GenesisAddress) UnmarshalJSON added in v1.1.1

func (a *GenesisAddress) UnmarshalJSON(input []byte) error

UnmarshalJSON parses a hash in hex syntax.

func (*GenesisAddress) UnmarshalText added in v1.1.1

func (a *GenesisAddress) UnmarshalText(input []byte) error

UnmarshalText parses a hash in hex syntax.

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

type GenesisElect added in v1.1.1

type GenesisElect struct {
	Account GenesisAddress
	Stock   uint16
	Type    common.ElectRoleType
	VIP     common.VIPRoleType
}

func TransToGenesisElect added in v1.1.1

func TransToGenesisElect(elect common.Elect) GenesisElect

type GenesisMState added in v1.1.1

type GenesisMState struct {
	Broadcasts                   *[]GenesisAddress                `json:"Broadcasts,omitempty"`
	InnerMiners                  *[]GenesisAddress                `json:"InnerMiners,omitempty"`
	Foundation                   *GenesisAddress                  `json:"Foundation,omitempty"`
	VersionSuperAccounts         *[]GenesisAddress                `json:"VersionSuperAccounts,omitempty"`
	BlockSuperAccounts           *[]GenesisAddress                `json:"BlockSuperAccounts,omitempty"`
	MultiCoinSuperAccounts       *[]GenesisAddress                `json:"MultiCoinSuperAccounts,omitempty"`
	SubChainSuperAccounts        *[]GenesisAddress                `json:"SubChainSuperAccounts,omitempty"`
	VIPCfg                       *[]mc.VIPConfig                  `json:"VIPCfg,omitempty" gencodec:"required"`
	BCICfg                       *mc.BCIntervalInfo               `json:"BroadcastInterval,omitempty" gencodec:"required"`
	LeaderCfg                    *mc.LeaderConfig                 `json:"LeaderCfg,omitempty" gencodec:"required"`
	BlkCalcCfg                   *string                          `json:"BlkCalcCfg,omitempty" gencodec:"required"`
	TxsCalcCfg                   *string                          `json:"TxsCalcCfg,omitempty" gencodec:"required"`
	InterestCalcCfg              *string                          `json:"InterestCalcCfg,omitempty" gencodec:"required"`
	LotteryCalcCfg               *string                          `json:"LotteryCalcCfg,omitempty" gencodec:"required"`
	SlashCalcCfg                 *string                          `json:"SlashCalcCfg,omitempty" gencodec:"required"`
	BlkRewardCfg                 *mc.BlkRewardCfg                 `json:"BlkRewardCfg,omitempty" gencodec:"required"`
	TxsRewardCfg                 *mc.TxsRewardCfg                 `json:"TxsRewardCfg,omitempty" gencodec:"required"`
	LotteryCfg                   *mc.LotteryCfg                   `json:"LotteryCfg,omitempty" gencodec:"required"`
	InterestCfg                  *mc.InterestCfg                  `json:"InterestCfg,omitempty" gencodec:"required"`
	SlashCfg                     *mc.SlashCfg                     `json:"SlashCfg,omitempty" gencodec:"required"`
	EleTimeCfg                   *mc.ElectGenTimeStruct           `json:"EleTime,omitempty" gencodec:"required"`
	EleInfoCfg                   *mc.ElectConfigInfo              `json:"EleInfo,omitempty" gencodec:"required"`
	ElectMinerNumCfg             *mc.ElectMinerNumStruct          `json:"ElectMinerNum,omitempty" gencodec:"required"`
	ElectBlackListCfg            *[]GenesisAddress                `json:"ElectBlackList,omitempty" gencodec:"required"`
	ElectWhiteListSwitcherCfg    *mc.ElectWhiteListSwitcher       `json:"ElectWhiteListSwitcherCfg,omitempty" gencodec:"required"`
	ElectWhiteListCfg            *[]GenesisAddress                `json:"ElectWhiteList,omitempty" gencodec:"required"`
	CurElect                     *[]GenesisElect                  `json:"CurElect,omitempty"  gencodec:"required"`
	BlockProduceSlashCfg         *mc.BlockProduceSlashCfg         `json:"BlkProduceSlashCfg,omitempty" gencodec:"required"`
	BlockProduceStats            *mc.BlockProduceStats            `json:"BlkProduceStats,omitempty" gencodec:"required"`
	BlockProduceSlashBlackList   *mc.BlockProduceSlashBlackList   `json:"BlkProduceBlackList,omitempty" gencodec:"required"`
	BlockProduceSlashStatsStatus *mc.BlockProduceSlashStatsStatus `json:"BlkProduceStatus,omitempty" gencodec:"required"`
}

func (*GenesisMState) SetSuperBlkToState added in v1.1.1

func (g *GenesisMState) SetSuperBlkToState(state *state.StateDBManage, extra []byte, num uint64) 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 GenesisNetTopology added in v1.1.1

type GenesisNetTopology struct {
	Type            uint8
	NetTopologyData []GenesisNetTopologyData
}

func TransToGenesisNetTopology added in v1.1.1

func TransToGenesisNetTopology(topology common.NetTopology) GenesisNetTopology

type GenesisNetTopologyData added in v1.1.1

type GenesisNetTopologyData struct {
	Account  GenesisAddress
	Position uint16
}

type Genesiscurrencys added in v1.1.3

type Genesiscurrencys struct {
	Account string
	Quant   *big.Int
}

func (Genesiscurrencys) MarshalJSON added in v1.1.3

func (gc Genesiscurrencys) MarshalJSON() ([]byte, error)

func (*Genesiscurrencys) UnmarshalJSON added in v1.1.3

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

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 mandb.Database, config *params.ChainConfig, 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(version string) consensus.Engine

Engine retrieves the header chain's consensus engine.

func (*HeaderChain) GetAncestorHash added in v1.1.1

func (hc *HeaderChain) GetAncestorHash(sonHash common.Hash, ancestorNumber uint64) (common.Hash, error)

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

func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int

func (*HeaderChain) GetTdByHash

func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int

GetTdByHash retrieves a block's total difficulty in the canonical chain from the database by hash, caching it 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) SetDposEngine added in v1.1.1

func (hc *HeaderChain) SetDposEngine(version string, engine consensus.DPOSEngine)

func (*HeaderChain) SetEngine added in v1.1.1

func (hc *HeaderChain) SetEngine(version string, engine consensus.Engine)

func (*HeaderChain) SetGenesis

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

SetGenesis sets a new genesis block header for the chain

func (*HeaderChain) SetHead

func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback)

SetHead rewinds the local chain to a new head. Everything above the new head will be deleted and the new one set.

func (*HeaderChain) SetSBlkHead added in v1.1.2

func (hc *HeaderChain) SetSBlkHead(oldHead *types.Header, head uint64, delFn DeleteCallback)

SetHead rewinds the local chain to a new head. Everything above the new head will be deleted and the new one set.

func (*HeaderChain) ValidateHeaderChain

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

func (*HeaderChain) WriteHeader

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

WriteHeader writes a header into the local chain, given that its parent is already known. If the total difficulty of the newly inserted header becomes greater than the current known TD, the canonical chain is re-routed.

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

func (*HeaderChain) WriteTd

func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error

WriteTd stores a block's total difficulty into the database, also caching it along the way.

type MatrixProcessor added in v1.1.1

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

func NewMatrixProcessor added in v1.1.1

func NewMatrixProcessor() *MatrixProcessor

func (*MatrixProcessor) ProcessMatrixState added in v1.1.1

func (mp *MatrixProcessor) ProcessMatrixState(block *types.Block, preVersion string, state *state.StateDBManage) error

func (*MatrixProcessor) ProcessStateVersion added in v1.1.1

func (mp *MatrixProcessor) ProcessStateVersion(version []byte, state *state.StateDBManage) error

func (*MatrixProcessor) RegisterProducer added in v1.1.1

func (mp *MatrixProcessor) RegisterProducer(key string, producer ProduceMatrixStateDataFn)

type MessageProcess added in v1.1.1

type MessageProcess interface {
	ProcessMsg(m NetworkMsgData)
	SendMsg(data MsgStruct)
}

消息中心的接口(如果需要消息中心就要实现这两个方法)

type MsgStruct

type MsgStruct struct {
	Msgtype    uint32
	SendAddr   common.Address
	MsgData    []byte
	TxpoolType byte
}

type NetworkMsgData

type NetworkMsgData struct {
	SendAddress common.Address
	Data        []*MsgStruct
}

type NewMinedBlockEvent

type NewMinedBlockEvent struct{ Block *types.Block }

NewMinedBlockEvent is posted when a block has been imported.

type NewTxsEvent

type NewTxsEvent struct {
	Txs types.SelfTransactions
	// contains filtered or unexported fields
}

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

type NormalTxPool added in v1.1.1

type NormalTxPool struct {
	SContainer map[common.Hash]*types.Transaction
	NContainer map[uint32]*types.Transaction
	// contains filtered or unexported fields
}

func NewTxPool

func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain, sendch chan NewTxsEvent) *NormalTxPool

func (*NormalTxPool) AddTxPool added in v1.1.1

func (nPool *NormalTxPool) AddTxPool(txer types.SelfTransaction) 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 (*NormalTxPool) CheckTx added in v1.1.1

func (nPool *NormalTxPool) CheckTx(mapSN map[uint32]*big.Int, nid common.Address)

检查当前map中是否存在洪泛过来的交易

func (*NormalTxPool) Content added in v1.1.1

func (nPool *NormalTxPool) Content() map[common.Address][]*types.Transaction

Content retrieves the data content of the transaction pool, returning all the pending as well as queued transactions, grouped by account and sorted by nonce.

func (*NormalTxPool) DemoteUnexecutables added in v1.1.1

func (nPool *NormalTxPool) DemoteUnexecutables()

demoteUnexecutables removes invalid and processed transactions from the pools executable/pending queue and any subsequent transactions that become unexecutable are moved back into the future queue.

func (*NormalTxPool) Get added in v1.1.1

func (nPool *NormalTxPool) Get(hash common.Hash) *types.Transaction

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

func (*NormalTxPool) GetConsensusTxByN added in v1.1.1

func (nPool *NormalTxPool) GetConsensusTxByN(listN []uint32, nid common.Address)

(共识要交易)根据N值获取对应的交易(modi )

func (*NormalTxPool) GetTxByN added in v1.1.1

func (nPool *NormalTxPool) GetTxByN(listN []uint32, nid common.Address)

根据N值获取对应的交易(洪泛)

func (*NormalTxPool) ListenUdp added in v1.1.1

func (nPool *NormalTxPool) ListenUdp()

func (*NormalTxPool) Pending added in v1.1.1

func (nPool *NormalTxPool) Pending() (map[string]map[common.Address]types.SelfTransactions, error)

Pending retrieves all currently processable transactions, groupped by origin account and sorted by nonce. The returned transaction set is a copy and can be freely modified by calling code.

func (*NormalTxPool) ProcessMsg added in v1.1.1

func (nPool *NormalTxPool) ProcessMsg(m NetworkMsgData)

ProcessMsg

func (*NormalTxPool) RecvConsensusFloodTx added in v1.1.1

func (nPool *NormalTxPool) RecvConsensusFloodTx(mapNtx map[uint32]types.SelfTransaction, nid common.Address)

此接口传的交易带s(modi )

func (*NormalTxPool) RecvErrTx added in v1.1.1

func (nPool *NormalTxPool) RecvErrTx(addr common.Address, listS []*big.Int)

接收错误交易

func (*NormalTxPool) RecvFloodTx added in v1.1.1

func (nPool *NormalTxPool) RecvFloodTx(mapNtx map[uint32]*types.Floodtxdata, nid common.Address)

接收洪泛的交易(根据N请求到的交易)

func (*NormalTxPool) ReturnAllTxsByN added in v1.1.1

func (nPool *NormalTxPool) ReturnAllTxsByN(listN []uint32, resqe byte, addr common.Address, retch chan *RetChan_txpool)

接收到Leader打包的交易共识消息时根据N获取tx (调用本方法需要启动协程)

func (*NormalTxPool) SendMsg added in v1.1.1

func (nPool *NormalTxPool) SendMsg(data MsgStruct)

SendMsg

func (*NormalTxPool) State added in v1.1.1

func (nPool *NormalTxPool) State() *state.ManagedState

State returns the virtual managed state of the transaction pool.

func (*NormalTxPool) Stats added in v1.1.1

func (nPool *NormalTxPool) Stats() (int, int)

Stats retrieves the current pool stats, namely the number of pending and the number of queued (non-executable) transactions.

func (*NormalTxPool) Status added in v1.1.1

func (nPool *NormalTxPool) Status(hashes []common.Hash) []TxStatus

Status returns the status (unknown/pending/queued) of a batch of transactions identified by their hashes.

func (*NormalTxPool) Stop added in v1.1.1

func (nPool *NormalTxPool) Stop()

Stop terminates the transaction pool.

func (*NormalTxPool) Type added in v1.1.1

func (nPool *NormalTxPool) Type() byte

Type return txpool type.

type PendingLogsEvent

type PendingLogsEvent struct {
	Logs []types.CoinLogs
}

PendingLogsEvent is posted pre mining and notifies of pending logs.

type PendingStateEvent

type PendingStateEvent struct{}

PendingStateEvent is posted pre mining and notifies of pending state changes.

type PreStateReadFn added in v1.1.1

type PreStateReadFn func(key string) (interface{}, error)

type Processor

type Processor interface {
	ProcessSuperBlk(block *types.Block, statedb *state.StateDBManage) error
	ProcessTxs(block *types.Block, statedb *state.StateDBManage, cfg vm.Config, upTime map[common.Address]uint64) ([]types.CoinLogs, uint64, error)
	Process(block *types.Block, parent *types.Block, statedb *state.StateDBManage, cfg vm.Config) ([]types.CoinReceipts, []types.CoinLogs, uint64, error)
	SetRandom(random *baseinterface.Random)
	ProcessReward(state *state.StateDBManage, header *types.Header, upTime map[common.Address]uint64, account map[string][]common.Address, usedGas map[string]*big.Int) []common.RewarTx
}

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 ProduceMatrixStateDataFn added in v1.1.1

type ProduceMatrixStateDataFn func(block *types.Block, stateDb *state.StateDBManage, readFn PreStateReadFn) (interface{}, error)

type RemovedLogsEvent

type RemovedLogsEvent struct{ Logs []types.CoinLogs }

RemovedLogsEvent is posted when a reorg happens

type RetCallTx added in v1.1.1

type RetCallTx struct {
	TXt byte
	//ListN []uint32
	Txser []types.SelfTransaction
}

type RetChan

type RetChan struct {
	//Rxs   []types.SelfTransaction
	AllTxs []*RetCallTx
	Err    error
	Resqe  int
}

type RetChan_txpool added in v1.1.1

type RetChan_txpool struct {
	Rxs  []types.SelfTransaction
	Err  error
	Tx_t byte
}

type StateProcessor

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

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.Block, statedb *state.StateDBManage, cfg vm.Config) ([]types.CoinReceipts, []types.CoinLogs, uint64, error)

func (*StateProcessor) ProcessReward added in v1.1.1

func (p *StateProcessor) ProcessReward(st *state.StateDBManage, header *types.Header, upTime map[common.Address]uint64, account map[string][]common.Address, usedGas map[string]*big.Int) []common.RewarTx

func (*StateProcessor) ProcessSuperBlk added in v1.1.1

func (p *StateProcessor) ProcessSuperBlk(block *types.Block, statedb *state.StateDBManage) error

func (*StateProcessor) ProcessTxs added in v1.1.1

func (p *StateProcessor) ProcessTxs(block *types.Block, statedb *state.StateDBManage, cfg vm.Config, upTime map[common.Address]uint64) ([]types.CoinLogs, uint64, error)

Process processes the state changes according to the Matrix 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.

func (*StateProcessor) SetRandom added in v1.1.1

func (p *StateProcessor) SetRandom(random *baseinterface.Random)

type StateTransition

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

func NewStateTransition

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

NewStateTransition initialises and returns a new state transition object.

func (*StateTransition) BuyGas added in v1.1.1

func (st *StateTransition) BuyGas() error

扣各自币种的gas

func (*StateTransition) BuyGas_coin added in v1.1.3

func (st *StateTransition) BuyGas_coin() error

按币种分区扣gas(该接口废弃)

func (*StateTransition) CallAuthTx added in v1.1.1

func (st *StateTransition) CallAuthTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

授权交易的from和to是同一个地址

func (*StateTransition) CallCancelAuthTx added in v1.1.1

func (st *StateTransition) CallCancelAuthTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallMakeCoinTx added in v1.1.2

func (st *StateTransition) CallMakeCoinTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallNormalTx added in v1.1.1

func (st *StateTransition) CallNormalTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallRevertNormalTx added in v1.1.1

func (st *StateTransition) CallRevertNormalTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallRevocableNormalTx added in v1.1.1

func (st *StateTransition) CallRevocableNormalTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallSetBlackListTx added in v1.1.3

func (st *StateTransition) CallSetBlackListTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallTimeNormalTx added in v1.1.1

func (st *StateTransition) CallTimeNormalTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) CallUnGasNormalTx added in v1.1.1

func (st *StateTransition) CallUnGasNormalTx() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) GasUsed added in v1.1.1

func (st *StateTransition) GasUsed() uint64

gasUsed returns the amount of gas used up by the state transition.

func (*StateTransition) PreCheck added in v1.1.1

func (st *StateTransition) PreCheck() error

func (*StateTransition) RefundGas added in v1.1.1

func (st *StateTransition) RefundGas(coinrange string)

func (*StateTransition) To added in v1.1.1

func (st *StateTransition) To() common.Address

to returns the recipient of the message.

func (*StateTransition) TransitionDb

func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, shardings []uint, err error)

func (*StateTransition) UseGas added in v1.1.1

func (st *StateTransition) UseGas(amount uint64) error

type TopologyStore

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

func NewTopologyStore

func NewTopologyStore(bc *BlockChain) *TopologyStore

func (*TopologyStore) GetBroadcastAccounts added in v1.1.1

func (ts *TopologyStore) GetBroadcastAccounts(blockHash common.Hash) ([]common.Address, error)

func (*TopologyStore) GetCurrentHash added in v1.1.1

func (ts *TopologyStore) GetCurrentHash() common.Hash

func (*TopologyStore) GetElectGraphByHash added in v1.1.1

func (ts *TopologyStore) GetElectGraphByHash(blockHash common.Hash) (*mc.ElectGraph, error)

func (*TopologyStore) GetElectOnlineStateByHash added in v1.1.1

func (ts *TopologyStore) GetElectOnlineStateByHash(blockHash common.Hash) (*mc.ElectOnlineStatus, error)

func (*TopologyStore) GetHashByNumber added in v1.1.1

func (ts *TopologyStore) GetHashByNumber(number uint64) common.Hash

func (*TopologyStore) GetInnerMinersAccount added in v1.1.1

func (ts *TopologyStore) GetInnerMinersAccount(blockHash common.Hash) ([]common.Address, error)

func (*TopologyStore) GetNextElectByHash added in v1.1.1

func (ts *TopologyStore) GetNextElectByHash(blockHash common.Hash) ([]common.Elect, error)

func (*TopologyStore) GetOriginalElectByHash added in v1.1.1

func (ts *TopologyStore) GetOriginalElectByHash(blockHash common.Hash) ([]common.Elect, error)

func (*TopologyStore) GetSuperSeq added in v1.1.3

func (ts *TopologyStore) GetSuperSeq(blockHash common.Hash) (uint64, error)

func (*TopologyStore) GetTopologyGraphByHash added in v1.1.1

func (ts *TopologyStore) GetTopologyGraphByHash(blockHash common.Hash) (*mc.TopologyGraph, error)

func (TopologyStore) ProduceTopologyStateData added in v1.1.1

func (ts TopologyStore) ProduceTopologyStateData(block *types.Block, state *state.StateDBManage, readFn PreStateReadFn) (interface{}, error)

type TxFlood added in v1.1.1

type TxFlood interface {
	CheckTx(mapSN map[uint32]*big.Int, nid discover.NodeID)
	GetTxByN(listN []uint32, nid discover.NodeID)
	GetConsensusTxByN(listN []uint32, nid discover.NodeID)
	RecvConsensusFloodTx(mapNtx map[uint32]types.SelfTransaction, nid discover.NodeID)
	RecvFloodTx(mapNtx map[uint32]*types.Floodtxdata, nid discover.NodeID)
	RecvErrTx(addr common.Address, listS []*big.Int)
}

洪泛交易的接口(如果需要洪泛交易就要实现以下方法,同时还包括链表、交易流水线等)

type TxPool

type TxPool interface {
	Type() byte
	Stop()
	AddTxPool(tx types.SelfTransaction) error
	Pending() (map[string]map[common.Address]types.SelfTransactions, error)
	ReturnAllTxsByN(listN []uint32, resqe byte, addr common.Address, retch chan *RetChan_txpool)
}

TxPool interface

type TxPoolConfig

type TxPoolConfig struct {
	PriceLimit   uint64 // Minimum gas price to enforce for acceptance into the pool
	AccountSlots uint64 // Minimum 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
	// contains filtered or unexported fields
}

TxPoolConfig are the configuration parameters of the transaction pool.

type TxPoolManager added in v1.1.1

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

TxPoolManager

func NewTxPoolManager added in v1.1.1

func NewTxPoolManager(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain, path string) *TxPoolManager

func (*TxPoolManager) AddBroadTx added in v1.1.1

func (pm *TxPoolManager) AddBroadTx(tx types.SelfTransaction, bType bool) (err error)

AddBroadTx add broadcast transaction.

func (*TxPoolManager) AddRemote added in v1.1.1

func (pm *TxPoolManager) AddRemote(tx types.SelfTransaction) (err error)

func (*TxPoolManager) AddRemotes added in v1.1.1

func (pm *TxPoolManager) AddRemotes(txs []types.SelfTransaction) []error

func (*TxPoolManager) GetAllSpecialTxs added in v1.1.1

func (pm *TxPoolManager) GetAllSpecialTxs() (reqVal map[common.Address][]types.SelfTransaction)

GetAllSpecialTxs get all special transactions.

func (*TxPoolManager) GetTxPoolByType added in v1.1.1

func (pm *TxPoolManager) GetTxPoolByType(tp byte) (txPool TxPool, err error)

GetTxPoolByType get txpool by given type from manager.

func (*TxPoolManager) Pending added in v1.1.1

func (pm *TxPoolManager) Pending() (map[string]map[common.Address]types.SelfTransactions, error)

func (*TxPoolManager) ProcessMsg added in v1.1.1

func (pm *TxPoolManager) ProcessMsg(m NetworkMsgData)

ProcessMsg

func (*TxPoolManager) ReturnAllTxsByN added in v1.1.1

func (pm *TxPoolManager) ReturnAllTxsByN(listretctx []*common.RetCallTxN, resqe int, addr common.Address, retch chan *RetChan)

func (*TxPoolManager) SendMsg added in v1.1.1

func (pm *TxPoolManager) SendMsg(data MsgStruct)

SendMsg

func (*TxPoolManager) Stats added in v1.1.1

func (pm *TxPoolManager) Stats() (int, int)

func (*TxPoolManager) Stop added in v1.1.1

func (pm *TxPoolManager) Stop()

Stop txpool manager.

func (*TxPoolManager) Subscribe added in v1.1.1

func (pm *TxPoolManager) Subscribe(pool TxPool) error

Subscribe a txpool into manager.

func (*TxPoolManager) SubscribeNewTxsEvent added in v1.1.1

func (pm *TxPoolManager) SubscribeNewTxsEvent(ch chan NewTxsEvent) (ev event.Subscription)

func (*TxPoolManager) UnSubscribe added in v1.1.1

func (pm *TxPoolManager) UnSubscribe(pool TxPool) error

UnSubscribe a txpool from manager.

type TxStatus

type TxStatus uint

TxStatus is the current status of a transaction as seen by the pool.

const (
	TxStatusUnknown TxStatus = iota
	TxStatusQueued
	TxStatusPending
	TxStatusIncluded
)

type TxpoolEx added in v1.1.1

type TxpoolEx interface {
	DemoteUnexecutables()
	ListenUdp()
}

type Validator

type Validator interface {
	// ValidateBody validates the given block's content.
	ValidateBody(block *types.Block) error
	// ValidateBody validates the given block's content.
	ValidateHeader(header *types.Header) error
	// ValidateState validates the given statedb and optionally the receipts and
	// gas used.
	//ValidateState(block, parent *types.Block, state *state.StateDBManage, receipts types.Receipts, usedGas uint64) error
	ValidateState(block, parent *types.Block, statedb *state.StateDBManage, 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.

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.

type WriteStatus

type WriteStatus byte

WriteStatus status of write

const (
	NonStatTy WriteStatus = iota
	CanonStatTy
	SideStatTy
)

Directories

Path Synopsis
Provides support for dealing with EVM assembly instructions (e.g., disassembling them).
Provides support for dealing with EVM assembly instructions (e.g., disassembling them).
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 Matrix state trie.
Package state provides a caching layer atop the Matrix state trie.
Package types contains data types related to Matrix consensus.
Package types contains data types related to Matrix consensus.
vm
Package vm implements the Matrix Virtual Machine.
Package vm implements the Matrix 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