go ethereum源码分析 PartIV Transaction相关


核心数据结构:
core.types.transaction.go
type Transaction struct {
data txdata
// caches
hash atomic.Value
size atomic.Value
from atomic.Value
}
Transaction.data
type txdata struct {
AccountNonce uint64 `json:"nonce" gencodec:"required"`
Price *big.Int `json:"gasPrice" gencodec:"required"`
GasLimit uint64 `json:"gas" gencodec:"required"`
Recipient *common.Address `json:"to" rlp:"nil"` // nil means contract creation
Amount *big.Int `json:"value" gencodec:"required"`
Payload []byte `json:"input" gencodec:"required"`
// Signature values
V *big.Int `json:"v" gencodec:"required"`
R *big.Int `json:"r" gencodec:"required"`
S *big.Int `json:"s" gencodec:"required"`
// This is only used when marshaling to JSON.
Hash *common.Hash `json:"hash" rlp:"-"`
}
辅助数据结构
core/tx_list.go
txList
type txList struct {
//nonces是否严格递增
strict bool // Whether nonces are strictly continuous or not
txs *txSortedMap // Heap indexed sorted hash map of the transactions
//costing最高的会话的价格(只有当超过balance时才重置)
costcap *big.Int // Price of the highest costing transaction (reset only if exceeds balance)
//spending最高的会话的gas limit
gascap uint64 // Gas limit of the highest spending transaction (reset only if exceeds block limit)
}
txList.txs txSortedMap
// txSortedMap is a nonce->transaction hash map with a heap based index to allow
// iterating over the contents in a nonce-incrementing way.
type txSortedMap struct {
items map[uint64]*types.Transaction // Hash map storing the transaction data
index *nonceHeap // Heap of nonces of all the stored transactions (non-strict mode)
cache types.Transactions // Cache of the transactions already sorted
}
txSortedMap.index nonceHeap
type nonceHeap []uint64
类似的结构,txPricedList
// txPricedList is a price-sorted heap to allow operating on transactions pool
// contents in a price-incrementing way.
type txPricedList struct {
all *txLookup // Pointer to the map of all transactions
items *priceHeap // Heap of prices of all the stored transactions
stales int // Number of stale price points to (re-heap trigger)
}
tx.PricedList.items priceHeap,令人有点吃惊,不够对称
type priceHeap []*types.Transaction
在tx_list.go中需要分析两个数据结构,1. txList, 2. txPricedList




