ledger

package
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2021 License: Apache-2.0 Imports: 31 Imported by: 0

README

ledger

账本逻辑实现。

Documentation

Index

Constants

View Source
const (
	// RootBlockVersion for version 1
	RootBlockVersion = 0
	// BlockVersion for version 1
	BlockVersion = 1
	// BlockCacheSize block counts in lru cache
	BlockCacheSize              = 100 //block counts in lru cache
	MaxBlockSizeKey             = "MaxBlockSize"
	ReservedContractsKey        = "ReservedContracts"
	ForbiddenContractKey        = "ForbiddenContract"
	NewAccountResourceAmountKey = "NewAccountResourceAmount"
	// Irreversible block height & slide window
	IrreversibleBlockHeightKey = "IrreversibleBlockHeight"
	IrreversibleSlideWindowKey = "IrreversibleSlideWindow"
	GasPriceKey                = "GasPrice"
	GroupChainContractKey      = "GroupChainContract"
	TransferFeeAmountKey       = "TransferFeeAmount"
)

Variables

View Source
var (
	// ErrBlockNotExist is returned when a block to query not exist in specific chain
	ErrBlockNotExist = errors.New("block not exist in this chain")
	// ErrTxNotFound is returned when a transaction to query not exist in confirmed table
	ErrTxNotFound = errors.New("transaction not found")
	// ErrTxDuplicated ...
	ErrTxDuplicated = errors.New("transaction duplicated in different blocks")
	// ErrRootBlockAlreadyExist is returned when two genesis block is checked in the process of confirming block
	ErrRootBlockAlreadyExist = errors.New("this ledger already has genesis block")
	// ErrTxNotConfirmed return tx not confirmed error
	ErrTxNotConfirmed = errors.New("transaction not confirmed")
	// NumCPU returns the number of CPU cores for the current system
	NumCPU = runtime.NumCPU()
)
View Source
var (
	// MemCacheSize baseDB memory level max size
	MemCacheSize = 128 //MB
	// FileHandlersCacheSize baseDB memory file handler cache max size
	FileHandlersCacheSize = 1024 //how many opened files-handlers cached
	// DisableTxDedup ...
	DisableTxDedup = false //whether disable dedup tx before confirm
)

Functions

func InvokeRequestFromJSON2Pb

func InvokeRequestFromJSON2Pb(jsonRequest []InvokeRequest) ([]*protos.InvokeRequest, error)

func MakeBlockID

func MakeBlockID(block *pb.InternalBlock) ([]byte, error)

MakeBlockID generate BlockID

func MakeMerkleTree

func MakeMerkleTree(txList []*pb.Transaction) [][]byte

MakeMerkleTree generate merkele-tree

func VerifyMerkle

func VerifyMerkle(block *pb.InternalBlock) error

VerifyMerkle

Types

type ConfirmStatus

type ConfirmStatus struct {
	Succ        bool  // 区块是否提交成功
	Split       bool  // 提交后是否发生了分叉
	Orphan      bool  // 是否是个孤儿节点
	TrunkSwitch bool  // 是否导致了主干分支切换
	Error       error //错误消息
}

ConfirmStatus block status

type GasPrice

type GasPrice struct {
	CpuRate  int64 `json:"cpu_rate" mapstructure:"cpu_rate"`
	MemRate  int64 `json:"mem_rate" mapstructure:"mem_rate"`
	DiskRate int64 `json:"disk_rate" mapstructure:"disk_rate"`
	XfeeRate int64 `json:"xfee_rate" mapstructure:"xfee_rate"`
}

GasPrice define gas rate for utxo

type GenesisBlock

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

GenesisBlock genesis block data structure

func NewGenesisBlock

func NewGenesisBlock(genesisCfg []byte) (*GenesisBlock, error)

NewGenesisBlock new a genesis block

func (*GenesisBlock) CalcAward

func (gb *GenesisBlock) CalcAward(blockHeight int64) *big.Int

CalcAward calc system award by block height

func (*GenesisBlock) GetConfig

func (gb *GenesisBlock) GetConfig() *RootConfig

GetConfig get config of genesis block

type InvokeRequest

type InvokeRequest struct {
	ModuleName   string            `json:"module_name" mapstructure:"module_name"`
	ContractName string            `json:"contract_name" mapstructure:"contract_name"`
	MethodName   string            `json:"method_name" mapstructure:"method_name"`
	Args         map[string]string `json:"args" mapstructure:"args"`
}

InvokeRequest define genesis reserved_contracts configure

type Ledger

type Ledger struct {
	ConfirmedTable kvdb.Database // 已确认的订单表

	GenesisBlock *GenesisBlock //创始块

	ConfirmBatch kvdb.Batch //新增区块
	// contains filtered or unexported fields
}

