深入学习 Go-Ethereum : 006. CMD模块-Geth

在 Go-Ethereum 源码中,cmd 包中包含了例如 geth、evm、clf等等客户端命令工具。如下图所示⬇️

go-ethereum 源码中 cmd 包结构
go-ethereum 源码中 cmd 包结构

其中最为重要的就是 geth 命令。它是使用以太坊客户端的主要命令。它还包含了很多子命令。在命令行中,可以使用 geth --help ⬇️查看相关帮助手册。

geth --help 执行结果,截取部分结果信息
geth --help 执行结果,截取部分结果信息
 geth 子命令清单及简介
geth 子命令清单及简介

⬆️如上图是 geth 的子命令信息,使用频次比较高的例如 account、console、db、dump、init、wallet


代码调用链
代码调用链

程序入口 cmd/geth/main.go⬇️

geth 的命令行使用 "gopkg.in/urfave/cli.v1" 库做为基础, 代码中执行 app.Run 启动geth。

初始化方法
初始化方法

在初始化函数中,指定了 geth 函数。程序的核心入口 ⬇️


// geth is the main entry point into the system if no special subcommand is ran.
// It creates a default node based on the command line arguments and runs it in
// blocking mode, waiting for it to be shut down.
func geth(ctx *cli.Context) error {
	if args := ctx.Args(); len(args) > 0 {
		return fmt.Errorf("invalid command: %q", args[0])
	}
	prepare(ctx)
	stack, backend := makeFullNode(ctx)
	defer stack.Close()
	startNode(ctx, stack, backend, false)
	stack.Wait()
	return nil
}
  1. 程序先判断上下文参数是否存在异常参数,如果存在异常参数,直接打印错误信息,并终止程序。
  2. 预处理 prepare 方法,主要内容是 创建缓存启动度量服务(启动 InfluxDB 时序数据库进行记录)。
  3. 创建全节点。// makeFullNode loads geth configuration and creates the Ethereum backend.
  4. 启动节点。
  5. 阻塞方式运行程序,等待关闭或者异常错误终止程序。

makeFullNode ⬇️

makeFullNode
makeFullNode

⬆️此方法的主要功能是 设置系统级别参数 和 启动 ethereum network 后台服务,方法内部关注makeConfigNode() 和 utils.RegisterEthService()

makeConfigNode
makeConfigNode

⬆️创建配置节点主要是获取 eth 的配置信息、节点的默认配置信息、度量服务的默认配置星系。然后将这些配置信息进行处理,创建 node 对象 stack, err := node.New(&cfg.Node)

RegisterEthService
RegisterEthService

⬆️RegisterEthService 是将一个 Ethereum 客户端添加到 stack 中, 如果启动时轻节点服务,此方法两个返回值中第二个是 les.Ethereum。如果同步模式是轻客户端模式,则启动轻量级客户端,否则启动全节点客户端,核心方法是 eth.New

startNode ⬇️

// startNode boots up the system node and all registered protocols, after which it unlocks any requested accounts, and starts the RPC/IPC interfaces and the miner.

此方法主要功能包含 启动系统节点和所有注册的协议、解锁用户、启动 RPC/IPC 接口服务、启动矿工挖矿服务

startNode
startNode
  1. 添加对象内存大小计算功能,使用 memsize 类库进行处理
  2. utils启动节点
  3. 解锁请求账户(意图还不了解,//TODO
  4. 订阅钱包事件
  5. 绑定本地客户端和geth节点的交互
  6. 创建客户端
  7. 开启协程进行「事件」处理

以上就是默认 geth 启动的代码流程了。

参考链接:

Subscribe to OutOfToken
Receive the latest updates directly to your inbox.
Verification
This entry has been permanently stored onchain and signed by its creator.