调用到tx_list.go的主要是tx_pool.go
tx_pool.go的主要数据结构是txPool,
txPool中包含目前已知的所有会话。会话上传到blockchain上的时候就会离开会话池。
// TxPool contains all currently known transactions. Transactions
// enter the pool when they are received from the network or submitted
// locally. They exit the pool when they are included in the blockchain.
//
// The pool separates processable transactions (which can be applied to the
// current state) and future transactions. Transactions move between those
// two states over time as they are received and processed.
//TxPool包含目前所有已知的会话,会话直接从本地提交,或者从网络传送过来之后,紧接着就进入池中
//会话被上传到blockchain的时候就会离开会话池
//会话池将processable的会话(可处理的会话)与future会话(未来的会话)分开。
//会话收发的过程中就不断在这两种状态之见切换
type TxPool struct {
config TxPoolConfig
chainconfig *params.ChainConfig//有专用的ChainConfig
chain blockChain
gasPrice *big.Int
txFeed event.Feed
scope event.SubscriptionScope
chainHeadCh chan ChainHeadEvent
chainHeadSub event.Subscription
signer types.Signer
mu sync.RWMutex
//blockchain头节点的状态-currentState
currentState *state.StateDB // Current state in the blockchain head
pendingState *state.ManagedState // Pending state tracking virtual nonces
//目前会话的gasLimit,有待具体确认
currentMaxGas uint64 // Current gas limit for transaction caps locals *accountSet // Set of local transaction to exempt from eviction rules
journal *txJournal // Journal of local transaction to back up to disk
//可处理的
pending map[common.Address]*txList // All currently processable transactions
//排着队的但是还没处理的
queue map[common.Address]*txList // Queued but non-processable transactions
//最后的波纹,啊不,临近节点的心跳
beats map[common.Address]time.Time // Last heartbeat from each known account
// all,有可能与txPricedList的all是同一个实例
all *txLookup // All transactions to allow lookups
priced *txPricedList // All transactions sorted by price
//for shutdown
wg sync.WaitGroup // for shutdown sync homestead bool
}
PoolConfig可以设定的内容以及默认参数
// TxPoolConfig are the configuration parameters of the transaction pool.
type TxPoolConfig struct {
Locals []common.Address // Addresses that should be treated by default as local
NoLocals bool // Whether local transaction handling should be disabled
Journal string // Journal of local transactions to survive node restarts
Rejournal time.Duration // Time interval to regenerate the local transaction journal PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce) AccountSlots uint64 // Number of executable transaction slots guaranteed per account
GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts
AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
} // DefaultTxPoolConfig contains the default configurations for the transaction
// pool.
var DefaultTxPoolConfig = TxPoolConfig{
Journal: "transactions.rlp",
Rejournal: time.Hour, PriceLimit: ,
PriceBump: , AccountSlots: ,
GlobalSlots: ,
AccountQueue: ,
GlobalQueue: , Lifetime: * time.Hour,
}
ChainConfig-区块链的核心设置
// ChainConfig is the core config which determines the blockchain settings.
//
// ChainConfig is stored in the database on a per block basis. This means
// that any network, identified by its genesis block, can have its own
// set of configuration options.
type ChainConfig struct {
ChainID *big.Int `json:"chainId"` // chainId identifies the current chain and is used for replay protection HomesteadBlock *big.Int `json:"homesteadBlock,omitempty"` // Homestead switch block (nil = no fork, 0 = already homestead) DAOForkBlock *big.Int `json:"daoForkBlock,omitempty"` // TheDAO hard-fork switch block (nil = no fork)
DAOForkSupport bool `json:"daoForkSupport,omitempty"` // Whether the nodes supports or opposes the DAO hard-fork // EIP150 implements the Gas price changes (https://github.com/ethereum/EIPs/issues/150)
EIP150Block *big.Int `json:"eip150Block,omitempty"` // EIP150 HF block (nil = no fork)
EIP150Hash common.Hash `json:"eip150Hash,omitempty"` // EIP150 HF hash (needed for header only clients as only gas pricing changed) EIP155Block *big.Int `json:"eip155Block,omitempty"` // EIP155 HF block
EIP158Block *big.Int `json:"eip158Block,omitempty"` // EIP158 HF block ByzantiumBlock *big.Int `json:"byzantiumBlock,omitempty"` // Byzantium switch block (nil = no fork, 0 = already on byzantium)
ConstantinopleBlock *big.Int `json:"constantinopleBlock,omitempty"` // Constantinople switch block (nil = no fork, 0 = already activated)
PetersburgBlock *big.Int `json:"petersburgBlock,omitempty"` // Petersburg switch block (nil = same as Constantinople)
EWASMBlock *big.Int `json:"ewasmBlock,omitempty"` // EWASM switch block (nil = no fork, 0 = already activated) // Various consensus engines
Ethash *EthashConfig `json:"ethash,omitempty"`
Clique *CliqueConfig `json:"clique,omitempty"`
}
// EthashConfig is the consensus engine configs for proof-of-work based sealing.
type EthashConfig struct{}
// CliqueConfig is the consensus engine configs for proof-of-authority based sealing.
type CliqueConfig struct {
Period uint64 `json:"period"` // Number of seconds between blocks to enforce
Epoch uint64 `json:"epoch"` // Epoch length to reset votes and checkpoint
}
BlockChain的定义,主要是起索引
type blockChain interface {
CurrentBlock() *types.Block
GetBlock(hash common.Hash, number uint64) *types.Block
StateAt(root common.Hash) (*state.StateDB, error)
SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
}
状态DB的定义
// StateDBs within the ethereum protocol are used to store anything
// within the merkle trie. StateDBs take care of caching and storing
// nested states. It's the general query interface to retrieve:
// * Contracts
// * Accounts
type StateDB struct {
db Database
trie Trie // This map holds 'live' objects, which will get modified while processing a state transition.
stateObjects map[common.Address]*stateObject
stateObjectsDirty map[common.Address]struct{} // DB error.
// State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs
// during a database read is memoized here and will eventually be returned
// by StateDB.Commit.
dbErr error // The refund counter, also used by state transitioning.
refund uint64 thash, bhash common.Hash
txIndex int
logs map[common.Hash][]*types.Log
logSize uint preimages map[common.Hash][]byte // Journal of state modifications. This is the backbone of
// Snapshot and RevertToSnapshot.
journal *journal
validRevisions []revision
nextRevisionId int
}
ManagedState定义,比普通的StateDB多了accounts的管理
type ManagedState struct {
*StateDB
mu sync.RWMutex
accounts map[common.Address]*account
}
type account struct {
stateObject *stateObject
nstart uint64
nonces []bool
}
tx_pool.go中的主要逻辑