Ledger define data structure of Ledger

func CreateLedger

func CreateLedger(lctx *LedgerCtx, genesisCfg []byte) (*Ledger, error)

NewLedger create an empty ledger, if it already exists, open it directly

func OpenLedger

func OpenLedger(lctx *LedgerCtx) (*Ledger, error)

OpenLedger open ledger which already exists

func (*Ledger) AssignRewards

func (l *Ledger) AssignRewards(address string, blockAward *big.Int) *big.Int

//设置奖励分配

func (*Ledger) Close

func (l *Ledger) Close()

Close close an instance of ledger

func (*Ledger) ConfirmBlock

func (l *Ledger) ConfirmBlock(block *pb.InternalBlock, isRoot bool) ConfirmStatus

ConfirmBlock submit a block to ledger

func (*Ledger) Dump

func (l *Ledger) Dump() ([][]string, error)

Dump dump ledger structure, block height to blockid

func (*Ledger) ExistBlock

func (l *Ledger) ExistBlock(blockid []byte) bool

ExistBlock check if a block exists in the ledger

func (*Ledger) FindUndoAndTodoBlocks

func (l *Ledger) FindUndoAndTodoBlocks(curBlockid []byte, destBlockid []byte) ([]*pb.InternalBlock, []*pb.InternalBlock, error)

FindUndoAndTodoBlocks get blocks required to undo and todo range from curBlockid to destBlockid

func (*Ledger) FormatBlock

func (l *Ledger) FormatBlock(txList []*pb.Transaction,
	proposer []byte, ecdsaPk *ecdsa.PrivateKey,
	timestamp int64, curTerm int64, curBlockNum int64,
	preHash []byte, utxoTotal *big.Int) (*pb.InternalBlock, error)

FormatBlock format normal block

func (*Ledger) FormatFakeBlock

func (l *Ledger) FormatFakeBlock(txList []*pb.Transaction,
	proposer []byte, ecdsaPk *ecdsa.PrivateKey,
	timestamp int64, curTerm int64, curBlockNum int64,
	preHash []byte, utxoTotal *big.Int, blockHeight int64) (*pb.InternalBlock, error)

FormatFakeBlock format fake block for contract pre-execution without signing

func (*Ledger) FormatMinerBlock

func (l *Ledger) FormatMinerBlock(txList []*pb.Transaction,
	proposer []byte, ecdsaPk *ecdsa.PrivateKey,
	timestamp int64, curTerm int64, curBlockNum int64,
	preHash []byte, targetBits int32, utxoTotal *big.Int,
	qc *pb.QuorumCert, failedTxs map[string]string, blockHeight int64) (*pb.InternalBlock, error)

FormatMinerBlock format block for miner

func (*Ledger) FormatRootBlock

func (l *Ledger) FormatRootBlock(txList []*pb.Transaction) (*pb.InternalBlock, error)

FormatRootBlock format genesis block

func (*Ledger) GetBaseDB

func (l *Ledger) GetBaseDB() kvdb.Database

GetBaseDB get internal db instance

func (*Ledger) GetBranchInfo

func (l *Ledger) GetBranchInfo(targetBlockid []byte, targetBlockHeight int64) ([]string, error)

func (*Ledger) GetCommonParentBlockid

func (l *Ledger) GetCommonParentBlockid(branch1Blockid, branch2Blockid []byte) ([]byte, error)

func (*Ledger) GetForbiddenContract

func (l *Ledger) GetForbiddenContract() ([]*protos.InvokeRequest, error)

func (*Ledger) GetGasPrice

func (l *Ledger) GetGasPrice() *protos.GasPrice

func (*Ledger) GetGenesisBlock

func (l *Ledger) GetGenesisBlock() *GenesisBlock

GetGenesisBlock returns genesis block if it exists

func (*Ledger) GetGroupChainContract

func (l *Ledger) GetGroupChainContract() ([]*protos.InvokeRequest, error)

func (*Ledger) GetIrreversibleSlideWindow

func (l *Ledger) GetIrreversibleSlideWindow() int64

GetIrreversibleSlideWindow return irreversible slide window

func (*Ledger) GetLDB

func (l *Ledger) GetLDB() kvdb.Database

GetLDB returns the instance of underlying of kv db

func (*Ledger) GetMaxBlockSize

func (l *Ledger) GetMaxBlockSize() int64

GetMaxBlockSize return max block size

func (*Ledger) GetMeta

func (l *Ledger) GetMeta() *pb.LedgerMeta

GetMeta returns meta info of Ledger, such as genesis block ID, current block height, tip block ID

func (*Ledger) GetNewAccountResourceAmount

