xuperchain源码分析-核心数据结构-爱代码爱编程
- XChainCore ,保存区块链所有核心数据信息
type XChainCore struct {
con *consensus.PluggableConsensus
Ledger *ledger.Ledger
Utxovm *utxo.UtxoVM
P2pSvr p2p_base.P2PServer
LedgerKeeper *LedgerKeeper
bcname string
log log.Logger
status int
privateKey *ecdsa.PrivateKey
publicKey *ecdsa.PublicKey
address []byte
award string
nodeMode string
CryptoClient crypto_base.CryptoClient
Speed *probe.SpeedCalc
// post_cache map[string] bool
stopFlag bool
proposal *proposal.Proposal
// isCoreMiner if current node is one of the core miners
isCoreMiner bool
// enable core peer connection or not
coreConnection bool
// if failSkip is false, you will execute loop of walk, or just only once walk
failSkip bool
// add a lru cache of tx gotten for xchaincore
txidCache *cache.Cache
txidCacheExpiredTime time.Duration
enableCompress bool
pruneOption config.PruneOption
// cache for duplicate block message
msgCache *common.LRUCache
blockBroadcaseMode uint8
// group chain involved
groupChain GroupChainRegister
}
- XChainMG,管理多条平行链,使用map结构存储chains
type XChainMG struct {
Log log.Logger
Cfg *config.NodeConfig
P2pSvr p2p_base.P2PServer
// msgChan is the message subscribe from net
msgChan chan *xuper_p2p.XuperMessage
chains *sync.Map
rootKernel *kernel.Kernel
datapath string
Ukeys *sync.Map //address -> scrkey
Speed *probe.SpeedCalc
Quit chan struct{}
nodeMode string
// the switch of compressed
enableCompress bool
// event involved
// group chain involved
groupChainCache *groupChainCache
}
- 账本核心数据
// Ledger define data structure of Ledger
type Ledger struct {
baseDB kvdb.Database // 底层是一个leveldb实例,kvdb进行了包装
metaTable kvdb.Database // 记录区块链的根节点、高度、末端节点
confirmedTable kvdb.Database // 已确认的订单表
blocksTable kvdb.Database // 区块表
mutex *sync.RWMutex
xlog log.Logger //日志库
meta *pb.LedgerMeta //账本关键的元数据{genesis, tip, height}
GenesisBlock *GenesisBlock //创始块
heightTable kvdb.Database //保存高度到Blockid的映射
blockCache *common.LRUCache // block cache, 加速QueryBlock
blkHeaderCache *common.LRUCache // block header cache, 加速fetchBlock
cryptoClient crypto_base.CryptoClient
enablePowMinning bool
powMutex *sync.Mutex
confirmBatch kvdb.Batch //新增区块
}
- 对账本的操作都必须经过LedgerKeeper
LedgerKeeper会管理一组task队列,task为外界对其的请求封装,分为直接追加账本(Appending)、批量同步(Syncing),Truncate单独作为同步处理
type LedgerKeeper struct {
p2pSvr p2p_base.P2PServer
log log.Logger
peersStatusMap *sync.Map // map[string]bool 更新同步节点的p2p列表活性
ledger *ledger.Ledger
bcName string
syncTaskMg *syncTaskManager
nodeMode string
utxovm *utxo.UtxoVM
con *consensus.PluggableConsensus
// 该锁保护同一时间内只有矿工or账本keeper对象中的一个对ledger及utxovm操作
// ledgledgerKeeper同步块和xchaincore 矿工doMiner抢锁
coreMutex sync.RWMutex
maxBlocksMsgSize int64 // 取最大区块大小
syncHeaderSize int64 // 一次同步头的大小
}
- UTXO数据和账本查询
// XModel xmodel data structure
type XModel struct {
ledger *ledger.Ledger
stateDB kvdb.Database
unconfirmTable kvdb.Database
extUtxoTable kvdb.Database
extUtxoDelTable kvdb.Database
logger log.Logger
batchCache *sync.Map
lastBatch kvdb.Batch
// extUtxoCache caches per bucket key-values using version as key
extUtxoCache sync.Map // map[string]*LRUCache
}
- filekey.go 从文件中加载私钥、公钥、钱包地址,或者生成到文件中
// 定义密码算法的类型
const (
// 不同语言标准不一样,这里用const直接定义值还是好一些
// 美国Federal Information Processing Standards的椭圆曲线
EccFIPS = iota
// 国密椭圆曲线
EccGM
)
// ECDSAAccount 助记词、私钥的json、公钥的json、钱包地址
type ECDSAAccount struct {
EntropyByte []byte
Mnemonic string
JSONPrivateKey string
JSONPublicKey string
Address string
}
- utxo.go 交易相关的所有,账本,utxo表,交易表,包括智能合约(合约没有UTXO)相关的交易
type UtxoVM struct {
meta *pb.UtxoMeta // utxo meta
metaTmp *pb.UtxoMeta // tmp utxo meta
mutexMeta *sync.Mutex // access control for meta
ldb kvdb.Database
mutex *sync.RWMutex // utxo leveldb表读写锁
mutexMem *sync.Mutex // 内存锁定状态互斥锁
spLock *SpinLock // 自旋锁,根据交易涉及的utxo和改写的变量
mutexBalance *sync.Mutex // 余额Cache锁
lockKeys map[string]*UtxoLockItem
lockKeyList *list.List // 按锁定的先后顺序,方便过期清理
lockExpireTime int // 临时锁定的最长时间
utxoCache *UtxoCache
xlog log.Logger
ledger *ledger_pkg.Ledger // 引用的账本对象
latestBlockid []byte // 当前vm最后一次执行到的blockid
unconfirmedTable kvdb.Database // 未确认交易表
utxoTable kvdb.Database // utxo表
metaTable kvdb.Database // 元数据表,会持久化保存latestBlockid
withdrawTable kvdb.Database // 平行币赎回表, 记录已经赎回的destroy proof
smartContract *contract.SmartContract // 智能合约执行机
OfflineTxChan chan []*pb.Transaction // 未确认tx的通知chan
prevFoundKeyCache *common.LRUCache // 上一次找到的可用utxo key,用于加速GenerateTx
utxoTotal *big.Int // 总资产
cryptoClient crypto_base.CryptoClient // 加密实例
modifyBlockAddr string // 可修改区块链的监管地址
model3 *xmodel.XModel // XuperModel实例,处理extutxo
vmMgr3 *contract.VMManager
aclMgr *acli.Manager // ACL manager for read/write acl table
minerPublicKey string
minerPrivateKey string
minerAddress []byte
failedTxBuf map[string][]string
inboundTxChan chan *InboundTx // 异步tx chan
verifiedTxChan chan *pb.Transaction //已经校验通过的tx
asyncMode bool // 是否工作在异步模式
asyncCancel context.CancelFunc // 停止后台异步batch写的句柄
asyncWriterWG *sync.WaitGroup // 优雅退出异步writer的信号量
asyncCond *sync.Cond // 用来出块线程优先权的条件变量
asyncTryBlockGen bool // doMiner线程是否准备出块
asyncResult *AsyncResult // 用于等待异步结果
// 上述asyncMode是指异步模式,默认是异步回调模式
// asyncBlockMode是指异步阻塞模式
asyncBlockMode bool // 是否工作在异步阻塞模式下
asyncBatch kvdb.Batch // 异步刷盘复用的batch
vatHandler *vat.VATHandler // Verifiable Autogen Tx 生成器
balanceCache *common.LRUCache //余额cache,加速GetBalance查询
cacheSize int //记录构造utxo时传入的cachesize
balanceViewDirty map[string]int //balanceCache 标记dirty: addr -> sequence of view
contractExectionTime int
unconfirmTxInMem *sync.Map //未确认Tx表的内存镜像
maxConfirmedDelay uint32 // 交易处于unconfirm状态的最长时间,超过后会被回滚
unconfirmTxAmount int64 // 未确认的Tx数目,用于监控
avgDelay int64 // 平均上链延时
bcname string
// 最新区块高度通知装置
heightNotifier *BlockHeightNotifier
}