代码编织梦想

  1. 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
}
  1. 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
}
  1. 账本核心数据
    // 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 //新增区块
}
  1. 对账本的操作都必须经过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 // 一次同步头的大小
}
  1. 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
}
  1. 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
}
  1. 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
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zengqiang1/article/details/120309196

案例分享| 如何基于XuperChain部署一个储存千万数据量的存证系统-爱代码爱编程

基于XuperChain,信浦存证平台团队搭建了一套存证系统。目前,该存证系统已完成了与上海市徐汇公证处、上海市张江公证处、苏州市相城公证处、无锡市江南公证处等权威机构的对接,为超过50家机构提供服务,产生存证记录1000多万条。 信浦存证平台团队分享的建设经验分成以下四部分: 一、背景介绍 二、部署go语言智能合约和实现存证功能 三、部署J

xuperchain-爱代码爱编程

百度超级链(xuperchain) 简介 高性能,通过原创的XuperModel模型,真正实现了智能合约的并行执行和验证,通过自研的WASM虚拟机,做到了指令集级别的极致优化。 在架构方面,其可插拔、插件化的设计使得用户可以方便选择适合自己业务场景的解决方案,通过独有的XuperBridge技术,可插拔多语言虚拟机,从而支持丰富的合约开发语言。在网络能力

XuperChain安装-爱代码爱编程

问题一:make报了一个关于g++的错误g++: command not found centos: yum -y update gcc yum -y install gcc+ gcc-c++ ubuntu: apt-get update gcc apt-get install g++ 问题二:git下载速度过慢:解决办法将仓库复制到gitee码云上。找

xuperchain源码分析-插件机制-爱代码爱编程

背景 因为最近我们在自研底层联盟链,所以调研了现在市面上的主流的公链,联盟链。 xuperchain基于插件机制,实现多个核心模块可替换,包括存储,共识,网络等。下面我们就来看看这个插件机制是如何实现的 PluginMgr 插件管理器 // PluginMgr defines the data struct of plugin manager,只管

xuperchain源码分析-合约-爱代码爱编程

这里的合约定义更多的是自动执行约定,而不是预置了一个带有合约地址的合约代码,当时看源码时候就产生过疑惑 合约类图 Contract表示一种自定义执行约定,调用合约的方式必须是交易,交易到区块上面打包。 每一个合约实现,都被称为一个module,上面就有4个module,tdpos,kernel,consensus,proposal。 tdpos

xuperchain源码分析-接口-爱代码爱编程

XchainServer,TCPServer的对外接口 // XchainServer is the server API for Xchain service. type XchainServer interface { // SelectUTXOBySize merge many utxos into a few of utxos Sel

xuperchain源码分析-智能合约-爱代码爱编程

XuperBridge XuperBridge为所有合约提供统一的合约接口,从抽象方式上类似于linux内核对应于应用程序,内核代码是一份,应用程序可以用各种语言实现,比如go,c。类比到合约上就是各种合约的功能,如KV访问,QueryBlock, QueryTx等,这些请求都会通过跟xchain通信的方式来执行,这样在其上实现的各种合约虚拟机只需要做纯