func (l *Ledger) GetNewAccountResourceAmount() int64

GetNewAccountResourceAmount return the resource amount of new an account

func (*Ledger) GetNoFee

func (l *Ledger) GetNoFee() bool

func (*Ledger) GetPendingBlock

func (l *Ledger) GetPendingBlock(blockID []byte) (*pb.InternalBlock, error)

GetPendingBlock get block from pending table

func (*Ledger) GetReservedContracts

func (l *Ledger) GetReservedContracts() ([]*protos.InvokeRequest, error)

func (*Ledger) GetTransferFeeAmount

func (l *Ledger) GetTransferFeeAmount() int64

获取创世块中设置的转账手续费

func (*Ledger) HandleFork

func (l *Ledger) HandleFork(oldTip []byte, newTip []byte, batchWrite kvdb.Batch) (*pb.InternalBlock, error)

func (*Ledger) HasTransaction

func (l *Ledger) HasTransaction(txid []byte) (bool, error)

HasTransaction check if a transaction exists in the ledger

func (*Ledger) IsTxInTrunk

func (l *Ledger) IsTxInTrunk(txid []byte) bool

IsTxInTrunk check if a transaction is in trunk by transaction ID

func (*Ledger) IsValidTx

func (l *Ledger) IsValidTx(idx int, tx *pb.Transaction, block *pb.InternalBlock) bool

IsValidTx valid transactions of coinbase in block

func (*Ledger) QueryBlock

func (l *Ledger) QueryBlock(blockid []byte) (*pb.InternalBlock, error)

QueryBlock query a block by blockID in the ledger

func (*Ledger) QueryBlockByHeight

func (l *Ledger) QueryBlockByHeight(height int64) (*pb.InternalBlock, error)

QueryBlockByHeight query block by height

func (*Ledger) QueryBlockByTxid

func (l *Ledger) QueryBlockByTxid(txid []byte) (*pb.InternalBlock, error)

QueryBlockByTxid query block by txid after it has confirmed

func (*Ledger) QueryBlockHeader

func (l *Ledger) QueryBlockHeader(blockid []byte) (*pb.InternalBlock, error)

QueryBlockHeader query a block by blockID in the ledger and return only block header

func (*Ledger) QueryTransaction

func (l *Ledger) QueryTransaction(txid []byte) (*pb.Transaction, error)

QueryTransaction query a transaction in the ledger and return it if exist

func (*Ledger) ReadBallotTable

func (l *Ledger) ReadBallotTable(user string, table *protos.CandidateRatio) error

读治理代币表

func (*Ledger) RemoveBlocks

func (l *Ledger) RemoveBlocks(fromBlockid []byte, toBlockid []byte, batch kvdb.Batch) error

func (*Ledger) RevokeVote

func (l *Ledger) RevokeVote(batch kvdb.Batch, user string, Args map[string]string) error

撤销投票写表

func (*Ledger) SavePendingBlock

func (l *Ledger) SavePendingBlock(block *pb.InternalBlock) error

SavePendingBlock put block into pending table

func (*Ledger) SetMeta

func (l *Ledger) SetMeta(meta *pb.LedgerMeta)

func (*Ledger) Truncate

func (l *Ledger) Truncate(utxovmLastID []byte) error

Truncate truncate ledger and set tipblock to utxovmLastID

func (*Ledger) UpdateBlockChainData

func (l *Ledger) UpdateBlockChainData(txid string, ptxid string, publickey string, sign string, height int64) error

UpdateBlockChainData modify tx which txid is txid

func (*Ledger) VerifyBlock

func (l *Ledger) VerifyBlock(block *pb.InternalBlock, logid string) (bool, error)

VerifyBlock verify block

func (*Ledger) VoteCandidateTable

func (l *Ledger) VoteCandidateTable(batch kvdb.Batch, user string, Args map[string]string) error

投票写表

func (*Ledger) WriteCandidateTable

func (l *Ledger) WriteCandidateTable(batch kvdb.Batch, user string, Args map[string]string) error

提案写表

func (*Ledger) WriteFreezeTable

func (l *Ledger) WriteFreezeTable(batch kvdb.Batch, amount string, user string, txid []byte) error

写入冻结表

func (*Ledger) WriteReCandidateTable

func (l *Ledger) WriteReCandidateTable(batch kvdb.Batch, user string, Args map[string]string) error

撤销提案写表

func (*Ledger) WriteThawTable

func (l *Ledger) WriteThawTable(batch kvdb.Batch, user string, desc []byte) error

申请解冻

type LedgerCtx