go ethereum源码分析 PartIV Transaction相关的更多相关文章
- EOS源码分析:transaction的一生
最近在处理智能合约的事务上链问题,发现其中仍旧有知识盲点.原有的认识是一个事务请求会从客户端设备打包签名,然后通过RPC传到非出块节点,广播给超级节点,校验打包到可逆区块,共识确认最后变为不可逆区块. ...
- [ethereum源码分析](3) ethereum初始化指令
前言 在上一章介绍了关于区块链的一些基础知识,这一章会分析指令 geth --datadir dev/data/02 init private-geth/genesis.json 的源码,若你的eth ...
- Android AdapterView 源码分析以及其相关回收机制的分析
忽然,发现,网上的公开资料都是教你怎么继承一个baseadapter,然后重写那几个方法,再调用相关view的 setAdpater()方法, 接着,你的item 就显示在手机屏幕上了.很少有人关注a ...
- trinitycore 魔兽服务器源码分析(三) 多线程相关
先看LockedQueue.h template <class T, typename StorageType = std::deque<T> >class LockedQue ...
- [ethereum源码分析](5) 创建新账号
前言 在上一章我们介绍了 ethereum运行开启console 的过程,那么在这一章我们将会介绍如何在以太坊中创建一个新的账号.以下的理解可能存在错误,如果各位大虾发现错误,还望指正. 指令分析 指 ...
- HDFS源码分析:NameNode相关的数据结构
本文主要基于Hadoop1.1.2分析HDFS中的关键数据结构. 1 NameNode 首先从NameNode开始.NameNode的主要数据结构如下: NameNode管理着两张很重要的表: 1) ...
- Ethereum 源码分析之 accounts
一.Account // Account represents an Ethereum account located at a specific location defined // by the ...
- [ethereum源码分析](4) ethereum运行开启console
前言 在上一章我们介绍了 ethereum初始化指令 ,包括了系统是如何调用指令和指令的执行.在本章节我们将会介绍 geth --datadir dev/data/ --networkid cons ...
- [ethereum源码分析](2) ethereum基础知识
前言 上一章我们介绍了如何搭建ethereum的debug环境.为了更深入的了解ethereum,我们需要了解一些ethereum的相关的知识,本章我们将介绍这些知识. ethereum相关知识 在学 ...
随机推荐
- 细数Linux的文件权限
普通权限 普通权限使用ls -l查看,最前面显示的即是,如: # ls -l .txt -rw-r--r-- 1 root root 8338 7月 19 20:27 1.txt 权限介绍: -/d/ ...
- 父级POM的表现形式
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...
- Python并发编程之线程池&进程池
引用 Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我 ...
- @Override报错的处理
有时候我们从SVN导的项目,jre和jar包都没问题,但是就会出如下图的错误: xi 点击红叉,显示错误信息如下: 点击工具里面的window-->preferences-->java-- ...
- VMware15 安装centos7标准板
VM主页——>创建虚拟机——>典型——>下一步: 选择安装安装操作系统,进入选择客户机操作系统界面 选择Linux 版本centos7 64位: 下一步——>填写虚拟机名称, ...
- Unity3d外包—就找北京动点软件(长年承接Unity3d软件、游戏项目外包)
承接Unity3d体感企业项目.游戏项目外包 北京公司.专业团队,成员为专业Unity3d产品公司一线开发人员,有大型产品开发经验: 提供优质的售后服务,保证产品质量,轻量级产品可以提供规范清晰的源代 ...
- Mybatis映射文件中#取值时指定参数相关规则
Mybatis映射文件中#取值时指定参数相关规则 在#{}中,除了需要的数值外,还可以规定参数的一些其他规则. 例如:javaType,jdbcType,mode(存储过程),numericScale ...
- php-fpm开启慢查询日志
php-fpm.conf /usr/local/php/etc/php-fpm.conf 开启慢查询日志 ; The log file for slow requests ; Default Valu ...
- docker 中安装 rabbitMQ
安装rabbitMQ的命令 docker run -d --hostname my-rabbit --name rabbit -e RABBITMQ_DEFAULT_USER=admin -e RAB ...
- edu9E. Thief in a Shop
题意:n个物品每个价值a[i],要求选k个,可以重复,问能取到哪几个价值 题解:fft裸题.但是直接一次fft,然后快速幂会boom.这样是严格的\(2^{20}*log2(2^{20})*log(w ...