本文系统梳理以太坊从启动到合约执行的全流程,涵盖P2P网络、共识机制、账户模型、EVM执行、存储引擎等关键环节,逐行详解源码,解析设计模式与安全机制,助你“知其然,知其所以然”。
以太坊整体架构如下:
入口:cmd/geth/main.go
func main() {
app := cli.NewApp() // 创建CLI应用
app.Action = geth // 主入口
app.Run(os.Args) // 运行
}
func geth(ctx *cli.Context) error {
stack, backend := makeFullNode(ctx) // 构建全节点
stack.Start() // 启动服务
return nil
}
高级技巧
设计模式
安全分析
调试技巧
geth --verbosity 5
输出详细日志文件:p2p/server.go
func (srv *Server) Start() error {
// 1. 启动节点发现(基于UDP)
srv.setupDiscovery()
// 2. 监听端口,接受连接
go srv.listenLoop()
// 3. 建立出站连接
go srv.connectLoop()
// ...
}
节点发现:p2p/discover/udp.go
func ListenUDP(conn *net.UDPConn, ...) {
for {
n, addr, err := conn.ReadFromUDP(buf)
// 解析节点消息
go handlePacket(addr, buf[:n])
}
}
设计模式
高级技巧
安全分析
调试技巧
admin.peers
查看连接节点Ethash(PoW):consensus/ethash/consensus.go
func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, ...) {
for {
hash := hashimoto(...)
if hash < target {
// 发现合格nonce
return newBlockWithNonce
}
}
}
Clique(PoA):consensus/clique/clique.go
func (clique *Clique) VerifyHeader(chain consensus.ChainReader, header *types.Header, ...) error {
// 验证签名、轮次、难度
if !clique.verifySealer(header) {
return errors.New("unauthorized sealer")
}
// ...
}
PoS(Beacon Chain)
详见 Prysm/Lighthouse/官方spec
设计模式
高级技巧
安全分析
调试技巧
geth --mine
启动挖矿core/state/state_object.go
type StateObject struct {
address common.Address
balance *big.Int
nonce uint64
codeHash []byte
storage Trie
}
状态变更流程
func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
so := s.getStateObject(addr)
so.SetBalance(new(big.Int).Add(so.Balance(), amount))
}
Trie操作:trie/trie.go
func (t *Trie) TryUpdate(key, value []byte) error {
// 更新节点并重算根哈希
}
设计模式
高级技巧
安全分析
调试技巧
debug.traceTransaction
跟踪状态变化core/tx_pool.go
func (pool *TxPool) AddLocal(tx *types.Transaction) error {
// 1. 校验签名
from, err := types.Sender(pool.signer, tx)
// 2. 检查余额/Nonce
if !enoughBalance(from, tx) { return ErrInsufficientFunds }
// 3. 插入优先队列
pool.pending[from] = tx
}
交易验证:core/tx_pool.go
func (pool *TxPool) validateTx(tx *types.Transaction) error {
// 签名、Gas、Nonce等多重检查
}
设计模式
高级技巧
安全分析
调试技巧
txpool.inspect
查看池内交易core/vm/interpreter.go
func (in *EVMInterpreter) Run() (ret []byte, err error) {
for {
op := in.code[in.pc]
switch op {
case ADD:
x, y := in.stack.pop(), in.stack.pop()
in.stack.push(x + y)
case CALL:
// 外部合约调用
...
}
in.pc++
}
}
安全分析:常见漏洞及防护
设计模式
高级技巧
调试技巧
debug.traceTransaction
指令级追踪trie/database.go
func (db *Database) Put(key, value []byte) error {
return db.lvl.Put(key, value, nil)
}
快照机制
func (s *StateDB) Snapshot() int {
// 生成状态快照ID
}
func (s *StateDB) RevertToSnapshot(id int) {
// 回滚至某快照
}
设计模式
高级技巧
安全分析
调试技巧
geth db inspect
口诀
启动先加载,P2P连环;
共识守安全,账户管钱权;
交易入池判,EVM跑合约;
存储护全链,安全常防范。
如需对某环节(如EVM某条指令、状态Trie算法、共识具体投票流程等)做更详细源码逐行注释和安全分析,欢迎留言具体模块,我将持续补充!
以太坊技术的精髓,在于分层解耦、模块迭代、机制安全、易于扩展。源码细读,既能掌控细节,也能洞悉全局。