type LedgerCtx struct {
	// 基础上下文
	xctx.BaseCtx
	// 运行环境配置
	EnvCfg *xconf.EnvConf
	// 账本配置
	LedgerCfg *lconf.XLedgerConf
	// 链名
	BCName string
}

账本运行上下文环境

func NewLedgerCtx

func NewLedgerCtx(envCfg *xconf.EnvConf, bcName string) (*LedgerCtx, error)

type Predistribution

type Predistribution struct {
	Address string `json:"address"`
	Quota   string `json:"quota"`
}

func PredistributionTranslator

func PredistributionTranslator(predistribution []struct {
	Address string `json:"address"`
	Quota   string `json:"quota"`
}) []Predistribution

type RootConfig

type RootConfig struct {
	Version   string `json:"version"`
	Crypto    string `json:"crypto"`
	Kvengine  string `json:"kvengine"`
	Consensus struct {
		Type  string `json:"type"`
		Miner string `json:"miner"`
	} `json:"consensus"`
	Predistribution []struct {
		Address string `json:"address"`
		Quota   string `json:"quota"`
	}
	// max block size in MB
	MaxBlockSize string `json:"maxblocksize"`
	Period       string `json:"period"`
	NoFee        bool   `json:"nofee"`
	Award        string `json:"award"`
	AwardDecay   struct {
		HeightGap int64   `json:"height_gap"`
		Ratio     float64 `json:"ratio"`
	} `json:"award_decay"`
	GasPrice struct {
		CpuRate  int64 `json:"cpu_rate"`
		MemRate  int64 `json:"mem_rate"`
		DiskRate int64 `json:"disk_rate"`
		XfeeRate int64 `json:"xfee_rate"`
	} `json:"gas_price"`
	Decimals          string                 `json:"decimals"`
	GenesisConsensus  map[string]interface{} `json:"genesis_consensus"`
	ReservedContracts []InvokeRequest        `json:"reserved_contracts"`
	ReservedWhitelist struct {
		Account string `json:"account"`
	} `json:"reserved_whitelist"`
	ForbiddenContract InvokeRequest `json:"forbidden_contract"`
	// NewAccountResourceAmount the amount of creating a new contract account
	NewAccountResourceAmount int64 `json:"new_account_resource_amount"`
	// IrreversibleSlideWindow
	IrreversibleSlideWindow string `json:"irreversibleslidewindow"`
	// GroupChainContract
	GroupChainContract InvokeRequest `json:"group_chain_contract"`
	TransferFeeAmount  int64         `json:"transfer_fee_amount"` //转账手续费
}

RootConfig genesis block configure

func (*RootConfig) GetCryptoType

func (rc *RootConfig) GetCryptoType() string

func (*RootConfig) GetForbiddenContract

func (rc *RootConfig) GetForbiddenContract() ([]*protos.InvokeRequest, error)

func (*RootConfig) GetGasPrice

func (rc *RootConfig) GetGasPrice() *protos.GasPrice

GetGasPrice get gas rate for different resource(cpu, mem, disk and xfee)

func (*RootConfig) GetGenesisConsensus

func (rc *RootConfig) GetGenesisConsensus() (map[string]interface{}, error)

GetGenesisConsensus get consensus config of genesis block

func (*RootConfig) GetGroupChainContract

func (rc *RootConfig) GetGroupChainContract() ([]*protos.InvokeRequest, error)

func (*RootConfig) GetIrreversibleSlideWindow

func (rc *RootConfig) GetIrreversibleSlideWindow() int64

GetIrreversibleSlideWindow get irreversible slide window

func (*RootConfig) GetMaxBlockSizeInByte

func (rc *RootConfig) GetMaxBlockSizeInByte() (n int64)

GetMaxBlockSizeInByte get max block size in Byte

func (*RootConfig) GetNewAccountResourceAmount

func (rc *RootConfig) GetNewAccountResourceAmount() int64

GetNewAccountResourceAmount get the resource amount of new an account

func (*RootConfig) GetPredistribution

func (rc *RootConfig) GetPredistribution() []Predistribution

GetPredistribution return predistribution

func (*RootConfig) GetReservedContract

func (rc *RootConfig) GetReservedContract() ([]*protos.InvokeRequest, error)

GetReservedContract get default contract config of genesis block

func (*RootConfig) GetReservedWhitelistAccount

func (rc *RootConfig) GetReservedWhitelistAccount() string

GetReservedWhitelistAccount return reserved whitelist account

func (*RootConfig) GetTransferFeeAmount

func (rc *RootConfig) GetTransferFeeAmount() int64

添加获取手续费的函数

type TxDesc

type TxDesc struct {
	Args map[string]interface{} `json:"args"`
}

TxDesc is the description to running a contract

Jump to

Keyboard shortcuts

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