Documentation
¶
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 MessageHandler
- 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 Watcher
Constants ¶
const ( ConfigNameOrgId = "org_id" ConfigNameRoot = "root" CertFreezeKey = "CERT_FREEZE" CertFreezeKeyPrefix = "freeze" CertRevokeKey = "CERT_CRL" CertRevokeKeyPrefix = "c_" // 不同策略的细粒度资源ID ResourceNameUnknown = "UNKNOWN" ResourceNameReadData = "READ" 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 = "ADMIN" RoleClient = "CLIENT" RoleLight = "LIGHT" RoleConsensus = "CONSENSUS" RoleCommonNode = "COMMON" RuleMajority = "MAJORITY" RuleAll = "ALL" RuleAny = "ANY" RuleSelf = "SELF" RuleForbidden = "FORBIDDEN" RuleDelete = "DELETE" )
const ( // 有证书许可 PermissionedWithCert string = "permissionedWithCert" // 使用公钥许可 PermissionedWithKey string = "permissionedWithKey" // 公钥 Public string = "public" // 身份(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 链配置密钥
const ( // 调用用户合约 max gas GasLimit = 1e10 // 1s TimeLimit = 1 * 1e9 // 每个交叉调用合约消耗的 Gas CallContractGasOnce = 1e5 // 交叉调用合约堆栈深度,必须小于 vm pool min size CallContractDepth = 5 EvmGasPrice = 1 EvmMaxStackDepth = 1024 // sdk调用链方法成功结果 ContractSdkSignalResultSuccess = 0 // sdk调用链方法成功结果 ContractSdkSignalResultFail = 1 // 合同状态长度的键和名称 DefaultMaxStateKeyLen = 1024 // 合同状态正则表达式的键和名称 DefaultStateRegex = "^[a-zA-Z0-9._-]+$" DefaultVersionLen = 64 DefaultVersionRegex = "^[a-zA-Z0-9._-]+$" ParametersKeyMaxCount = 50 // 每个参数的默认大小事务 (MB) DefaultParametersValueMaxSize = 10 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__" // 用户合约必须实现这种方法 ContractInitMethod = "init_contract" ContractUpgradeMethod = "upgrade" ContractAllocateMethod = "allocate" ContractDeallocateMethod = "deallocate" ContractRuntimeTypeMethod = "runtime_type" ContractEvmParamKey = "data" // 智能合约 sdk 常用的方法名 ContractMethodLogMessage = "LogMessage" ContractMethodSuccessResult = "SuccessResult" ContractMethodErrorResult = "ErrorResult" ContractMethodCallContract = "CallContract" ContractMethodCallContractLen = "CallContractLen" // kv ContractMethodGetStateLen = "GetStateLen" ContractMethodGetState = "GetState" ContractMethodPutState = "PutState" ContractMethodDeleteState = "DeleteState" // kv 迭代器 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(2210)
链的默认版本
Variables ¶
var (
// ConsensusDBName is used to store consensus data
ConsensusDBName = "consensus"
)
var (
ParametersValueMaxLength uint32
)
Functions ¶
func CheckTopicStr ¶
Types ¶
type AccessControlProvider ¶
type AccessControlProvider interface {
// GetHashAlg 返回访问控制提供者使用的哈希算法
GetHashAlg() string
// ValidateResourcePolicy 检查给定的资源策略是否有效
ValidateResourcePolicy(resourcePolicy *config.ResourcePolicy) bool
// LookUpPolicy 返回为给定资源名称配置的相应策略
LookUpPolicy(resourceName string) (*pbac.Policy, error)
// LookUpExceptionalPolicy 返回为给定资源名称配置的相应异常策略
LookUpExceptionalPolicy(resourceName string) (*pbac.Policy, error)
// CreatePrincipal 为一次性身份验证创建一个主体
CreatePrincipal(resourceName string, endorsements []*common.EndorsementEntry, message []byte) (Principal, error)
// Create Principal ForTarget Org 为“SELF”类型策略创建主体,需要在一次身份验证中将 SELF 转换为特定的组织 ID
CreatePrincipalForTargetOrg(resourceName string, endorsements []*common.EndorsementEntry, message []byte, targetOrigId string) (Principal, error)
// GetValidEndorsements 过滤所有背书条目并返回所有有效条目
GetValidEndorsements(principal Principal) ([]*common.EndorsementEntry, error)
// 验证 Principal 验证是否满足资源策略
VerifyPrincipal(principal Principal) (bool, error)
// NewMember 从 pb Member 创建一个成员
NewMember(member *pbac.Member) (Member, error)
// GetMemberStatus 获取会员的状态信息
GetMemberStatus(member *pbac.Member) (pbac.MemberStatus, error)
// VerifyRelatedMaterial 验证会员相关身份资料
VerifyRelatedMaterial(verifyType pbac.VerifyType, data []byte) (bool, error)
}
访问控制提供者管理策略和原则
type BlockCommitter ¶
区块提交者,将区块和读写集放入账本(DB)
type BlockProposer ¶
type BlockProposer interface {
// 启动提议者
Start() error
// 停止提议者
Stop() error
// 接收来自 txpool 模块的提议信号
OnReceiveTxPoolSignal(proposeSignal *txpool.TxPoolSignal)
// 接收信号指示节点是否是来自共识模块的提议者
OnReceiveProposeStatusChange(proposeStatus bool)
// 接收来自 maxbft 共识(Hotstuff)的信号并提出新区块
OnReceiveMaxBFTProposal(proposal *maxbft.BuildProposal)
}
区块提议者,当节点是共识提议者时生成新区块
type BlockVerifier ¶
type BlockVerifier interface {
// 验证块是否有效
VerifyBlock(block *common.Block, mode VerifyMode) error
//
VerifyBlockWithRwSets(block *common.Block, rwsets []*common.TxRWSet, mode VerifyMode) error
}
区块验证者,验证区块是否有效
type BlockchainStore ¶
type BlockchainStore interface {
StateSqlOperation
SysContractQuery
MemberQuery
//InitGenesis 初始化创世单元到数据库
InitGenesis(genesisBlock *store.BlockWithRWSet) error
// PutBlock 在原子操作中提交块和相应的 rwset
PutBlock(block *common.Block, txRWSets []*common.TxRWSet) error
// GetBlockByHash 返回一个给定哈希值的块,如果不存在则返回 nil
GetBlockByHash(blockHash []byte) (*common.Block, error)
// 如果黑色哈希存在,BlockExists 返回 true,如果不存在则返回 false
BlockExists(blockHash []byte) (bool, error)
// GetHeightByHash 返回一个给定哈希的块高度,如果不存在则返回 nil。
GetHeightByHash(blockHash []byte) (uint64, error)
// GetBlockHeaderByHeight 根据给定的高度返回块头,如果不存在则返回 nil。
GetBlockHeaderByHeight(height uint64) (*common.BlockHeader, error)
// GetBlock 根据块高度返回一个块,如果不存在则返回 nil。
GetBlock(height uint64) (*common.Block, error)
// GetLastConfigBlock 返回最后一个配置块。
GetLastConfigBlock() (*common.Block, error)
// GetLastChainConfig 返回最后一个链配置
GetLastChainConfig() (*configPb.ChainConfig, error)
// GetBlockByTx 返回一个包含 tx 的块。
GetBlockByTx(txId string) (*common.Block, error)
// GetBlockWithRWSets 返回一个块和给定块高度的相应 rwsets,如果不存在则返回 nil。
GetBlockWithRWSets(height uint64) (*store.BlockWithRWSet, error)
// GetTx 通过 txid 检索交易,如果不存在则返回 nil。
GetTx(txId string) (*common.Transaction, error)
// GetTxWithRWSet 返回 tx 并设置为 rw
GetTxWithRWSet(txId string) (*common.TransactionWithRWSet, error)
// GetTxInfoWithRWSet 返回 tx 和 tx 信息和 rw 集
GetTxInfoWithRWSet(txId string) (*common.TransactionInfoWithRWSet, error)
// GetTxWithInfo 获取 tx 和 tx 区块信息
GetTxWithInfo(txId string) (*common.TransactionInfo, error)
// 如果 tx 存在,TxExists 返回 true,如果不存在,则返回 false。
TxExists(txId string) (bool, error)
// 如果 tx 存在,则 TxExistsInFullDB 返回 true 和 db 中最新提交的块高度,如果不存在则返回 false 和 math.MaxUint64。
TxExistsInFullDB(txId string) (bool, uint64, error)
// TxExistsInIncrementDB 如果 tx 从 starHeight 到最新提交的块存在则返回 true,如果不存在则返回 false。
TxExistsInIncrementDB(txId string, startHeight uint64) (bool, error)
// GetTxInfoOnly 获取 tx 区块高度、时间戳、txindex
GetTxInfoOnly(txId string) (*commonPb.TransactionInfo, error)
// 已弃用,请使用 GetTxInfoOnly,通过 txid 检索事务高度,如果不存在则返回 nil。
GetTxHeight(txId string) (uint64, error)
// 已弃用,请使用GetTxInfoOnly,返回给定tx的确认时间
GetTxConfirmedTime(txId string) (int64, error)
// GetLastBlock 返回最后一个块
GetLastBlock() (*common.Block, error)
// ReadObject 返回给定合约名称和密钥的状态值,如果不存在则返回 nil。
ReadObject(contractName string, key []byte) ([]byte, error)
// SelectObject 返回一个迭代器,其中包含给定键范围之间的所有键值。startKey 包含在结果中,并且排除了限制。
SelectObject(contractName string, startKey []byte, limit []byte) (StateIterator, error)
// GetTxRWSet 为给定的 txId 返回一个 txRWSet,如果不存在则返回 nil。
GetTxRWSet(txId string) (*common.TxRWSet, error)
// GetTxRWSetsByHeight 返回区块对应的所有 rwsets,如果区块不存在则返回 nil
GetTxRWSetsByHeight(height uint64) ([]*common.TxRWSet, error)
// GetDBHandle 返回给定 dbName 的数据库句柄
GetDBHandle(dbName string) DBHandle
// GetArchivedPivot 返回存档的枢轴(包括此枢轴高度)
GetArchivedPivot() uint64
// ArchiveBlock 备份后的块
ArchiveBlock(archiveHeight uint64) error
// RestoreBlocks 从外部块数据中恢复块
RestoreBlocks(serializedBlocks [][]byte) error
// Close 关闭所有 store db 实例并释放 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 提供存储实例的句柄
type ChainConf ¶
type ChainConf interface {
// 初始化
Init() error
// 获取最新的链配置
ChainConfig() *config.ChainConfig
// 通过(blockHeight-1)获取chainconfig
GetChainConfigFromFuture(blockHeight uint64) (*config.ChainConfig, error)
// 通过 blockHeight 获取链配置
GetChainConfigAt(blockHeight uint64) (*config.ChainConfig, error)
// 获取节点列表
GetConsensusNodeIdList() ([]string, error)
// 插入块到数据库成功后的回调
CompleteBlock(block *common.Block) error
// 添加观察者
AddWatch(w Watcher)
// 添加虚拟机观察者
AddVmWatch(w VmWatcher)
}
ChainConf chainconf 接口
type ChainNodeInfo ¶
type ChainNodesInfoProvider ¶
type ChainNodesInfoProvider interface {
// GetChainNodesInfo 返回链的基节点信息列表
GetChainNodesInfo() ([]*ChainNodeInfo, error)
}
ChainNodesInfoProvider 提供链的基础节点信息列表
type ConsensusEngine ¶
type ConsensusExtendEngine ¶
type ConsensusExtendEngine interface {
ConsensusEngine
InitExtendHandler(handler ConsensusExtendHandler)
}
ConsensusExtendEngine 扩展引擎以达成共识
type ConsensusExtendHandler ¶
type ConsensusExtendHandler interface {
// CreateRWSet 为提议的块创建一个 RwSet
CreateRWSet(preBlkHash []byte, proposedBlock *consensuspb.ProposalBlock) error
// VerifyConsensusArgs 验证区块内包含的 DPoS RwSet 的内容
VerifyConsensusArgs(block *common.Block, blockTxRwSet map[string]*common.TxRWSet) error
// GetValidators 获取当前 epoch 的验证器
GetValidators() ([]string, error)
}
type ConsensusState ¶
type ContractWacsiCommon ¶
type ContractWacsiKV ¶
type ContractWacsiSQL ¶
type CoreEngine ¶
type CoreEngine interface {
Start()
Stop()
GetBlockCommitter() BlockCommitter
GetBlockVerifier() BlockVerifier
msgbus.Subscriber
GetMaxbftHelper() MaxbftHelper
}
type DBHandle ¶
type DBHandle interface {
// GetDbType returns db type
GetDbType() string
// Get 返回给定键的值,如果不存在则返回 nil
Get(key []byte) ([]byte, error)
// Put 保存键值
Put(key []byte, value []byte) error
// 如果给定键存在则返回 true,如果不存在则返回 false
Has(key []byte) (bool, error)
// Delete 删除给定的键
Delete(key []byte) error
// WriteBatch 在原子操作中写入批处理
WriteBatch(batch StoreBatcher, sync bool) error
// CompactRange 为给定的键范围压缩底层数据库。
CompactRange(start, limit []byte) error
// NewIteratorWithRange 返回一个迭代器,其中包含给定键范围之间的所有键值, start 包含在结果中,limit 被排除在外。
NewIteratorWithRange(start []byte, limit []byte) (Iterator, error)
// NewIteratorWithPrefix 返回一个迭代器,其中包含具有给定前缀的所有键值
NewIteratorWithPrefix(prefix []byte) (Iterator, error)
// GetWriteBatchSize 获取每次写入的批号
GetWriteBatchSize() uint64
Close() error
}
DBHandle 是数据库的句柄
type DPoS ¶
type DPoS interface {
// CreateDPoSRWSet 为提议的区块创建 DPoS 的 RwSet
CreateDPoSRWSet(preBlkHash []byte, proposedBlock *consensuspb.ProposalBlock) error
// VerifyConsensusArgs 验证区块内包含的 DPoS RwSet 的内容
VerifyConsensusArgs(block *common.Block, blockTxRwSet map[string]*common.TxRWSet) error
// GetValidators 获取当前 epoch 的验证器
GetValidators() ([]string, error)
}
type DirectMsgHandler ¶
DirectMsgHandler 处理从其他节点接收到的消息
type ExecOrderTxType ¶
type ExecOrderTxType int
const ( ExecOrderTxTypeNormal ExecOrderTxType = iota ExecOrderTxTypeIterator ExecOrderTxTypeChargeGas )
type Government ¶
type Government interface {
// 用于验证共识数据
Verify(consensusType consensuspb.ConsensusType, chainConfig *config.ChainConfig) error
GetGovernanceContract() (*consensuspb.GovernanceContract, error)
}
type Iterator ¶
type Iterator interface {
Next() bool
First() bool
Error() error
Key() []byte
Value() []byte
Release()
}
迭代器允许链代码对范围查询返回的一组 kev/值对进行迭代。
type KeyHistoryIterator ¶
type KeyHistoryIterator interface {
Next() bool
Value() (*store.KeyModification, error)
Release()
}
type LedgerCache ¶
type LedgerCache interface {
// 获取最新提交的区块
GetLastCommittedBlock() *common.Block
// 设置最新提交的块
SetLastCommittedBlock(b *common.Block)
// 返回当前块高度
CurrentHeight() (uint64, error)
}
在分类帐(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是 Perseus 链 的logger接口
type MaxbftHelper ¶
type MaxbftHelper interface {
// DiscardAboveHeight 删除大于baseHeight的块数据
DiscardAboveHeight(baseHeight uint64)
}
type Member ¶
type Member interface {
// GetMemberId 返回此成员的身份(非唯一性)
GetMemberId() string
// GetOrgId 返回此成员所属的组织 ID
GetOrgId() string
// GetRole 返回此成员的角色
GetRole() Role
// GetUid 返回此成员的身份(唯一)
GetUid() string
// 验证使用此成员验证某些消息的签名
Verify(hashType string, msg []byte, sig []byte) error
// GetMember 返回成员
GetMember() (*pbac.Member, error)
}
Member 是节点或用户的身份。
type MemberQuery ¶
type MemberQuery interface {
// GetMemberExtraData 按会员获取会员额外数据
GetMemberExtraData(member *accesscontrol.Member) (*accesscontrol.MemberExtraData, error)
}
MemberQuery查询成员信息
type MessageHandler ¶
type MessageHandler func(from string, msg []byte, msgType net.NetMessage_MessageType) error
type Net ¶
type Net interface {
// GetNodeUid 是节点的唯一 id
GetNodeUid() string
// InitPubSub 将使用给定的 chainId 和 maxMessageSize 初始化新的 PubSub 实例
InitPubSub(chainId string, maxMessageSize int) error
// Broadcast With ChainId 将向具有 pub-sub 服务的 PubSub Topic 广播一条消息,该 id 被赋予 chainId
BroadcastWithChainId(chainId string, topic string, netMsg []byte) error
// SubscribeWithChainId 将 PubSubMsgHandler 注册到具有 pub-sub 服务的 PubSubTopic,其中 id 被指定为 chainId
SubscribeWithChainId(chainId string, topic string, handler PubSubMsgHandler) error
// CancelSubscribeWithChainId 取消订阅具有 pub-sub 服务的 PubSubTopic,该服务的 id 被指定为 chainId
CancelSubscribeWithChainId(chainId string, topic string) error
// SendMsg 将消息发送到给定字符串的节点。
// msgFlag:是用于区分msg类型的标志。
SendMsg(chainId string, node string, msgFlag string, netMsg []byte) error
// DirectMsgHandle 向网络注册一个 DirectMsgHandler。
// msgFlag:是用于区分msg类型的标志。
DirectMsgHandle(chainId string, msgFlag string, handler DirectMsgHandler) error
// CancelDirectMsgHandle 注销 DirectMsgHandler。
// msgFlag:是用于区分msg类型的标志。
CancelDirectMsgHandle(chainId string, msgFlag string) error
// AddSeed 添加一个种子节点地址。
AddSeed(seed string) error
// RefreshSeeds 刷新种子节点地址列表。
RefreshSeeds(seeds []string) error
// SetChainCustomTrustRoots 设置链的自定义信任根。在证书权限模式下,
// 如果通过链的访问控制验证证书失败,证书将再次被自定义信任根池验证。
SetChainCustomTrustRoots(chainId string, roots [][]byte)
// ReVerifyPeers 将通过链的访问控制模块验证对等点的权限,其中 id 是给定的chainId。
ReVerifyPeers(chainId string)
// 当网络实例正在运行时,IsRunning 返回 true。
IsRunning() bool
// 启动本地网络。
Start() error
// 停止本地网络
Stop() error
// ChainNodesInfo 返回链的基节点信息列表,其中 id 是给定的chainId。
ChainNodesInfo(chainId string) ([]*ChainNodeInfo, error)
// GetNodeUidByCertId 返回映射到给定证书 id 的节点 uid。 如果未映射返回错误。
GetNodeUidByCertId(certId string) (string, error)
// AddAC 为撤销的验证器添加一个 AccessControlProvider。
AddAC(chainId string, ac AccessControlProvider)
// SetMsgPriority 设置 msg 标志的优先级。 如果禁用优先级控制,则为空操作。
SetMsgPriority(msgFlag string, priority uint8)
}
Net 是本地网络接口
type NetService ¶
type NetService interface {
// BroadcastMessage 向网络广播消息
BroadcastMessage(msg []byte, msgType net.NetMessage_MessageType) error
// Subscribe 注册一个 MessageHandler 进行订阅
Subscribe(msgType net.NetMessage_MessageType, handler MessageHandler) error
// CancelSubscribe 取消订阅
CancelSubscribe(msgType net.NetMessage_MessageType) error
// ConsensusBroadcastMessage 向共识节点广播消息
ConsensusBroadcastMessage(msg []byte, msgType net.NetMessage_MessageType) error
// ConsensusSubscribe 注册一个 MessageHandler 处理来自共识节点的 msg 以进行订阅
ConsensusSubscribe(msgType net.NetMessage_MessageType, handler MessageHandler) error
// CancelConsensusSubscribe 取消订阅
CancelConsensusSubscribe(msgType net.NetMessage_MessageType) error
// SendMessage 向任何节点发送消息
SendMessage(msg []byte, msgType net.NetMessage_MessageType, to ...string) error
// ReceiveMessage 注册一个 MessageHandler 来处理从其他节点接收到的 msg
ReceiveMessage(msgType net.NetMessage_MessageType, handler MessageHandler) error
// 启动网络服务
Start() error
// 停止网络服务
Stop() error
// GetNodeUidByCertId 返回映射到给定证书 id 的节点 uid。 如果未映射返回错误
GetNodeUidByCertId(certId string) (string, error)
// GetChainNodesInfoProvider 返回一个 ChainNodesInfoProvider 的实现。
GetChainNodesInfoProvider() ChainNodesInfoProvider
}
网络服务
type Principal ¶
type Principal interface {
// GetResourceName 返回验证的资源名称
GetResourceName() string
// GetEndorsement 返回验证的所有背书(签名)
GetEndorsement() []*common.EndorsementEntry
// GetMessage 返回验证的签名数据
GetMessage() []byte
// 如果验证是针对特定组织的,则 GetTargetOrgId 返回验证的目标组织 ID
GetTargetOrgId() string
}
主体包含与一次性验证相关的所有信息
type ProposalCache ¶
type ProposalCache interface {
// 清除建议的高度块。
ClearProposedBlockAt(height uint64)
// 获取特定高度的所有建议块
GetProposedBlocksAt(height uint64) []*common.Block
// 在当前共识高度获取具有特定区块哈希的提议区块。
GetProposedBlock(b *common.Block) (*common.Block, map[string]*common.TxRWSet, map[string][]*common.ContractEvent)
// 在生成或验证后,将 porposed 块设置为当前共识高度。
SetProposedBlock(b *common.Block, rwSetMap map[string]*common.TxRWSet, contractEventMap map[string][]*common.ContractEvent, selfProposed bool) error
// 获取由节点本身提议的提议块。
GetSelfProposedBlockAt(height uint64) *common.Block
// 通过块哈希和块高度获取建议的块
GetProposedBlockByHashAndHeight(hash []byte, height uint64) (*common.Block, map[string]*common.TxRWSet)
// 如果提议的块已缓存在当前共识高度,则返回。
HasProposedBlockAt(height uint64) bool
// 如果该节点作为提议者提议了一个块,则返回。
IsProposedAt(height uint64) bool
// 为了标记这个节点已经提议了一个区块作为提议者。
SetProposedAt(height uint64)
// 重置此节点的提议状态。
ResetProposedAt(height uint64)
// 除特定块外,删除高度建议的块。
KeepProposedBlock(hash []byte, height uint64) []*common.Block
// DiscardAboveHeight 删除大于baseHeight的块数据
DiscardAboveHeight(baseHeight uint64) []*common.Block
// ClearTheBlock 清除proposerCache中的特殊块
ClearTheBlock(block *common.Block)
}
缓存尚未提交的建议块
type PubSubMsgHandler ¶
PubSubMsgHandler 处理其他节点发布的消息
type RuntimeInstance ¶
type RuntimeInstance interface {
Invoke(contractId *common.Contract, method string, byteCode []byte, parameters map[string][]byte,
txContext TxSimContext, gasUsed uint64) (*common.ContractResult, ExecOrderTxType)
}
Runtime智能合约引擎运行时实例
type SigningMember ¶
type Snapshot ¶
type Snapshot interface {
// 获取用于虚拟机访问的数据库
GetBlockchainStore() BlockchainStore
// 从当前快照和上一个快照中读取密钥
GetKey(txExecSeq int, contractName string, key []byte) ([]byte, error)
// 调度完成后,从当前快照中获取读写集
GetTxRWSetTable() []*common.TxRWSet
// 调度完成后,从当前快照中获取结果
GetTxResultMap() map[string]*common.Result
// 获取快照的 exec seq
GetSnapshotSize() int
// 调度完成后,从当前快照中获取事务序列表
GetTxTable() []*common.Transaction
// GetSpecialTxTable 返回将按顺序执行的 specialTy 表
GetSpecialTxTable() []*common.Transaction
// 获取上一个快照
GetPreSnapshot() Snapshot
// 设置上一个快照
SetPreSnapshot(Snapshot)
// GetBlockHeight 返回当前块高度
GetBlockHeight() uint64
// GetBlockTimestamp 返回当前区块时间戳
GetBlockTimestamp() int64
// 获取当前快照的 Block Proposer
GetBlockProposer() *accesscontrol.Member
// 如果冲突依赖建立后事务可以添加到快照中
// 即使事务移交给虚拟机模块时发生异常,
// 事务仍然被打包到一个块中,但是事务的读写集是空的。
// 这种情况包括:
// 使用了 1 个错误的 txtype,
// 解析querypayload和transactpayload时出现2个参数错误,
// 3 虚拟机运行时抛出恐慌,
// 4个智能合约字节码主动抛出panic
// 这里的第二个bool参数表示是否发生了上述异常
ApplyTxSimContext(TxSimContext, ExecOrderTxType, bool, bool) (bool, int)
// 为所有已解决读写冲突依赖关系的事务构建一个 dag
BuildDAG(isSql bool) *common.DAG
// 如果快照被密封,则不会再向快照添加事务
IsSealed() bool
Seal()
}
快照是链式结构,保存了不在库中的块的读写缓存信息
type SnapshotManager ¶
type SnapshotManager interface {
// 在当前区块高度创建 ContractStore
NewSnapshot(prevBlock *common.Block, block *common.Block) Snapshot
// 提交区块后,通知快照清理
NotifyBlockCommitted(block *common.Block) error
}
用于管理链式快照的快照管理容器
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(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 不在事务中,直接查询状态数据库,返回一行结果
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
}
type StoreBatcher ¶
type StoreBatcher interface {
// Put 添加一个键值
Put(key []byte, value []byte)
// Delete 删除一个键和关联的值
Delete(key []byte)
// len 返回键值的数量
Len() int
// Merge 用于合并两个 StoreBatcher
Merge(batcher StoreBatcher)
// KV 返回键值映射
KVs() map[string][]byte
// SplitBatch 将其他 kv 拆分为更多 updateBatchs 按 batchCnt 划分
SplitBatch(batchCnt uint64) []StoreBatcher
// 按键获取值
Get(key []byte) ([]byte, error)
// 检查键值是否存在
Has(key []byte) bool
}
StoreBatcher 用于缓存原子操作中提交的键值
type StoreHelper ¶
type StoreHelper interface {
RollBack(*common.Block, BlockchainStore) error
BeginDbTransaction(BlockchainStore, string)
GetPoolCapacity() int
}
type SyncService ¶
type SyncService interface {
// 初始化同步服务器,同步服务器每广播时间广播当前区块高度
Start() error
// 停止同步服务器
Stop()
}
SyncServer 是同步区块链的服务器
type SysContractQuery ¶
type SysContractQuery interface {
GetContractByName(name string) (*commonPb.Contract, error)
GetContractBytecode(name string) ([]byte, error)
}
SysContractQuery 查询系统合约数据
type TxFilter ¶
type TxFilter interface {
GetHeight() uint64
SetHeight(height uint64)
Add(txId string) error
// 批量添加添加事务到过滤器,如果发生异常,记录并返回异常事务数组
Adds(txIds []string) error
IsExists(txId string, ruleType ...common.RuleType) (bool, error)
// ValidateRule 验证规则
ValidateRule(txId string, ruleType ...common.RuleType) error
IsExistsAndReturnHeight(txId string, ruleType ...common.RuleType) (bool, uint64, error)
AddsAndSetHeight(txId []string, height uint64) (result error)
Close()
}
type TxHistoryIterator ¶
type TxPool ¶
type TxPool interface {
// 开始启动 txPool 服务
Start() error
// 停止停止 txPool 服务
Stop() error
// AddTx 向 txPool 添加交易 Source 有 3 种类型(RPC/P2P/INTERNAL),针对不同类型的情况进行不同的检查
AddTx(tx *common.Transaction, source TxSource) error
// GetTxByTxId 通过 txId 从 txPool 中检索交易
GetTxByTxId(txId string) (tx *common.Transaction, inBlockHeight uint64)
// IsTxExistInPool 验证交易是否存在于 tx_pool
TxExists(tx *common.Transaction) bool
// GetTxsByTxIds 根据 txIds 从 tx 池中检索 tx。
// txsRet 如果交易在 tx 池中,它将在 txsRet 中返回。
// txsHeightRet 如果交易在 tx 池的待处理队列中,
// 返回交易进入区块时对应的区块高度,
// 如果交易在 tx 池的正常队列中,则 tx 高度为 0,
// 如果交易不在交易池中,则tx高度为-1。
GetTxsByTxIds(txIds []string) (txsRet map[string]*common.Transaction, txsHeightRet map[string]uint64)
// RetryAndRemove 在同一高度处理多个提议块内的事务,
// 以确保这些事务不丢失,重新添加不在本地节点上的有效 txs。在提交块中删除 txs。
RetryAndRemoveTxs(retryTxs []*common.Transaction, removeTxs []*common.Transaction)
// FetchTxBatch 从 tx 池中获取交易批次以生成新块
FetchTxBatch(blockHeight uint64) []*common.Transaction
// AddTxsToPendingCache 这些事务将被添加到缓存中以避免再次获取事务并重新填充到新块中。 因为 HotStuff 共识算法中的链确认规则。
AddTxsToPendingCache(txs []*common.Transaction, blockHeight uint64)
}
TxPool 管理待处理的交易并更新交易的当前状态(待处理的包、待处理的入库、待处理的重试等)
type TxScheduler ¶
type TxScheduler interface {
// 使用 DAG 将事务批次调度到一个块中
// 返回每个事务的结果(和读写集),无论执行成功、失败、超时。
// 对于跨合约调用,结果(和读写集)包括所有合约相关。
Schedule(block *common.Block, txBatch []*common.Transaction, snapshot Snapshot) (map[string]*common.TxRWSet, map[string][]*common.ContractEvent, error)
// 使用给定的 DAG 运行 VM,并返回结果。
SimulateWithDag(block *common.Block, snapshot Snapshot) (map[string]*common.TxRWSet, map[string]*common.Result, error)
// 停止调度程序并释放 VM 资源。
Halt()
}
TxScheduler 调度一个事务批次并返回一个带有 DAG 的块(可能不完整) TxScheduler 也可以使用给定的 DAG 运行 VM,并返回结果。 只能被 BlockProposer 调用 应该有多种实现和自适应模式
type TxSimContext ¶
type TxSimContext interface {
// 从缓存中获取key,将此操作记录到read set
Get(contractName string, key []byte) ([]byte, error)
// GetNoRecord 从状态中读取数据,但不记录到读取集中,仅用于框架
GetNoRecord(contractName string, key []byte) ([]byte, error)
// 将密钥放入缓存
Put(name string, key []byte, value []byte) error
// PutRecord 将 sql 状态放入缓存
PutRecord(contractName string, value []byte, sqlType SqlType)
// PutIntoReadSet 将 kv 放入读取集
PutIntoReadSet(contractName string, key []byte, value []byte)
// Del 从缓存中删除键
Del(name string, key []byte) error
// 选择键的范围查询[开始,限制)
Select(name string, startKey []byte, limit []byte) (StateIterator, error)
// GetHistoryIterForKey 查询合约中key的变更历史
GetHistoryIterForKey(contractName string, key []byte) (KeyHistoryIterator, error)
// CallContract 跨合约调用,返回(合约结果,使用的gas)
CallContract(contract *common.Contract, method string, byteCode []byte,
parameter map[string][]byte, gasUsed uint64, refTxType common.TxType) (
*common.ContractResult, ExecOrderTxType, common.TxStatusCode)
// GetCurrentResult 获取跨合约调用结果,缓存 len
GetCurrentResult() []byte
// GetTx 获取相关交易
GetTx() *common.Transaction
// GetBlockHeight 返回当前块高度
GetBlockHeight() uint64
// GetBlockTimestamp 返回当前区块时间戳
GetBlockTimestamp() int64
// 获取当前区块提议者
GetBlockProposer() *pbac.Member
// 获取 tx 结果
GetTxResult() *common.Result
// 设置发送结果
SetTxResult(*common.Result)
// 获取当前事务完成的读写集
GetTxRWSet(runVmSuccess bool) *common.TxRWSet
// 获取合约的创建者
GetCreator(namespace string) *pbac.Member
// 获取事务的调用者
GetSender() *pbac.Member
// 获取相关区块链存储实例句柄
GetBlockchainStore() BlockchainStore
// 获取权限控制服务
GetAccessControl() (AccessControlProvider, error)
// 获取组织服务
GetChainNodesInfoProvider() (ChainNodesInfoProvider, error)
// 事务的执行顺序,用于构造dag,表示事务调度时完成的事务个数
GetTxExecSeq() int
SetTxExecSeq(int)
// 深入获取交叉合约调用
GetDepth() int
SetIterHandle(index int32, iter interface{})
GetIterHandle(index int32) (interface{}, bool)
GetBlockVersion() uint32
// GetContractByName 按名称获取合约信息
GetContractByName(name string) (*common.Contract, error)
// GetContractBytecode 获取合约字节码
GetContractBytecode(name string) ([]byte, error)
}
模拟事务的执行上下文,为事务的读写提供缓存
type Verifier ¶
type Verifier interface {
Verify(consensusType consensus.ConsensusType, chainConfig *config.ChainConfig) error
}
验证者验证共识数据
type VerifyMode ¶
type VerifyMode int
const ( CONSENSUS_VERIFY VerifyMode = iota SYNC_VERIFY )
func (VerifyMode) String ¶
func (i VerifyMode) String() string
type VmInstancesManager ¶
type VmInstancesManager interface {
NewRuntimeInstance(txSimContext TxSimContext, chainId, method, codePath string, contract *common.Contract,
byteCode []byte, log Logger) (RuntimeInstance, error)
StartVM() error
StopVM() error
}
type VmManager ¶
type VmManager interface {
// GetAccessControl 获取 accessControl 管理策略和原则
GetAccessControl() AccessControlProvider
// GetChainNodesInfoProvider 获取 ChainNodesInfoProvider 提供链的基节点信息列表。
GetChainNodesInfoProvider() ChainNodesInfoProvider
// RunContract 根据contractId中的ContractName运行原生或用户合约,并调用指定函数
RunContract(contract *common.Contract, method string, byteCode []byte, parameters map[string][]byte,
txContext TxSimContext, gasUsed uint64, refTxType common.TxType) (
*common.ContractResult, ExecOrderTxType, common.TxStatusCode)
// 启动所有 vm 实例
Start() error
// 停止所有 vm 实例
Stop() error
}
VmManager 管理 vm 运行时
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