Mempool > mempool_object > Transaction
交易池,虽然它也是内核的一部分,但它是一个比较独立的功能模块,所以在进一步细分时,可以考虑把它拎出来。
除了“链”,它不直接与任何外部其它模块交互,都是通过
chain
封装的接口。
交易池,顾名思义它是一个池子、一个容器,有存储作用,在程序上由一个“服务”来表示。
但这不是其核心,核心是数据的进入、输出,及对里面数据的管理。
// at this point in time, this is an ultrafast written mempool,
// it will not scale for more than 10000 transactions but is good enough for now
// we can always come back and rewrite it
// NOTE: the pool is now persistant
type Mempool struct {
txs sync.Map //map[crypto.Hash]*mempool_object
key_images sync.Map //map[crypto.Hash]bool // contains key images of all txs
sorted_by_fee []crypto.Hash // contains txids sorted by fees
sorted []TX_Sorting_struct // contains TX sorting information, so as new block can be forged easily
modified bool // used to monitor whethel mem pool contents have changed,
height uint64 // track blockchain height
P2P_TX_Relayer p2p_TX_Relayer // actual pointer, setup by the dero daemon during runtime
// global variable , but don't see it utilisation here except fot tx verification
//chain *Blockchain
Exit_Mutex chan bool
sync.Mutex
}
交易池,从“数据结构”的角度来说并不是很有特色,从“算法”的角度来说也没有什么特殊之处,但从“业务”上来说,它是内核体系里重要的、不可或缺的一环。
它主要用时存储交易和密钥镜像,以及上链确认之前的一些前置校验、处理。转账交易被广播后,会先进入交易池进行临时存储,然后由矿工通过挖矿,打包到区块上。
sync.Map 相当于 map[interface{}]interface{}
在这里用来存放交易。
// this is only used for sorting and nothing else
type TX_Sorting_struct struct {
FeesPerByte uint64 // this is fees per byte
Hash crypto.Hash // transaction hash
Size uint64 // transaction size
}
“交易池”所存储的具体对象(mempool_object),不仅仅是“交易”,还有一些附加属性。
// this object is serialized and deserialized
type mempool_object struct {
Tx *transaction.Transaction
Added uint64 // time in epoch format
Height uint64 // at which height the tx unlocks in the mempool
Relayed int // relayed count
RelayedAt int64 // when was tx last relayed
Size uint64 // size in bytes of the TX
FEEperBYTE uint64 // fee per byte
}
// function type, exported in p2p but cannot use due to cyclic dependency
type p2p_TX_Relayer func(*transaction.Transaction, uint64) int
和 block/proc 类似,实现闭包。
这里的具体实现查看 p2p.Broadcast_Tx
架构设计:
交易池本质是一个容器,可以放“交易 txs”等数据(Dero 还有 key_images)。
主要做的事情有几个:
管理自身(启动、停止)
管理里面所存储的数据(增、删、查)
交易池里主要数据有:交易、密钥镜像
发生某些事件时,与其它模块协作(比如 Blockchain、P2P 模块)
设计上,它是一个比较独立的模块。虽然和 P2P 那边还会有所交互(主要是事件处理),但真正实现时可以做到“解耦”。
小缺陷,当前,Dero 这块还没有定期持久化操作。关闭时,可保存到文件。