Documentation
¶
Overview ¶
Copyright (C) BABEC. All rights reserved.
SPDX-License-Identifier: Apache-2.0
Copyright (C) BABEC. All rights reserved.
SPDX-License-Identifier: Apache-2.0
define vm parameter and interface
Index ¶
- Constants
- Variables
- func CheckEventData(eventData []string) error
- func CheckKeyFieldStr(key string, field string) error
- func CheckTopicStr(topic string) error
- func GetKey(key []byte, field []byte) []byte
- func GetKeyStr(key string, field string) []byte
- type AccessControlProvider
- type BlockCommitter
- type BlockProposer
- type BlockVerifier
- type BlockchainStore
- type ChainConf
- type ChainNodeInfo
- type ChainNodesInfoProvider
- type ConsensusEngine
- type ContractWacsiCommon
- type ContractWacsiKV
- type ContractWacsiSQL
- type CoreEngine
- type DBHandle
- type DPoS
- type DirectMsgHandler
- type Government
- type HotStuffHelper
- type Iterator
- type KeyHistoryIterator
- type LedgerCache
- type Logger
- type Member
- type MsgHandler
- type NetService
- type NetType
- type Principal
- type ProposalCache
- type PubsubMsgHandler
- type Role
- type Rule
- type SigningMember
- type Snapshot
- type SnapshotManager
- type Spv
- type SqlDBHandle
- type SqlDBTransaction
- type SqlRow
- type SqlRows
- type SqlType
- type SqlVerifier
- type StateIterator
- type StateSqlOperation
- type StoreBatcher
- type SyncService
- type SysContractQuery
- type TxHistoryIterator
- type TxPool
- type TxScheduler
- type TxSimContext
- type TxSource
- type Verifier
- type VerifyMode
- type VmManager
- type VmWatcher
- type Watcher
Constants ¶
const ( ConfigNameOrgId = "org_id" ConfigNameRoot = "root" CertFreezeKey = "CERT_FREEZE" CertFreezeKeyPrefix = "freeze_" CertRevokeKey = "CERT_CRL" CertRevokeKeyPrefix = "c_" // fine-grained resource id for different policies ResourceNameUnknown = "UNKNOWN" ResourceNameReadData = "READ" ResourceNameWriteData = "WRITE" ResourceNameP2p = "P2P" ResourceNameConsensusNode = "CONSENSUS" ResourceNameAdmin = "ADMIN" ResourceNameUpdateConfig = "CONFIG" ResourceNameUpdateSelfConfig = "SELF_CONFIG" ResourceNameAllTest = "ALL_TEST" ResourceNameTxQuery = "query" ResourceNameTxTransact = "transaction" ResourceNamePrivateCompute = "PRIVATE_COMPUTE" ResourceNameArchive = "ARCHIVE" ResourceNameSubscribe = "SUBSCRIBE" RoleAdmin Role = "ADMIN" RoleClient Role = "CLIENT" RoleLight Role = "LIGHT" RoleConsensusNode Role = "CONSENSUS" RoleCommonNode Role = "COMMON" RuleMajority Rule = "MAJORITY" RuleAll Rule = "ALL" RuleAny Rule = "ANY" RuleSelf Rule = "SELF" RuleForbidden Rule = "FORBIDDEN" RuleDelete Rule = "DELETE" )
const ( TBFT_propose_timeout_key = "TBFT_propose_timeout" TBFT_propose_delta_timeout_key = "TBFT_propose_delta_timeout" TBFT_blocks_per_proposer = "TBFT_blocks_per_proposer" )
TBFT chain config keys
const ( TBFTAddtionalDataKey = "TBFTAddtionalDataKey" RAFTAddtionalDataKey = "RAFTAddtionalDataKey" )
TBFT data key in Block.AdditionalData.ExtraData
const ( GasLimit = 1e10 // invoke user contract max gas TimeLimit = 1 * 1e9 // 1s CallContractGasOnce = 1e5 // Gas consumed per cross call contract CallContractDepth = 5 // cross call contract stack depth, must less than vm pool min size EvmGasPrice = 1 EvmMaxStackDepth = 1024 ContractSdkSignalResultSuccess = 0 // sdk call chain method success result ContractSdkSignalResultFail = 1 // sdk call chain method success result DefaultStateLen = 64 // key & name for contract state length DefaultStateRegex = "^[a-zA-Z0-9._-]+$" // key & name for contract state regex DefaultVersionLen = 64 // key & name for contract state length DefaultVersionRegex = "^[a-zA-Z0-9._-]+$" // key & name for contract state regex ParametersKeyMaxCount = 50 // ParametersValueMaxLength = 1024 * 1024 TopicMaxLen = 255 EventDataMaxLen = 65535 EventDataMaxCount = 16 //ContractKey = ":K:" //ContractByteHeader = ":H:" //ContractByteCode = ":B:" //ContractVersion = ":V:" //ContractRuntimeType = ":R:" //ContractCreator = ":C:" //ContractFreeze = ":F:" //ContractRevoke = ":RV:" //ContractAddress = ":A:" ContractStoreSeparator = "#" // special parameters passed to contract ContractCreatorOrgIdParam = "__creator_org_id__" ContractCreatorRoleParam = "__creator_role__" ContractCreatorPkParam = "__creator_pk__" ContractSenderOrgIdParam = "__sender_org_id__" ContractSenderRoleParam = "__sender_role__" ContractSenderPkParam = "__sender_pk__" ContractBlockHeightParam = "__block_height__" ContractTxIdParam = "__tx_id__" ContractContextPtrParam = "__context_ptr__" // user contract must implement such method ContractInitMethod = "init_contract" ContractUpgradeMethod = "upgrade" ContractAllocateMethod = "allocate" ContractDeallocateMethod = "deallocate" ContractRuntimeTypeMethod = "runtime_type" ContractEvmParamKey = "data" // method name used by smart contract sdk // common ContractMethodLogMessage = "LogMessage" ContractMethodSuccessResult = "SuccessResult" ContractMethodErrorResult = "ErrorResult" ContractMethodCallContract = "CallContract" ContractMethodCallContractLen = "CallContractLen" // kv ContractMethodGetStateLen = "GetStateLen" ContractMethodGetState = "GetState" ContractMethodPutState = "PutState" ContractMethodDeleteState = "DeleteState" // kv iterator author:whang1234 ContractMethodKvIterator = "KvIterator" ContractMethodKvPreIterator = "KvPreIterator" ContractMethodKvIteratorHasNext = "KvIteratorHasNext" ContractMethodKvIteratorNextLen = "KvIteratorNextLen" ContractMethodKvIteratorNext = "KvIteratorNext" ContractMethodKvIteratorClose = "KvIteratorClose" // sql ContractMethodExecuteQuery = "ExecuteQuery" ContractMethodExecuteQueryOne = "ExecuteQueryOne" ContractMethodExecuteQueryOneLen = "ExecuteQueryOneLen" ContractMethodRSNext = "RSNext" ContractMethodRSNextLen = "RSNextLen" ContractMethodRSHasNext = "RSHasNext" ContractMethodRSClose = "RSClose" ContractMethodExecuteUpdate = "ExecuteUpdate" ContractMethodExecuteDdl = "ExecuteDDL" ContractMethodEmitEvent = "EmitEvent" // paillier ContractMethodGetPaillierOperationResult = "GetPaillierOperationResult" ContractMethodGetPaillierOperationResultLen = "GetPaillierOperationResultLen" PaillierOpTypeAddCiphertext = "AddCiphertext" PaillierOpTypeAddPlaintext = "AddPlaintext" PaillierOpTypeSubCiphertext = "SubCiphertext" PaillierOpTypeSubPlaintext = "SubPlaintext" PaillierOpTypeNumMul = "NumMul" // bulletproofs ContractMethodGetBulletproofsResult = "GetBulletproofsResult" ContractMethodGetBulletproofsResultLen = "GetBulletproofsResultLen" BulletProofsOpTypePedersenAddNum = "PedersenAddNum" BulletProofsOpTypePedersenAddCommitment = "PedersenAddCommitment" BulletProofsOpTypePedersenSubNum = "PedersenSubNum" BulletProofsOpTypePedersenSubCommitment = "PedersenSubCommitment" BulletProofsOpTypePedersenMulNum = "PedersenMulNum" BulletProofsVerify = "BulletproofsVerify" )
const DefaultBlockVersion = uint32(20) // default version of chain
Variables ¶
var (
// ConsensusDBName is used to store consensus data
ConsensusDBName = "consensus"
)
Functions ¶
func CheckEventData ¶
CheckEventTopicTableData verify event data
func CheckKeyFieldStr ¶
CheckKeyFieldStr verify param
Types ¶
type AccessControlProvider ¶
type AccessControlProvider interface {
// GetHashAlg return hash algorithm the access control provider uses
GetHashAlg() string
// ValidateResourcePolicy checks whether the given resource policy is valid
ValidateResourcePolicy(resourcePolicy *config.ResourcePolicy) bool
//LookUpPolicy returns corresponding policy configured for the given resource name
LookUpPolicy(resourceName string) (*pbac.Policy, error)
// CreatePrincipal creates a principal for one time authentication
CreatePrincipal(resourceName string, endorsements []*common.EndorsementEntry, message []byte) (Principal, error)
// CreatePrincipalForTargetOrg creates a principal for "SELF" type policy,
// which needs to convert SELF to a sepecific organization id in one authentication
CreatePrincipalForTargetOrg(resourceName string, endorsements []*common.EndorsementEntry, message []byte, targetOrgId string) (Principal, error)
// VerifyPrincipal verifies if the policy for the resource is met
VerifyPrincipal(principal Principal) (bool, error)
// NewMember creates a member from pb Member
NewMember(member *pbac.Member) (Member, error)
//GetMemberStatus get the status information of the member
GetMemberStatus(member *pbac.Member) (pbac.MemberStatus, error)
//VerifyRelatedMaterial verify the member's relevant identity material
VerifyRelatedMaterial(verifyType pbac.VerifyType, data []byte) (bool, error)
}
AccessControlProvider manages policies and principals.
type BlockCommitter ¶
type BlockCommitter interface {
// Put block into ledger(DB) after block verify. Invoke by consensus or sync module.
AddBlock(blk *common.Block) error
}
Block committer, put block and read write set into ledger(DB).
type BlockProposer ¶
type BlockProposer interface {
// Start proposer.
Start() error
// Stop proposer
Stop() error
// Receive propose signal from txpool module.
OnReceiveTxPoolSignal(proposeSignal *txpool.TxPoolSignal)
// Receive signal indicates if node is proposer from consensus module.
OnReceiveProposeStatusChange(proposeStatus bool)
// Receive signal from chained bft consensus(Hotstuff) and propose new block.
OnReceiveChainedBFTProposal(proposal *chainedbft.BuildProposal)
}
Block proposer, generate new block when node is consensus proposer.
type BlockVerifier ¶
type BlockVerifier interface {
// Verify if a block is valid
VerifyBlock(block *common.Block, mode VerifyMode) error
}
Block verifier, verify if a block is valid
type BlockchainStore ¶
type BlockchainStore interface {
StateSqlOperation
SysContractQuery
//InitGenesis 初始化创世单元到数据库
InitGenesis(genesisBlock *store.BlockWithRWSet) error
// PutBlock commits the block and the corresponding rwsets in an atomic operation
PutBlock(block *common.Block, txRWSets []*common.TxRWSet) error
// GetBlockByHash returns a block given it's hash, or returns nil if none exists.
GetBlockByHash(blockHash []byte) (*common.Block, error)
// BlockExists returns true if the black hash exist, or returns false if none exists.
BlockExists(blockHash []byte) (bool, error)
// GetHeightByHash returns a block height given it's hash, or returns nil if none exists.
GetHeightByHash(blockHash []byte) (uint64, error)
// GetBlockHeaderByHeight returns a block header by given it's height, or returns nil if none exists.
GetBlockHeaderByHeight(height uint64) (*common.BlockHeader, error)
// GetBlock returns a block given it's block height, or returns nil if none exists.
GetBlock(height uint64) (*common.Block, error)
// GetLastConfigBlock returns the last config block.
GetLastConfigBlock() (*common.Block, error)
//GetLastChainConfig return the last chain config
GetLastChainConfig() (*configPb.ChainConfig, error)
// GetBlockByTx returns a block which contains a tx.
GetBlockByTx(txId string) (*common.Block, error)
// GetBlockWithRWSets returns a block and the corresponding rwsets given
// it's block height, or returns nil if none exists.
GetBlockWithRWSets(height uint64) (*store.BlockWithRWSet, error)
// GetTx retrieves a transaction by txid, or returns nil if none exists.
GetTx(txId string) (*common.Transaction, error)
// TxExists returns true if the tx exist, or returns false if none exists.
TxExists(txId string) (bool, error)
// GetTxHeight retrieves a transaction height by txid, or returns nil if none exists.
GetTxHeight(txId string) (uint64, error)
// GetTxConfirmedTime returns the confirmed time for given tx
GetTxConfirmedTime(txId string) (int64, error)
// GetLastBlock returns the last block.
GetLastBlock() (*common.Block, error)
// ReadObject returns the state value for given contract name and key, or returns nil if none exists.
ReadObject(contractName string, key []byte) ([]byte, error)
// SelectObject returns an iterator that contains all the key-values between given key ranges.
// startKey is included in the results and limit is excluded.
SelectObject(contractName string, startKey []byte, limit []byte) (StateIterator, error)
// GetTxRWSet returns an txRWSet for given txId, or returns nil if none exists.
GetTxRWSet(txId string) (*common.TxRWSet, error)
// GetTxRWSetsByHeight returns all the rwsets corresponding to the block,
// or returns nil if zhe block does not exist
GetTxRWSetsByHeight(height uint64) ([]*common.TxRWSet, error)
// GetDBHandle returns the database handle for given dbName
GetDBHandle(dbName string) DBHandle
// GetArchivedPivot returns the archived pivot (include this pivot height)
GetArchivedPivot() uint64
// ArchiveBlock the block after backup
ArchiveBlock(archiveHeight uint64) error
//RestoreBlocks restore blocks from outside block data
RestoreBlocks(serializedBlocks [][]byte) error
// Close closes all the store db instances and releases any resources held by BlockchainStore
Close() error
//GetHistoryForKey 查询某合约中某个Key的变更历史
GetHistoryForKey(contractName string, key []byte) (KeyHistoryIterator, error)
//GetAccountTxHistory 查询一个账户的交易历史记录
GetAccountTxHistory(accountId []byte) (TxHistoryIterator, error)
//GetContractTxHistory 查询一个合约的调用交易历史记录
GetContractTxHistory(contractName string) (TxHistoryIterator, error)
}
BlockchainStore provides handle to store instances
type ChainConf ¶
type ChainConf interface {
Init() error // init
ChainConfig() *config.ChainConfig // get the latest chainconfig
GetChainConfigFromFuture(blockHeight uint64) (*config.ChainConfig, error) // get chainconfig by (blockHeight-1)
GetChainConfigAt(blockHeight uint64) (*config.ChainConfig, error) // get chainconfig by blockHeight
GetConsensusNodeIdList() ([]string, error) // get node list
CompleteBlock(block *common.Block) error // callback after insert block to db success
AddWatch(w Watcher) // add watcher
AddVmWatch(w VmWatcher) // add vm watcher
}
ChainConf chainconf interface
type ChainNodeInfo ¶
type ChainNodesInfoProvider ¶
type ChainNodesInfoProvider interface {
// GetChainNodesInfo return base node info list of chain.
GetChainNodesInfo() ([]*ChainNodeInfo, error)
}
ChainNodesInfoProvider provide base node info list of chain.
type ConsensusEngine ¶
type ContractWacsiCommon ¶
type ContractWacsiKV ¶
type ContractWacsiSQL ¶
type CoreEngine ¶
type CoreEngine interface {
Start()
Stop()
GetBlockCommitter() BlockCommitter
GetBlockVerifier() BlockVerifier
msgbus.Subscriber
//HotStuffHelper
GetHotStuffHelper() HotStuffHelper
}
type DBHandle ¶
type DBHandle interface {
// Get returns the value for the given key, or returns nil if none exists
Get(key []byte) ([]byte, error)
// Put saves the key-values
Put(key []byte, value []byte) error
// Has return true if the given key exist, or return false if none exists
Has(key []byte) (bool, error)
// Delete deletes the given key
Delete(key []byte) error
// WriteBatch writes a batch in an atomic operation
WriteBatch(batch StoreBatcher, sync bool) error
// CompactRange compacts the underlying DB for the given key range.
CompactRange(start, limit []byte) error
// NewIteratorWithRange returns an iterator that contains all the key-values between given key ranges
// start is included in the results and limit is excluded.
NewIteratorWithRange(start []byte, limit []byte) Iterator
// NewIteratorWithPrefix returns an iterator that contains all the key-values with given prefix
NewIteratorWithPrefix(prefix []byte) Iterator
Close() error
}
DBHandle is an handle to a db
type DPoS ¶
type DPoS interface {
// CreateDPoSRWSet Creates a RwSet for DPoS for the proposed block
CreateDPoSRWSet(preBlkHash []byte, proposedBlock *consensuspb.ProposalBlock) error
// VerifyConsensusArgs Verify the contents of the DPoS RwSet contained within the block
VerifyConsensusArgs(block *common.Block, blockTxRwSet map[string]*common.TxRWSet) error
// GetValidators Gets the validators for the current epoch
GetValidators() ([]string, error)
}
type DirectMsgHandler ¶
DirectMsgHandler handle the msg received from other node.
type Government ¶
type Government interface {
//used to verify consensus data
Verify(consensusType consensuspb.ConsensusType, chainConfig *config.ChainConfig) error
GetGovernanceContract() (*consensuspb.GovernanceContract, error)
}
type HotStuffHelper ¶
type HotStuffHelper interface {
// DiscardAboveHeight Delete blocks data greater than the baseHeight
DiscardAboveHeight(baseHeight uint64)
}
type Iterator ¶
type Iterator interface {
Next() bool
First() bool
Error() error
Key() []byte
Value() []byte
Release()
}
Iterator allows a chaincode to iterator over a set of kev/value pairs returned by range query.
type KeyHistoryIterator ¶
type KeyHistoryIterator interface {
Next() bool
Value() (*store.KeyModification, error)
Release()
}
type LedgerCache ¶
type LedgerCache interface {
// Get the latest committed block
GetLastCommittedBlock() *common.Block
// Set the latest committed block
SetLastCommittedBlock(b *common.Block)
// Return current block height
CurrentHeight() (uint64, error)
}
Cache the latest block in ledger(DB).
type Logger ¶
type Logger interface {
Debug(args ...interface{})
Debugf(format string, args ...interface{})
Debugw(msg string, keysAndValues ...interface{})
Error(args ...interface{})
Errorf(format string, args ...interface{})
Errorw(msg string, keysAndValues ...interface{})
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
Fatalw(msg string, keysAndValues ...interface{})
Info(args ...interface{})
Infof(format string, args ...interface{})
Infow(msg string, keysAndValues ...interface{})
Panic(args ...interface{})
Panicf(format string, args ...interface{})
Panicw(msg string, keysAndValues ...interface{})
Warn(args ...interface{})
Warnf(format string, args ...interface{})
Warnw(msg string, keysAndValues ...interface{})
DebugDynamic(getStr func() string)
InfoDynamic(getStr func() string)
}
Logger is logger interface of chainmaker.
type Member ¶
type Member interface {
// GetMemberId returns the identity of this member (non-uniqueness)
GetMemberId() string
// GetOrgId returns the organization id which this member belongs to
GetOrgId() string
// GetRole returns roles of this member
GetRole() Role
// GetUid returns the identity of this member (unique)
GetUid() string
// Verify verifies a signature over some message using this member
Verify(hashType string, msg []byte, sig []byte) error
// GetMember returns Member
GetMember() (*pbac.Member, error)
}
Member is the identity of a node or user.
type NetService ¶
type NetService interface {
// BroadcastMsg broadcast a msg to the net.
BroadcastMsg(msg []byte, msgType net.NetMsg_MsgType) error
// Subscribe register a MsgHandler for subscribe.
Subscribe(msgType net.NetMsg_MsgType, handler MsgHandler) error
// CancelSubscribe cancel subscribe.
CancelSubscribe(msgType net.NetMsg_MsgType) error
// ConsensusBroadcastMsg broadcast a msg to the consensus nodes.
ConsensusBroadcastMsg(msg []byte, msgType net.NetMsg_MsgType) error
// ConsensusSubscribe register a MsgHandler handle the msg from consensus nodes for subscribe.
ConsensusSubscribe(msgType net.NetMsg_MsgType, handler MsgHandler) error
// CancelConsensusSubscribe cancel subscribe.
CancelConsensusSubscribe(msgType net.NetMsg_MsgType) error
// SendMsg send msg to any nodes.
SendMsg(msg []byte, msgType net.NetMsg_MsgType, to ...string) error
// ReceiveMsg register a MsgHandler to handle the msg received from other node.
ReceiveMsg(msgType net.NetMsg_MsgType, handler MsgHandler) error
// Start the net service.
Start() error
// Stop the net service.
Stop() error
// GetNodeUidByCertId return node uid which mapped to the given cert id. If unmapped return error.
GetNodeUidByCertId(certId string) (string, error)
// GetChainNodesInfoProvider return a implementation of ChainNodesInfoProvider.
GetChainNodesInfoProvider() ChainNodesInfoProvider
}
NetService
type Principal ¶
type Principal interface {
// GetResourceName returns resource name of the verification
GetResourceName() string
// GetEndorsement returns all endorsements (signatures) of the verification
GetEndorsement() []*common.EndorsementEntry
// GetMessage returns signing data of the verification
GetMessage() []byte
// GetTargetOrgId returns target organization id of the verification if the verification is for a specific organization
GetTargetOrgId() string
}
Principal contains all information related to one time verification
type ProposalCache ¶
type ProposalCache interface {
// Clear proposed blocks with height.
ClearProposedBlockAt(height uint64)
// Get all proposed blocks at a specific height
GetProposedBlocksAt(height uint64) []*common.Block
// Get proposed block with specific block hash in current consensus height.
GetProposedBlock(b *common.Block) (*common.Block, map[string]*common.TxRWSet, map[string][]*common.ContractEvent)
// Set porposed block in current consensus height, after it's generated or verified.
SetProposedBlock(b *common.Block, rwSetMap map[string]*common.TxRWSet, contractEventMap map[string][]*common.ContractEvent, selfProposed bool) error
// Get proposed block that is proposed by node itself.
GetSelfProposedBlockAt(height uint64) *common.Block
// Get proposed block by block hash and block height
GetProposedBlockByHashAndHeight(hash []byte, height uint64) (*common.Block, map[string]*common.TxRWSet)
// Return if a proposed block has cached in current consensus height.
HasProposedBlockAt(height uint64) bool
// Return if this node has proposed a block as proposer.
IsProposedAt(height uint64) bool
// To mark this node has proposed a block as proposer.
SetProposedAt(height uint64)
// Reset propose status of this node.
ResetProposedAt(height uint64)
// Remove proposed block in height except the specific block.
KeepProposedBlock(hash []byte, height uint64) []*common.Block
// DiscardAboveHeight Delete blocks data greater than the baseHeight
DiscardAboveHeight(baseHeight uint64) []*common.Block
// ClearTheBlock clean the special block in proposerCache
ClearTheBlock(block *common.Block)
}
Cache proposed blocks that are not committed yet
type PubsubMsgHandler ¶
PubsubMsgHandler handle the msg published by other node.
type SigningMember ¶
type Snapshot ¶
type Snapshot interface {
// Get database for virtual machine access
GetBlockchainStore() BlockchainStore
//Read the key from the current snapshot and the previous snapshot
GetKey(txExecSeq int, contractName string, key []byte) ([]byte, error)
// After the scheduling is completed, get the read and write set from the current snapshot
GetTxRWSetTable() []*common.TxRWSet
// After the scheduling is completed, get the result from the current snapshot
GetTxResultMap() map[string]*common.Result
// Get exec seq for snapshot
GetSnapshotSize() int
// After the scheduling is completed, obtain the transaction sequence table from the current snapshot
GetTxTable() []*common.Transaction
// Get previous snapshot
GetPreSnapshot() Snapshot
// Set previous snapshot
SetPreSnapshot(Snapshot)
// Get Block Height for current snapshot
GetBlockHeight() uint64
// Get Block Proposer for current snapshot
GetBlockProposer() *accesscontrol.Member
// If the transaction can be added to the snapshot after the conflict dependency is established
// Even if an exception occurs when the transaction is handed over to the virtual machine module,
// the transaction is still packed into a block, but the read-write set of the transaction is left empty.
// This situation includes:
// 1 wrong txtype is used,
// 2 parameter error occurs when parsing querypayload and transactpayload,
// 3 virtual machine runtime throws panic,
// 4 smart contract byte code actively throws panic
// The second bool parameter here indicates whether the above exception has occurred
ApplyTxSimContext(TxSimContext, bool) (bool, int)
// Build a dag for all transactions that have resolved the read-write conflict dependencies
BuildDAG(isSql bool) *common.DAG
// If snapshot is sealed, no more transaction will be added into snapshot
IsSealed() bool
Seal()
}
Snapshot is a chain structure that saves the read and write cache information of the blocks that are not in the library
type SnapshotManager ¶
type SnapshotManager interface {
// Create ContractStore at the current block height
NewSnapshot(prevBlock *common.Block, block *common.Block) Snapshot
//Once the block is submitted, notify the snapshot to clean up
NotifyBlockCommitted(block *common.Block) error
}
Snapshot management container to manage chained snapshots
type SqlDBHandle ¶
type SqlDBHandle interface {
DBHandle
//CreateDatabaseIfNotExist 如果数据库不存在则创建对应的数据库,创建后将当前数据库设置为新数据库,返回是否已存在
CreateDatabaseIfNotExist(dbName string) (bool, error)
//CreateTableIfNotExist 根据一个对象struct,自动构建对应的sql数据库表
CreateTableIfNotExist(obj interface{}) error
//Save 直接保存一个对象到SQL数据库中
Save(value interface{}) (int64, error)
//ExecSql 执行指定的SQL语句,返回受影响的行数
ExecSql(sql string, values ...interface{}) (int64, error)
//QuerySingle 执行指定的SQL语句,查询单条数据记录,如果查询到0条,则返回nil,nil,如果查询到多条,则返回第一条
QuerySingle(sql string, values ...interface{}) (SqlRow, error)
//QueryMulti 执行指定的SQL语句,查询多条数据记录,如果查询到0条,则SqlRows.Next()直接返回false
QueryMulti(sql string, values ...interface{}) (SqlRows, error)
//BeginDbTransaction 开启一个数据库事务,并指定该事务的名字,并缓存其句柄,如果之前已经开启了同名的事务,则返回错误
BeginDbTransaction(txName string) (SqlDBTransaction, error)
//GetDbTransaction 根据事务的名字,获得事务的句柄,如果事务不存在,则返回错误
GetDbTransaction(txName string) (SqlDBTransaction, error)
//CommitDbTransaction 提交一个事务,并从缓存中清除该事务,如果找不到对应的事务,则返回错误
CommitDbTransaction(txName string) error
//RollbackDbTransaction 回滚一个事务,并从缓存中清除该事务,如果找不到对应的事务,则返回错误
RollbackDbTransaction(txName string) error
}
SqlDBHandle 对SQL数据库的操作方法
type SqlDBTransaction ¶
type SqlDBTransaction interface {
//ChangeContextDb 改变当前上下文所使用的数据库
ChangeContextDb(dbName string) error
//Save 直接保存一个对象到SQL数据库中
Save(value interface{}) (int64, error)
//ExecSql 执行指定的SQL语句,返回受影响的行数
ExecSql(sql string, values ...interface{}) (int64, error)
//QuerySingle 执行指定的SQL语句,查询单条数据记录,如果查询到0条,则返回nil,nil,如果查询到多条,则返回第一条
QuerySingle(sql string, values ...interface{}) (SqlRow, error)
//QueryMulti 执行指定的SQL语句,查询多条数据记录,如果查询到0条,则SqlRows.Next()直接返回false
QueryMulti(sql string, values ...interface{}) (SqlRows, error)
//BeginDbSavePoint 创建一个新的保存点
BeginDbSavePoint(savePointName string) error
//回滚事务到指定的保存点
RollbackDbSavePoint(savePointName string) error
}
SqlDBTransaction开启一个事务后,能在这个事务中进行的操作
type SqlRow ¶
type SqlRow interface {
//将这个数据的每个列赋值到dest指针对应的对象中
ScanColumns(dest ...interface{}) error
//将这个数据赋值到dest对象的属性中
//ScanObject(dest interface{}) error
//将这个数据转换为ColumnName为Key,Data为Value的Map中
Data() (map[string][]byte, error)
//判断返回的SqlRow是否为空
IsEmpty() bool
}
运行SQL查询后返回的一行数据,在获取这行数据时提供了ScanColumns,ScanObject和Data三种方法,但是三选一,调用其中一个就别再调另外一个。
type SqlRows ¶
type SqlRows interface {
//还有下一行
Next() bool
//将当前行这个数据的每个列赋值到dest指针对应的对象中
ScanColumns(dest ...interface{}) error
//将当前行这个数据赋值到dest对象的属性中
//ScanObject(dest interface{}) error
//将当前行这个数据转换为ColumnName为Key,Data为Value的Map中
Data() (map[string][]byte, error)
Close() error
}
运行SQL查询后返回的多行数据
type SqlVerifier ¶
type SqlVerifier interface {
//VerifyDDLSql 验证输入语句是不是DDL语句,是DDL则返回nil,不是则返回error
VerifyDDLSql(sql string) error
//VerifyDMLSql 验证输入的SQL语句是不是更新语句(insert、update、delete),是则返回nil,不是则返回error
VerifyDMLSql(sql string) error
//VerifyDQLSql 验证输入的语句是不是查询语句,是则返回nil,不是则返回error
VerifyDQLSql(sql string) error
}
SqlVerifier 在支持SQL语句操作状态数据库模式下,对合约中输入的SQL语句进行规则校验
type StateIterator ¶
type StateSqlOperation ¶
type StateSqlOperation interface {
//不在事务中,直接查询状态数据库,返回一行结果
QuerySingle(contractName, sql string, values ...interface{}) (SqlRow, error)
//不在事务中,直接查询状态数据库,返回多行结果
QueryMulti(contractName, sql string, values ...interface{}) (SqlRows, error)
//执行建表、修改表等DDL语句,不得在事务中运行
ExecDdlSql(contractName, sql, version string) error
//启用一个事务
BeginDbTransaction(txName string) (SqlDBTransaction, error)
//根据事务名,获得一个已经启用的事务
GetDbTransaction(txName string) (SqlDBTransaction, error)
//提交一个事务
CommitDbTransaction(txName string) error
//回滚一个事务
RollbackDbTransaction(txName string) error
}
type StoreBatcher ¶
type StoreBatcher interface {
// Put adds a key-value
Put(key []byte, value []byte)
// Delete deletes a key and associated value
Delete(key []byte)
// Len retrun the number of key-values
Len() int
// Merge used to merge two StoreBatcher
Merge(batcher StoreBatcher)
// KVs return the map of key-values
KVs() map[string][]byte
}
StoreBatcher used to cache key-values that commit in a atomic operation
type SyncService ¶
type SyncService interface {
//Init the sync server, and the sync server broadcast the current block height every broadcastTime
Start() error
//Stop the sync server
Stop()
}
SyncServer is the server to sync the blockchain
type SysContractQuery ¶
type SysContractQuery interface {
GetContractByName(name string) (*commonPb.Contract, error)
GetContractBytecode(name string) ([]byte, error)
}
SysContractQuery query system contract data
type TxHistoryIterator ¶
type TxPool ¶
type TxPool interface {
// Start start the txPool service
Start() error
// Stop stop the txPool service
Stop() error
// AddTx Add a transaction to the txPool
// There are three types of Source (RPC/P2P/INTERNAL), which different checks
// are performed for different types of cases
AddTx(tx *common.Transaction, source TxSource) error
// GetTxByTxId Retrieve the transaction by the txId from the txPool
GetTxByTxId(txId string) (tx *common.Transaction, inBlockHeight uint64)
// IsTxExistInPool verifies whether the transaction exists in the tx_pool
TxExists(tx *common.Transaction) bool
// GetTxsByTxIds Retrieves the tx by the txIds from the tx pool.
// txsRet if the transaction is in the tx pool, it will be returned in txsRet.
// txsHeightRet if the transaction is in the pending queue of the tx pool,
// the corresponding block height when the transaction entered the block is returned,
// if the transaction is in the normal queue of the tx pool, the tx height is 0,
// if the transaction is not in the transaction pool, the tx height is -1.
GetTxsByTxIds(txIds []string) (txsRet map[string]*common.Transaction, txsHeightRet map[string]uint64)
// RetryAndRemove Process transactions within multiple proposed blocks at the same height to
// ensure that these transactions are not lost, re-add valid txs which that are not on local node.
// remove txs in the commit block.
RetryAndRemoveTxs(retryTxs []*common.Transaction, removeTxs []*common.Transaction)
// FetchTxBatch Get the batch of transactions from the tx pool to generate new block
FetchTxBatch(blockHeight uint64) []*common.Transaction
// AddTxsToPendingCache These transactions will be added to the cache to avoid the transactions
// are fetched again and re-filled into the new block. Because Because of the chain confirmation
// rule in the HotStuff consensus algorithm.
AddTxsToPendingCache(txs []*common.Transaction, blockHeight uint64)
}
TxPool Manage pending transactions and update the current status of transactions (pending packages, pending warehousing, pending retries, etc.)
type TxScheduler ¶
type TxScheduler interface {
// schedule a transaction batch into a block with DAG
// Return result(and read write set) of each transaction, no matter it is executed OK, or fail, or timeout.
// For cross-contracts invoke, result(and read write set) include all contract relative.
Schedule(block *common.Block, txBatch []*common.Transaction, snapshot Snapshot) (map[string]*common.TxRWSet, map[string][]*common.ContractEvent, error)
// Run VM with a given DAG, and return results.
SimulateWithDag(block *common.Block, snapshot Snapshot) (map[string]*common.TxRWSet, map[string]*common.Result, error)
// To halt scheduler and release VM resources.
Halt()
}
TxScheduler schedules a transaction batch and returns a block (maybe not complete) with DAG TxScheduler also can run VM with a given DAG, and return results. It can only be called by BlockProposer Should have multiple implementations and adaptive mode
type TxSimContext ¶
type TxSimContext interface {
// Get key from cache
Get(name string, key []byte) ([]byte, error)
// Put key into cache
Put(name string, key []byte, value []byte) error
// PutRecord put sql state into cache
PutRecord(contractName string, value []byte, sqlType SqlType)
// Delete key from cache
Del(name string, key []byte) error
// Select range query for key [start, limit)
Select(name string, startKey []byte, limit []byte) (StateIterator, error)
// Cross contract call, return (contract result, gas used)
CallContract(contract *common.Contract, method string, byteCode []byte,
parameter map[string][]byte, gasUsed uint64, refTxType common.TxType) (*common.ContractResult, common.TxStatusCode)
// Get cross contract call result, cache for len
GetCurrentResult() []byte
// Get related transaction
GetTx() *common.Transaction
// Get related transaction
GetBlockHeight() uint64
// Get current block proposer
GetBlockProposer() *pbac.Member
// Get the tx result
GetTxResult() *common.Result
// Set the tx result
SetTxResult(*common.Result)
// Get the read and write set completed by the current transaction
GetTxRWSet(runVmSuccess bool) *common.TxRWSet
// Get the creator of the contract
GetCreator(namespace string) *pbac.Member
// Get the invoker of the transaction
GetSender() *pbac.Member
// Get related blockchain store
GetBlockchainStore() BlockchainStore
// Get access control service
GetAccessControl() (AccessControlProvider, error)
// Get organization service
GetChainNodesInfoProvider() (ChainNodesInfoProvider, error)
// The execution sequence of the transaction, used to construct the dag,
// indicating the number of completed transactions during transaction scheduling
GetTxExecSeq() int
SetTxExecSeq(int)
// Get cross contract call deep
GetDepth() int
SetStateSqlHandle(int32, SqlRows)
GetStateSqlHandle(int32) (SqlRows, bool)
SetStateKvHandle(int32, StateIterator)
GetStateKvHandle(int32) (StateIterator, bool)
GetBlockVersion() uint32
//GetContractByName get contract info by name
GetContractByName(name string) (*common.Contract, error)
//GetContractBytecode get contract bytecode
GetContractBytecode(name string) ([]byte, error)
}
The simulated execution context of the transaction, providing a cache for the transaction to read and write
type Verifier ¶
type Verifier interface {
Verify(consensusType consensus.ConsensusType, chainConfig *config.ChainConfig) error
}
Verifier verify consensus data
type VerifyMode ¶
type VerifyMode int
const ( CONSENSUS_VERIFY VerifyMode = iota SYNC_VERIFY )
func (VerifyMode) String ¶
func (i VerifyMode) String() string
type VmManager ¶
type VmManager interface {
// GetAccessControl get accessControl manages policies and principles
GetAccessControl() AccessControlProvider
// GetChainNodesInfoProvider get ChainNodesInfoProvider provide base node info list of chain.
GetChainNodesInfoProvider() ChainNodesInfoProvider
// RunContract run native or user contract according ContractName in contractId, and call the specified function
RunContract(contract *common.Contract, method string, byteCode []byte, parameters map[string][]byte,
txContext TxSimContext, gasUsed uint64, refTxType common.TxType) (*common.ContractResult, common.TxStatusCode)
}
VmManager manage vm runtime
type VmWatcher ¶
type VmWatcher interface {
Module() string // module
ContractNames() []string // watch the contract
Callback(contractName string, payloadBytes []byte) error // callback
}
VmWatcher native vm watcher
type Watcher ¶
type Watcher interface {
Module() string // module
Watch(chainConfig *config.ChainConfig) error // callback the chainconfig
}
Watcher chainconfig watcher
Source Files
¶
- access_control_interface.go
- cache_interface.go
- chainconf_interface.go
- consensus_interface.go
- core_interface.go
- dpos_interface.go
- government_interface.go
- hotstuff_helper.go
- logger_interface.go
- net_interface.go
- scheduler_interface.go
- snapshot_interface.go
- spv_interface.go
- store_interface.go
- sync_interface.go
- tx_pool_interface.go
- verifymode_string.go
- vm_interface.go