Documentation ¶
Overview ¶
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
Package protocol is a protocol package, which is base.
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 AuthType
- type BlockCommitter
- type BlockProposer
- type BlockVerifier
- type BlockchainStore
- type ChainConf
- type ChainNodeInfo
- type ChainNodesInfoProvider
- type ConsensusEngine
- type ConsensusExtendEngine
- type ConsensusExtendHandler
- type ConsensusState
- type ContractWacsiCommon
- type ContractWacsiKV
- type ContractWacsiSQL
- type CoreEngine
- type DBHandle
- type DPoS
- type DirectMsgHandler
- type ExecOrderTxType
- type Government
- type Iterator
- type KeyHistoryIterator
- type LedgerCache
- type Logger
- type MaxbftHelper
- type Member
- type MemberQuery
- type MsgHandler
- type Net
- type NetService
- type NetType
- type Principal
- type ProposalCache
- type PubSubMsgHandler
- type Role
- type Rule
- type RuntimeInstance
- 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 StoreHelper
- type SyncService
- type SysContractQuery
- type TxFilter
- type TxHistoryIterator
- type TxPool
- type TxScheduler
- type TxSimContext
- type TxSource
- type Verifier
- type VerifyMode
- type VmInstancesManager
- type VmManager
- type VmWatcher
- type Wacsi
- type WacsiWithGas
- type Watcher
Constants ¶
const ( // ConfigNameOrgId org_id ConfigNameOrgId = "org_id" // ConfigNameRoot root ConfigNameRoot = "root" // CertFreezeKey CERT_FREEZE CertFreezeKey = "CERT_FREEZE" // CertFreezeKeyPrefix freeze_ CertFreezeKeyPrefix = "freeze_" // CertRevokeKey CERT_CRL CertRevokeKey = "CERT_CRL" // CertRevokeKeyPrefix c_ CertRevokeKeyPrefix = "c_" 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" RoleContract Role = "CONTRACT" RuleMajority Rule = "MAJORITY" RuleAll Rule = "ALL" RuleAny Rule = "ANY" RuleSelf Rule = "SELF" RuleForbidden Rule = "FORBIDDEN" RuleDelete Rule = "DELETE" )
以下ac模块相关常量
const ( //PermissionedWithCert permissioned with certificate PermissionedWithCert string = "permissionedwithcert" //PermissionedWithKey permissioned with public key PermissionedWithKey string = "permissionedwithkey" // Public public key Public string = "public" // Identity (1.X PermissionedWithCert) Identity string = "identity" )
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 ( 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 DefaultMaxStateKeyLen = 1024 // 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 // DefaultParametersValueMaxSize = 10 // default size transaction's per parameter (MB) TopicMaxLen = 255 EventDataMaxLen = 65535 EventDataMaxCount = 16 ContractStoreSeparator = "#" 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__" ContractTxTimeStamp = "__tx_time_stamp__" ContractContextPtrParam = "__context_ptr__" ContractAddrTypeParam = "__addr_type__" ContractSenderTypeParam = "__sender_type__" ContractCreatorTypeParam = "__creator_type__" ContractCrossCallerParam = "__cross_caller__" ContractInitMethod = "init_contract" ContractUpgradeMethod = "upgrade" ContractAllocateMethod = "allocate" ContractDeallocateMethod = "deallocate" ContractRuntimeTypeMethod = "runtime_type" ContractEvmParamKey = "data" ContractMethodLogMessage = "LogMessage" ContractMethodSuccessResult = "SuccessResult" ContractMethodErrorResult = "ErrorResult" ContractMethodCallContract = "CallContract" ContractMethodCallContractLen = "CallContractLen" ContractMethodGetStateLen = "GetStateLen" ContractMethodGetState = "GetState" ContractMethodPutState = "PutState" ContractMethodDeleteState = "DeleteState" ContractMethodKvIterator = "KvIterator" ContractMethodKvPreIterator = "KvPreIterator" ContractMethodKvIteratorHasNext = "KvIteratorHasNext" ContractMethodKvIteratorNextLen = "KvIteratorNextLen" ContractMethodKvIteratorNext = "KvIteratorNext" ContractMethodKvIteratorClose = "KvIteratorClose" ContractMethodExecuteQuery = "ExecuteQuery" ContractMethodExecuteQueryOne = "ExecuteQueryOne" ContractMethodExecuteQueryOneLen = "ExecuteQueryOneLen" ContractMethodRSNext = "RSNext" ContractMethodRSNextLen = "RSNextLen" ContractMethodRSHasNext = "RSHasNext" ContractMethodRSClose = "RSClose" ContractMethodExecuteUpdate = "ExecuteUpdate" ContractMethodExecuteDdl = "ExecuteDDL" ContractMethodEmitEvent = "EmitEvent" ContractMethodGetPaillierOperationResult = "GetPaillierOperationResult" ContractMethodGetPaillierOperationResultLen = "GetPaillierOperationResultLen" PaillierOpTypeAddCiphertext = "AddCiphertext" PaillierOpTypeAddPlaintext = "AddPlaintext" PaillierOpTypeSubCiphertext = "SubCiphertext" PaillierOpTypeSubPlaintext = "SubPlaintext" PaillierOpTypeNumMul = "NumMul" ContractMethodGetBulletproofsResult = "GetBulletproofsResult" ContractMethodGetBulletproofsResultLen = "GetBulletproofsResultLen" BulletProofsOpTypePedersenAddNum = "PedersenAddNum" BulletProofsOpTypePedersenAddCommitment = "PedersenAddCommitment" BulletProofsOpTypePedersenSubNum = "PedersenSubNum" BulletProofsOpTypePedersenSubCommitment = "PedersenSubCommitment" BulletProofsOpTypePedersenMulNum = "PedersenMulNum" BulletProofsVerify = "BulletproofsVerify" )
constant data for VM
const DefaultBlockVersion = uint32(2030600) // default version of chain
DefaultBlockVersion default blockHeader.Version value
const (
SYNC_txHash_set_key = "SYNC_txHash_set_key"
)
SYNC_txHash_set_key additional data key
Variables ¶
var (
// ConsensusDBName is used to store consensus data
ConsensusDBName = "consensus"
)
var ( //ParametersValueMaxLength 参数Value允许的最大长度 ParametersValueMaxLength uint32 )
Functions ¶
func CheckEventData ¶
CheckEventData 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 //GetAllPolicy returns all policies GetAllPolicy() (map[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) //GetValidEndorsements filters all endorsement entries and returns all valid ones GetValidEndorsements(principal Principal, blockVersion uint32) ([]*common.EndorsementEntry, error) // VerifyPrincipalLT2330 verifies if the policy is met VerifyPrincipalLT2330(principal Principal, blockVersion uint32) (bool, error) // VerifyMsgPrincipal verifies if the policy for the msg is met VerifyMsgPrincipal(principal Principal, blockVersion uint32) (bool, error) // VerifyTxPrincipal verifies if the policy for the resource is met VerifyTxPrincipal(tx *common.Transaction, resourceId string, blockVersion uint32) (bool, error) VerifyMultiSignTxPrincipal( mInfo *syscontract.MultiSignInfo, blockVersion uint32) (syscontract.MultiSignStatus, error) // IsRuleSupportedByMultiSign verifies if the policy of resourceName supported by multi-sign IsRuleSupportedByMultiSign(resourceName string, blockVersion uint32) error // RefineEndorsements verifies endorsements RefineEndorsements(endorsements []*common.EndorsementEntry, msg []byte) []*common.EndorsementEntry // 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) GetAddressFromCache(pkBytes []byte) (string, crypto.PublicKey, error) GetCertFromCache(keyBytes []byte) ([]byte, error) // GetPayerFromCache get payer from cache GetPayerFromCache(key []byte) ([]byte, error) // SetPayerToCache set payer to cache SetPayerToCache(key []byte, value []byte) error }
AccessControlProvider manages policies and principals.
type BlockCommitter ¶
type BlockCommitter interface { // AddBlock Put block into ledger(DB) after block verify. Invoke by consensus or sync module. AddBlock(blk *common.Block) error }
BlockCommitter put block and read write set into ledger(DB).
type BlockProposer ¶
type BlockProposer interface { // Start proposer. Start() error // Stop proposer Stop() error // OnReceiveTxPoolSignal Receive propose signal from txpool module. OnReceiveTxPoolSignal(proposeSignal *txpool.TxPoolSignal) // OnReceiveProposeStatusChange Receive signal indicates if node is proposer from consensus module. OnReceiveProposeStatusChange(proposeStatus bool) // OnReceiveMaxBFTProposal Receive signal from maxbft consensus(Hotstuff) and propose new block. OnReceiveMaxBFTProposal(proposal *maxbft.BuildProposal) // ProposeBlock propose new block from maxbft consensus by sync call ProposeBlock(proposal *maxbft.BuildProposal) (*consensuspb.ProposalBlock, error) // OnReceiveRwSetVerifyFailTxs Receive signal from consensus and remove fails txs. OnReceiveRwSetVerifyFailTxs(rwSetVerifyFailTxs *consensuspb.RwSetVerifyFailTxs) }
BlockProposer 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 VerifyBlockSync(block *common.Block, mode VerifyMode) (*consensuspb.VerifyResult, error) VerifyBlockWithRwSets(block *common.Block, rwsets []*common.TxRWSet, mode VerifyMode) error }
BlockVerifier verify if a block is valid
type BlockchainStore ¶
type BlockchainStore interface { StateSqlOperation SysContractQuery MemberQuery //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 // its 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) //GetTxWithRWSet return tx and it's rw set GetTxWithRWSet(txId string) (*common.TransactionWithRWSet, error) //GetTxInfoWithRWSet return tx and tx info and rw set GetTxInfoWithRWSet(txId string) (*common.TransactionInfoWithRWSet, error) //GetTxWithInfo get tx and tx block information GetTxWithInfo(txId string) (*common.TransactionInfo, error) // TxExists returns true if the tx exist, or returns false if none exists. TxExists(txId string) (bool, error) // TxExistsInFullDB returns true and the latest committed block height in db if the tx exist, // or returns false and math.MaxUint64 if none exists. TxExistsInFullDB(txId string) (bool, uint64, error) // TxExistsInIncrementDB returns true if the tx exist from starHeight to the latest committed block, // or returns false if none exists. TxExistsInIncrementDB(txId string, startHeight uint64) (bool, error) // TxExistsInIncrementDBState returns // first return value is true if the tx exist from starHeight to the // latest committed block,or returns false if none exists. // second return value is true if inside the window or false if outside the window. TxExistsInIncrementDBState(txId string, startHeight uint64) (bool, bool, error) //GetTxInfoOnly get tx block height,timestamp, txindex GetTxInfoOnly(txId string) (*commonPb.TransactionInfo, error) //Deprecated, please use GetTxInfoOnly, retrieves a transaction height by txid, or returns nil if none exists. GetTxHeight(txId string) (uint64, error) //Deprecated, please use GetTxInfoOnly, returns the confirmed time for given tx GetTxConfirmedTime(txId string) (int64, error) // GetLastBlock returns the last block. GetLastBlock() (*common.Block, error) // GetLastHeight returns the last block height. GetLastHeight() (uint64, 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) // ReadObjects returns the state values for given contract name and keys ReadObjects(contractName string, keys [][]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) //Deprecated GetArchivedPivot() uint64 // GetArchiveStatus returns archive status GetArchiveStatus() (*store.ArchiveStatus, error) // 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 SetChainConfig(chainConf *config.ChainConfig) error // set new 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 // Deprecated: Use msgbus.PublishSync instead since version 2.3.0. CompleteBlock(block *common.Block) error // callback after insert block to db success // Deprecated: Use msgbus.Register instead since version 2.3.0. AddWatch(w Watcher) // add watcher // Deprecated: Use msgbus.Register instead since version 2.3.0. AddVmWatch(w VmWatcher) // add vm watcher }
ChainConf chainconf interface
type ChainNodeInfo ¶
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 ConsensusEngine interface { // Start the consensus engine. Start() error // Stop stops the consensus engine. Stop() error // ConsensusState get the consensus state ConsensusState }
ConsensusEngine consensus abstract engine
type ConsensusExtendEngine ¶ added in v2.2.0
type ConsensusExtendEngine interface { ConsensusEngine InitExtendHandler(handler ConsensusExtendHandler) }
ConsensusExtendEngine extend engine for consensus
type ConsensusExtendHandler ¶ added in v2.2.0
type ConsensusExtendHandler interface { // CreateRWSet Creates a RwSet for the proposed block CreateRWSet(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) }
ConsensusExtendHandler extend consensus handler
type ConsensusState ¶ added in v2.2.0
type ConsensusState interface { GetValidators() ([]string, error) GetLastHeight() uint64 GetConsensusStateJSON() ([]byte, error) }
ConsensusState get consensus state
type ContractWacsiCommon ¶
type ContractWacsiCommon interface { LogMessage() int32 SuccessResult() int32 ErrorResult() int32 CallContract() int32 }
ContractWacsiCommon 合约提供的公共接口
type ContractWacsiKV ¶
type ContractWacsiKV interface { ContractWacsiCommon GetState() int32 PutState() int32 DeleteState() int32 KvIterator() int32 KvPreIterator() int32 KvIteratorClose() int32 KvIteratorNext() int32 KvIteratorHasNext() int32 }
ContractWacsiKV 合约在支持KV模式下的接口
type ContractWacsiSQL ¶
type ContractWacsiSQL interface { ContractWacsiCommon ExecuteQuery() int32 ExecuteQueryOne() int32 RSHasNext() int32 RSNext() int32 RSClose() int32 ExecuteUpdate() int32 ExecuteDDL() int32 }
ContractWacsiSQL 合约支持SQL模式下的接口
type CoreEngine ¶
type CoreEngine interface { Start() Stop() GetBlockProposer() BlockProposer GetBlockCommitter() BlockCommitter GetBlockVerifier() BlockVerifier msgbus.Subscriber //MaxbftHelper GetMaxbftHelper() MaxbftHelper }
CoreEngine 核心引擎接口
type DBHandle ¶
type DBHandle interface { // GetDbType returns db type GetDbType() string // Get returns the value for the given key, or returns nil if none exists Get(key []byte) ([]byte, error) // GetKeys returns the values for the given keys concurrent GetKeys(keys [][]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, error) // NewIteratorWithPrefix returns an iterator that contains all the key-values with given prefix NewIteratorWithPrefix(prefix []byte) (Iterator, error) // GetWriteBatchSize get each write batch numbers GetWriteBatchSize() uint64 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) }
DPoS dpos共识相关接口
type DirectMsgHandler ¶
DirectMsgHandler handle the msg received from other node.
type ExecOrderTxType ¶ added in v2.1.1
type ExecOrderTxType int
ExecOrderTxType 执行排序类型
const ( ExecOrderTxTypeNormal ExecOrderTxType = iota ExecOrderTxTypeIterator ExecOrderTxTypeChargeGas )
ExecOrderTxType list
type Government ¶
type Government interface { // Verify used to verify consensus data Verify(consensusType consensuspb.ConsensusType, chainConfig *config.ChainConfig) error // GetGovernanceContract get GovernanceContract GetGovernanceContract() (*consensuspb.GovernanceContract, error) }
Government 治理接口
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 是否有下一个值 // @return bool Next() bool // Value Key的变更记录 // @return *store.KeyModification // @return error Value() (*store.KeyModification, error) // Release 释放迭代器的句柄 Release() }
KeyHistoryIterator 状态数据Key的历史记录查询返回的迭代器接口
type LedgerCache ¶
type LedgerCache interface { // GetLastCommittedBlock Get the latest committed block GetLastCommittedBlock() *common.Block // SetLastCommittedBlock Set the latest committed block SetLastCommittedBlock(b *common.Block) // CurrentHeight Return current block height CurrentHeight() (uint64, error) }
LedgerCache 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 MaxbftHelper ¶ added in v2.2.0
type MaxbftHelper interface { // DiscardBlocks Delete blocks data greater than the baseHeight DiscardBlocks(baseHeight uint64) }
MaxbftHelper MaxBFT共识的接口
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) //GetPk returns public key GetPk() crypto.PublicKey }
Member is the identity of a node or user.
type MemberQuery ¶ added in v2.1.0
type MemberQuery interface { // GetMemberExtraData get member extra data by member GetMemberExtraData(member *accesscontrol.Member) (*accesscontrol.MemberExtraData, error) }
MemberQuery query member information
type MsgHandler ¶
type MsgHandler func(from string, msg []byte, msgType net.NetMsg_MsgType) error
MsgHandler P2P网络消息处理Handler
type Net ¶ added in v2.1.0
type Net interface { // GetNodeUid is the unique id of the node. GetNodeUid() string // InitPubSub will init new PubSub instance with given chainId and maxMessageSize. InitPubSub(chainId string, maxMessageSize int) error // StopPubSub will stop the PubSub instance with chainId. StopPubSub(chainId string) // BroadcastWithChainId will broadcast a msg to a PubSubTopic with the pub-sub service which id is given chainId. BroadcastWithChainId(chainId string, topic string, netMsg []byte) error // SubscribeWithChainId register a PubSubMsgHandler to a PubSubTopic // with the pub-sub service which id is given chainId. SubscribeWithChainId(chainId string, topic string, handler PubSubMsgHandler) error // CancelSubscribeWithChainId cancel subscribe a PubSubTopic with the pub-sub service which id is given chainId. CancelSubscribeWithChainId(chainId string, topic string) error // SendMsg send msg to the node which id is given string. // msgFlag: is a flag used to distinguish msg type. SendMsg(chainId string, node string, msgFlag string, netMsg []byte) error // DirectMsgHandle register a DirectMsgHandler to the net. // msgFlag: is a flag used to distinguish msg type. DirectMsgHandle(chainId string, msgFlag string, handler DirectMsgHandler) error // CancelDirectMsgHandle unregister a DirectMsgHandler. // msgFlag: is a flag used to distinguish msg type. CancelDirectMsgHandle(chainId string, msgFlag string) error // AddSeed add a seed node addr. AddSeed(seed string) error // RefreshSeeds refresh the seed node addr list. RefreshSeeds(seeds []string) error // SetChainCustomTrustRoots set custom trust roots of chain. // In cert permission mode, if it is failed when verifying cert by access control of chains, // the cert will be verified by custom trust root pool again. SetChainCustomTrustRoots(chainId string, roots [][]byte) // ReVerifyPeers will verify permission of peers existed with the access control module of the chain // which id is the given chainId. ReVerifyPeers(chainId string) // IsRunning return true when the net instance is running. IsRunning() bool // Start the local net. Start() error // Stop the local net. Stop() error // ChainNodesInfo return base node info list of chain which id is the given chainId. ChainNodesInfo(chainId string) ([]*ChainNodeInfo, error) // GetNodeUidByCertId return node uid which mapped to the given cert id. If unmapped return error. GetNodeUidByCertId(certId string) (string, error) // AddAC add a AccessControlProvider for revoked validator. AddAC(chainId string, ac AccessControlProvider) // DeleteAC delete the AccessControlProvider for revoked validator. DeleteAC(chainId string) // SetMsgPriority set the priority of the msg flag. // If priority control disabled, it is no-op. SetMsgPriority(msgFlag string, priority uint8) }
Net is local net interface.
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 // CancelReceiveMsg unregister a MsgHandler to handle the msg received from other node. CancelReceiveMsg(msgType net.NetMsg_MsgType) 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 an implementation of ChainNodesInfoProvider. GetChainNodesInfoProvider() ChainNodesInfoProvider }
NetService P2P网络模块接口
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 { // ClearProposedBlockAt Clear proposed blocks with height. ClearProposedBlockAt(height uint64) // GetProposedBlocksAt Get all proposed blocks at a specific height GetProposedBlocksAt(height uint64) []*common.Block // GetProposedBlock 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) // SetProposedBlock 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 // GetSelfProposedBlockAt Get proposed block that is proposed by node itself. GetSelfProposedBlockAt(height uint64) *common.Block // GetProposedBlockByHashAndHeight Get proposed block by block hash and block height GetProposedBlockByHashAndHeight(hash []byte, height uint64) (*common.Block, map[string]*common.TxRWSet) // HasProposedBlockAt Return if a proposed block has cached in current consensus height. HasProposedBlockAt(height uint64) bool // IsProposedAt Return if this node has proposed a block as proposer. IsProposedAt(height uint64) bool // SetProposedAt To mark this node has proposed a block as proposer. SetProposedAt(height uint64) // ResetProposedAt Reset propose status of this node. ResetProposedAt(height uint64) // KeepProposedBlock Remove proposed block in height except the specific block. KeepProposedBlock(hash []byte, height uint64) []*common.Block // DiscardBlocks Delete blocks data greater than the baseHeight DiscardBlocks(baseHeight uint64) []*common.Block // ClearTheBlock clean the special block in proposerCache ClearTheBlock(block *common.Block) }
ProposalCache Cache proposed blocks that are not committed yet
type PubSubMsgHandler ¶ added in v2.1.0
PubSubMsgHandler handle the msg published by other node.
type RuntimeInstance ¶ added in v2.1.0
type RuntimeInstance interface { // start vm runtime with invoke, call “method” Invoke(contractId *common.Contract, method string, byteCode []byte, parameters map[string][]byte, txContext TxSimContext, gasUsed uint64) (*common.ContractResult, ExecOrderTxType) }
RuntimeInstance of smart contract engine runtime
type SigningMember ¶
type SigningMember interface { // Extends Member interface Member // Sign signs the message with the given hash type and returns signature bytes Sign(hashType string, msg []byte) ([]byte, error) }
SigningMember signer
type Snapshot ¶
type Snapshot interface { // GetBlockchainStore Get database for virtual machine access GetBlockchainStore() BlockchainStore // GetLastChainConfig return last chain config GetLastChainConfig() *config.ChainConfig // GetKey Read the key from the current snapshot and the previous snapshot GetKey(txExecSeq int, contractName string, key []byte) ([]byte, error) // GetKeys Read the key from the current snapshot and the previous snapshot GetKeys(txExecSeq int, keys []*vmPb.BatchKey) ([]*vmPb.BatchKey, error) // GetTxRWSetTable After the scheduling is completed, get the read and write set from the current snapshot GetTxRWSetTable() []*common.TxRWSet // GetTxResultMap After the scheduling is completed, get the result from the current snapshot GetTxResultMap() map[string]*common.Result // GetSnapshotSize Get exec seq for snapshot GetSnapshotSize() int // GetTxTable After the scheduling is completed, obtain the transaction sequence table from the current snapshot GetTxTable() []*common.Transaction // GetSpecialTxTable return specialTxTable which will be exec sequencially GetSpecialTxTable() []*common.Transaction // GetPreSnapshot Get previous snapshot GetPreSnapshot() Snapshot // SetPreSnapshot Set previous snapshot SetPreSnapshot(Snapshot) // GetBlockHeight returns current block height GetBlockHeight() uint64 // GetBlockFingerprint returns current block fingerprint GetBlockFingerprint() string // GetBlockTimestamp returns current block timestamp GetBlockTimestamp() int64 // GetBlockProposer returns Block Proposer for current snapshot GetBlockProposer() *accesscontrol.Member // ApplyTxSimContext 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, ExecOrderTxType, bool, bool) (bool, int) // BuildDAG Build a dag for all transactions that have resolved the read-write conflict dependencies // If txRWSetTable is nil, it uses snapshot.txRWSetTable. Otherwise use txRWSetTable in argument. BuildDAG(isSql bool, txRWSetTable []*common.TxRWSet) *common.DAG // IsSealed If snapshot is sealed, no more transaction will be added into snapshot IsSealed() bool // Seal set seal to true in atomic Seal() // ApplyBlock In the fast synchronization mode, the results pulled from other // nodes will be written to snapshot after the block verification passes ApplyBlock(block *common.Block, txRWSetMap map[string]*common.TxRWSet) }
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 { // NewSnapshot Create ContractStore at the current block height NewSnapshot(prevBlock *common.Block, block *common.Block) Snapshot // NotifyBlockCommitted Once the block is submitted, notify the snapshot to clean up NotifyBlockCommitted(block *common.Block) error // ClearSnapshot clean the snapshot when verify fail in tbft ClearSnapshot(block *common.Block) error // GetSnapshot Get Snapshot by block fingerPrint GetSnapshot(prevBlock *common.Block, block *common.Block) Snapshot }
SnapshotManager 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 // GetSqlDbType 获得SqlDBType字段的值 GetSqlDbType() string }
SqlDBHandle 对SQL数据库的操作方法
type SqlDBTransaction ¶
type SqlDBTransaction interface { // ChangeContextDb 改变当前上下文所使用的数据库 ChangeContextDb(dbName string) error // SaveBatch 直接保存一批对象到SQL数据库中 SaveBatch(values []interface{}) (int64, 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 回滚事务到指定的保存点 RollbackDbSavePoint(savePointName string) error }
SqlDBTransaction 开启一个事务后,能在这个事务中进行的操作
type SqlRow ¶
type SqlRow interface { // ScanColumns 将这个数据的每个列赋值到dest指针对应的对象中 ScanColumns(dest ...interface{}) error // Data 将这个数据转换为ColumnName为Key,Data为Value的Map中 Data() (map[string][]byte, error) // IsEmpty 判断返回的SqlRow是否为空 IsEmpty() bool }
SqlRow 运行SQL查询后返回的一行数据,在获取这行数据时提供了ScanColumns,ScanObject和Data三种方法,但是三选一,调用其中一个就别再调另外一个。
type SqlRows ¶
type SqlRows interface { // Next 还有下一行 Next() bool // ScanColumns 将当前行这个数据的每个列赋值到dest指针对应的对象中 ScanColumns(dest ...interface{}) error // Data 将当前行这个数据转换为ColumnName为Key,Data为Value的Map中 Data() (map[string][]byte, error) // Close 关闭sql.Rows连接 // @return error Close() error }
SqlRows 运行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 StateIterator interface { // Next 是否有下一个值 // @return bool Next() bool // Value 当前值的KV // @return *store.KV // @return error Value() (*store.KV, error) // Release 释放迭代器的句柄 Release() }
StateIterator 状态数据查询迭代器结果,在对状态数据进行前缀查询或者范围查询时返回
type StateSqlOperation ¶
type StateSqlOperation interface { // QuerySingle 不在事务中,直接查询状态数据库,返回一行结果 QuerySingle(contractName, sql string, values ...interface{}) (SqlRow, error) // QueryMulti 不在事务中,直接查询状态数据库,返回多行结果 QueryMulti(contractName, sql string, values ...interface{}) (SqlRows, error) // ExecDdlSql 执行建表、修改表等DDL语句,不得在事务中运行 ExecDdlSql(contractName, sql, version string) error // BeginDbTransaction 启用一个事务 BeginDbTransaction(txName string) (SqlDBTransaction, error) // GetDbTransaction 根据事务名,获得一个已经启用的事务 GetDbTransaction(txName string) (SqlDBTransaction, error) // CommitDbTransaction 提交一个事务 CommitDbTransaction(txName string) error // RollbackDbTransaction 回滚一个事务 RollbackDbTransaction(txName string) error // CreateDatabase 为新合约创建数据库 CreateDatabase(contractName string) error // DropDatabase 删除一个合约对应的数据库 DropDatabase(contractName string) error // GetContractDbName 获得一个合约对应的状态数据库名 GetContractDbName(contractName string) string }
StateSqlOperation 状态数据库的SQL操作
type StoreBatcher ¶
type StoreBatcher interface { // Put adds a key-value Put(key []byte, value []byte) // Delete deletes a key and associated value,value is be set to nil Delete(key []byte) // Remove key and value be removed Remove(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 // SplitBatch split other kvs to more updateBatchs division by batchCnt SplitBatch(batchCnt uint64) []StoreBatcher // Get value by key Get(key []byte) ([]byte, error) // Check key-value wether exist or not Has(key []byte) bool }
StoreBatcher used to cache key-values that commit in a atomic operation
type StoreHelper ¶ added in v2.2.0
type StoreHelper interface { RollBack(*common.Block, BlockchainStore) error BeginDbTransaction(BlockchainStore, string) GetPoolCapacity() int }
StoreHelper 存储抽象接口
type SyncService ¶
type SyncService interface { // Start Init the sync server, and the sync server broadcast the current block height every broadcastTime Start() error // Stop the sync server Stop() // ListenSyncToIdealHeight listen local block height has synced to ideal height ListenSyncToIdealHeight() <-chan struct{} // StopBlockSync syncing blocks from other nodes, but still process other nodes synchronizing blocks from itself StopBlockSync() // StartBlockSync start request service StartBlockSync() // GetState get sync state, with_others indicates whether to obtain the height state of other nodes known. // Return an error if failed. GetState(with_others bool) (*syncPb.SyncState, error) }
SyncService 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 TxFilter ¶ added in v2.2.2
type TxFilter interface { // GetHeight return the filtered non-existent block height for this transaction GetHeight() uint64 // SetHeight set the confirmed non-existent block height SetHeight(height uint64) // Add add txId to filter Add(txId string) error // Adds add transactions to the filter in batches, //and log and return an array of abnormal transactions if an exception occurs Adds(txIds []string) error // IsExists ruleType see chainmaker.org/chainmaker/protocol/v2/birdsnest.RulesType IsExists(txId string, ruleType ...birdsnest.RuleType) (bool, *txfilter.Stat, error) // ValidateRule validate rules ValidateRule(txId string, ruleType ...birdsnest.RuleType) error IsExistsAndReturnHeight(txId string, ruleType ...birdsnest.RuleType) (bool, uint64, *txfilter.Stat, error) AddsAndSetHeight(txId []string, height uint64) (result error) Close() }
TxFilter 交易过滤接口
type TxHistoryIterator ¶
type TxHistoryIterator interface { // Next 是否有下一个值 // @return bool Next() bool // Value 交易的历史记录 // @return *store.TxHistory // @return error Value() (*store.TxHistory, error) // Release 释放迭代器的句柄 Release() }
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 // FetchTxs Get some transactions from single or normal txPool by block height to generate new block. // return transactions. FetchTxs(blockHeight uint64) (txs []*common.Transaction) // FetchTxBatches Get some transactions from batch txPool by block height to generate new block. // return transactions table and batchId list. FetchTxBatches(blockHeight uint64) (batchIds []string, txsTable [][]*common.Transaction) // ReGenTxBatchesWithRetryTxs Generate new batches by retryTxs // and return new txsTable and batchIds of new batches for batch txPool, // then, put new batches into the pendingCache of pool // and retry old batches retrieved by the batchIds into the queue of pool. ReGenTxBatchesWithRetryTxs(blockHeight uint64, batchIds []string, retryTxs []*common.Transaction) ( newBatchIds []string, newTxsTable [][]*common.Transaction) // ReGenTxBatchesWithRemoveTxs Remove removeTxs in batches that retrieved by the batchIds // to create new batches for batch txPool and return new txsTable and batchIds of new batches // then put new batches into the pendingCache of pool // and delete old batches retrieved by the batchIds in pool. ReGenTxBatchesWithRemoveTxs(blockHeight uint64, batchIds []string, removeTxs []*common.Transaction) ( newBatchIds []string, newTxsTable [][]*common.Transaction) // RemoveTxsInTxBatches Remove removeTxs in batches that retrieved by the batchIds // to create new batches for batch txPool. // then, put new batches into the queue of pool // and delete old batches retrieved by the batchIds in pool. RemoveTxsInTxBatches(batchIds []string, removeTxs []*common.Transaction) // GetTxsByTxIds Retrieve transactions by the txIds from single or normal txPool, // and only return transactions it has. // txsRet is the transaction in the txPool, txsMis is the transaction not in the txPool. GetTxsByTxIds(txIds []string) (txsRet map[string]*common.Transaction, txsMis map[string]struct{}) // GetAllTxsByTxIds Retrieve all transactions by the txIds from single or normal txPool synchronously. // if there are some transactions lacked, it need to obtain them by height from the proposer. // if txPool get all transactions before timeout return txsRet, otherwise, return error. GetAllTxsByTxIds(txIds []string, proposerId string, height uint64, timeoutMs int) ( txsRet map[string]*common.Transaction, err error) // GetAllTxsByBatchIds Retrieve all transactions by the batchIds from batch txPool synchronously. // if there are some batches lacked, it need to obtain them by height from the proposer. // if txPool get all batches before timeout return txsRet, otherwise, return error. GetAllTxsByBatchIds(batchIds []string, proposerId string, height uint64, timeoutMs int) ( txsTable [][]*common.Transaction, err error) // AddTxsToPendingCache These transactions will be added to single or normal txPool to avoid the transactions // are fetched again and re-filled into the new block. Because of the chain confirmation // rule in the HotStuff consensus algorithm. AddTxsToPendingCache(txs []*common.Transaction, blockHeight uint64) // AddTxBatchesToPendingCache These transactions will be added to batch txPool to avoid the transactions // are fetched again and re-filled into the new block. Because of the chain confirmation // rule in the HotStuff consensus algorithm. AddTxBatchesToPendingCache(batchIds []string, blockHeight uint64) // RetryAndRemoveTxs Process transactions within multiple proposed blocks at the same height to // ensure that these transactions are not lost for single or normal txPool // re-add valid transactions which that are not on local node. // remove transactions in the commit block. RetryAndRemoveTxs(retryTxs []*common.Transaction, removeTxs []*common.Transaction) // RetryAndRemoveTxBatches Process batches within multiple proposed blocks at the same height to // ensure that these batches are not lost for batch txPool. // re-add valid batches to the queue of pool. // remove batches in the commit block. RetryAndRemoveTxBatches(retryBatchIds []string, removeBatchIds []string) // TxExists verifies whether the transaction exists in the txPool. TxExists(tx *common.Transaction) bool // GetPoolStatus Returns the max size of config transaction pool and common transaction pool, // the num of config transaction in queue and pendingCache, // and the the num of common transaction in queue and pendingCache. GetPoolStatus() (txPoolStatus *txpool.TxPoolStatus) // GetTxIdsByTypeAndStage Returns config or common txIds in different stage. // TxType may be TxType_CONFIG_TX, TxType_COMMON_TX, (TxType_CONFIG_TX|TxType_COMMON_TX) // TxStage may be TxStage_IN_QUEUE, TxStage_IN_PENDING, (TxStage_IN_QUEUE|TxStage_IN_PENDING) GetTxIdsByTypeAndStage(txType, txStage int32) (txIds []string) // GetTxsInPoolByTxIds Retrieve the transactions by the txIds from the txPool, // return transactions in the txPool and txIds not in txPool. // default query upper limit is 1w transaction, and error is returned if the limit is exceeded. GetTxsInPoolByTxIds(txIds []string) (txsRet []*common.Transaction, txsMis []string, err error) }
TxPool Manage pending transactions and update the current status of transactions (pending packages, pending warehousing, pending retries, etc.)
type TxScheduler ¶
type TxScheduler interface { // Schedule 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) // SimulateWithDag Run VM with a given DAG, and return results. SimulateWithDag(block *common.Block, snapshot Snapshot) ( map[string]*common.TxRWSet, map[string]*common.Result, error) // Halt 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, record this operation to read set Get(contractName string, key []byte) ([]byte, error) // GetKeys key from cache, record this operation to read set GetKeys(keys []*vmPb.BatchKey) ([]*vmPb.BatchKey, error) //GetNoRecord read data from state, but not record into read set, only used for framework GetNoRecord(contractName string, key []byte) ([]byte, error) // GetSnapshot get the snapshot in TxSimContext, just for calculating gas GetSnapshot() Snapshot // 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) // PutIntoReadSet put kv to readset PutIntoReadSet(contractName string, key []byte, value []byte) // Del 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) // GetHistoryIterForKey query the change history of a key in a contract GetHistoryIterForKey(contractName string, key []byte) (KeyHistoryIterator, error) // CallContract Cross contract call, return (contract result, gas used) CallContract(caller, contract *common.Contract, method string, byteCode []byte, parameter map[string][]byte, gasUsed uint64, refTxType common.TxType) ( *common.ContractResult, ExecOrderTxType, common.TxStatusCode) // GetCurrentResult Get cross contract call result, cache for len GetCurrentResult() []byte // GetTx get related transaction GetTx() *common.Transaction // GetBlockHeight returns current block height GetBlockHeight() uint64 // GetBlockFingerprint returns unique id for block GetBlockFingerprint() string // GetBlockTimestamp returns current block timestamp GetBlockTimestamp() int64 // GetBlockProposer returns current block proposer GetBlockProposer() *pbac.Member // GetTxResult returns the tx result GetTxResult() *common.Result // SetTxResult set the tx result SetTxResult(*common.Result) // GetTxRWSet returns the read and write set completed by the current transaction GetTxRWSet(runVmSuccess bool) *common.TxRWSet // GetCreator returns the creator of the contract GetCreator(namespace string) *pbac.Member // GetSender returns the invoker of the transaction GetSender() *pbac.Member // GetBlockchainStore returns related blockchain store GetBlockchainStore() BlockchainStore // GetLastChainConfig returns last chain config GetLastChainConfig() *config.ChainConfig // GetAccessControl returns access control service GetAccessControl() (AccessControlProvider, error) // GetChainNodesInfoProvider returns 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 SetIterHandle(index int32, iter interface{}) GetIterHandle(index int32) (interface{}, bool) GetBlockVersion() uint32 //GetContractByName get contract info by name GetContractByName(name string) (*common.Contract, error) //GetContractBytecode get contract bytecode GetContractBytecode(name string) ([]byte, error) // GetTxRWMapByContractName get the read-write map of the specified contract of the current transaction GetTxRWMapByContractName(contractName string) (map[string]*common.TxRead, map[string]*common.TxWrite) // GetCrossInfo get contract call link information GetCrossInfo() uint64 // HasUsed judge whether the specified common.RuntimeType has appeared in the previous depth // in the current cross-link HasUsed(runtimeType common.RuntimeType) bool // RecordRuntimeTypeIntoCrossInfo record the new contract call information to the top of crossInfo RecordRuntimeTypeIntoCrossInfo(runtimeType common.RuntimeType) // RemoveRuntimeTypeFromCrossInfo remove the top-level information from the crossInfo RemoveRuntimeTypeFromCrossInfo() // GetStrAddrFromPbMember calculate string address from pb Member GetStrAddrFromPbMember(pbMember *pbac.Member) (string, error) // SubtractGas charge gas used for this tx SubtractGas(gasUsed uint64) error // GetGasRemaining return gas remaining for this tx GetGasRemaining() uint64 }
TxSimContext 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
VerifyMode 区块验证模式
const ( //CONSENSUS_VERIFY 共识节点验证 CONSENSUS_VERIFY VerifyMode = iota //SYNC_VERIFY 同步节点验证 SYNC_VERIFY //PROPOSER_VERIFY 主节点验证 PROPOSER_VERIFY //SYNC_FILTER_VERIFY 同步节点带交易过滤的验证 SYNC_FILTER_VERIFY )
func (VerifyMode) String ¶
func (i VerifyMode) String() string
type VmInstancesManager ¶ added in v2.1.0
type VmInstancesManager interface { NewRuntimeInstance(txSimContext TxSimContext, chainId, method, codePath string, contract *common.Contract, byteCode []byte, log Logger) (RuntimeInstance, error) // StartVM Start vm StartVM() error // StopVM Stop vm StopVM() error BeforeSchedule(blockFingerprint string, blockHeight uint64) AfterSchedule(blockFingerprint string, blockHeight uint64) }
VmInstancesManager VM实例的管理接口
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, ExecOrderTxType, common.TxStatusCode) // Start all vm instance Start() error // Stop all vm instance Stop() error BeforeSchedule(blockFingerprint string, blockHeight uint64) AfterSchedule(blockFingerprint string, blockHeight uint64) }
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 Deprecated: Since version 2.3.0, it has been replaced by implementing msgBus.Subscriber interface.
type Wacsi ¶ added in v2.3.0
type Wacsi interface { // state operation PutState(requestBody []byte, contractName string, txSimContext TxSimContext) error GetState(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) DeleteState(requestBody []byte, contractName string, txSimContext TxSimContext) error // call other contract CallContract(caller *common.Contract, requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, gasUsed uint64, isLen bool) (*common.ContractResult, uint64, ExecOrderTxType, error) // result record SuccessResult(contractResult *common.ContractResult, data []byte) int32 ErrorResult(contractResult *common.ContractResult, data []byte) int32 // emit event EmitEvent(requestBody []byte, txSimContext TxSimContext, contractId *common.Contract, log Logger) (*common.ContractEvent, error) // paillier PaillierOperation(requestBody []byte, memory []byte, data []byte, isLen bool) ([]byte, error) // bulletproofs BulletProofsOperation(requestBody []byte, memory []byte, data []byte, isLen bool) ([]byte, error) // kv iterator KvIterator(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error KvPreIterator(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error KvIteratorHasNext(requestBody []byte, txSimContext TxSimContext, memory []byte) error KvIteratorNext(requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, contractName string, isLen bool) ([]byte, error) KvIteratorClose(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error // sql operation ExecuteQuery(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, chainId string) error ExecuteQueryOne(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, data []byte, chainId string, isLen bool) ([]byte, error) ExecuteUpdate(requestBody []byte, contractName string, method string, txSimContext TxSimContext, memory []byte, chainId string) error ExecuteDDL(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, method string) error RSHasNext(requestBody []byte, txSimContext TxSimContext, memory []byte) error RSNext(requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) RSClose(requestBody []byte, txSimContext TxSimContext, memory []byte) error }
Wacsi WebAssembly chainmaker system interface
type WacsiWithGas ¶ added in v2.3.3
type WacsiWithGas interface { LogMessage(requestBody []byte, txSimContext TxSimContext) int32 // state operation PutState(requestBody []byte, contractName string, txSimContext TxSimContext) error GetState(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) DeleteState(requestBody []byte, contractName string, txSimContext TxSimContext) error // call other contract CallContract(caller *common.Contract, requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, gasUsed uint64, isLen bool) (*common.ContractResult, uint64, ExecOrderTxType, error) // result record SuccessResult(contractResult *common.ContractResult, txSimContext TxSimContext, data []byte) int32 ErrorResult(contractResult *common.ContractResult, txSimContext TxSimContext, data []byte) int32 // emit event EmitEvent(requestBody []byte, txSimContext TxSimContext, contractId *common.Contract, log Logger) (*common.ContractEvent, error) // paillier PaillierOperation( requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) // bulletproofs BulletProofsOperation( requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) // kv iterator KvIterator(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error KvPreIterator(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error KvIteratorHasNext(requestBody []byte, txSimContext TxSimContext, memory []byte) error KvIteratorNext(requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, contractName string, isLen bool) ([]byte, error) KvIteratorClose(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte) error // sql operation ExecuteQuery(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, chainId string) error ExecuteQueryOne(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, data []byte, chainId string, isLen bool) ([]byte, error) ExecuteUpdate(requestBody []byte, contractName string, method string, txSimContext TxSimContext, memory []byte, chainId string) error ExecuteDDL(requestBody []byte, contractName string, txSimContext TxSimContext, memory []byte, method string) error RSHasNext(requestBody []byte, txSimContext TxSimContext, memory []byte) error RSNext(requestBody []byte, txSimContext TxSimContext, memory []byte, data []byte, isLen bool) ([]byte, error) RSClose(requestBody []byte, txSimContext TxSimContext, memory []byte) error }
WacsiWithGas WebAssembly chainmaker system interface
type Watcher ¶
type Watcher interface { Module() string // module Watch(chainConfig *config.ChainConfig) error // callback the chainconfig }
Watcher chainconfig watcher Deprecated: Since version 2.3.0, it has been replaced by implementing msgBus.Subscriber interface.
Source Files ¶
- access_control_interface.go
- cache_interface.go
- chainconf_interface.go
- consensus_interface.go
- core_interface.go
- dpos_interface.go
- government_interface.go
- logger_interface.go
- maxbft_helper.go
- net_interface.go
- scheduler_interface.go
- snapshot_interface.go
- spv_interface.go
- store_interface.go
- sync_interface.go
- tx_filiter_interface.go
- tx_pool_interface.go
- verifymode_string.go
- vm_interface.go