作者:Derek

简介

Github地址:https://github.com/Bytom/bytom

Gitee地址:https://gitee.com/BytomBlockchain/bytom

本章介绍bytom代码启动、节点初始化、及停止的过程

作者使用MacOS操作系统,其他平台也大同小异

Golang Version: 1.8

预备工作

编译安装

详细步骤见官方 bytom install

设置debug日志输出

开启debug输出文件、函数、行号等详细信息

export BYTOM_DEBUG=debug

初始化并启动bytomd

初始化

./bytomd init --chain_id testnet

bytomd目前支持两种网络,这里我们使用测试网

mainnet:主网

testnet:测试网

启动bytomd

./bytomd node --mining --prof_laddr=":8011"

--prof_laddr=":8080" // 开启pprof输出性能指标

访问:http://127.0.0.1:8080/debug/pprof/

bytomd init初始化

入口函数

** cmd/bytomd/main.go **

func init() {
log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableColors: true}) // If environment variable BYTOM_DEBUG is not empty,
// then add the hook to logrus and set the log level to DEBUG
if os.Getenv("BYTOM_DEBUG") != "" {
log.AddHook(ContextHook{})
log.SetLevel(log.DebugLevel)
}
} func main() {
cmd := cli.PrepareBaseCmd(commands.RootCmd, "TM", os.ExpandEnv(config.DefaultDataDir()))
cmd.Execute()
}

init函数会在main执行之前做初始化操作,可以看到init中bytomd加载BYTOM_DEBUG变量来设置debug日志输出

command cli传参初始化

bytomd的cli解析使用cobra

** cmd/bytomd/commands **

  • cmd/bytomd/commands/root.go

    初始化--root传参。bytomd存储配置、keystore、数据的root目录。在MacOS下,默认路径是~/Library/Bytom/
  • cmd/bytomd/commands/init.go

    初始化--chain_id传参。选择网络类型,在启动bytomd时我们选择了testnet也就是测试网络
  • cmd/bytomd/commands/version.go

    初始化version传参
  • cmd/bytomd/commands/run_node.go

    初始化node节点运行时所需要的传参

初始化默认配置

用户传参只有一部分参数,那节点所需的其他参数需要从默认配置中加载。

** cmd/bytomd/commands/root.go **

var (
config = cfg.DefaultConfig()
)

在root.go中有一个config全局变量加载了node所需的所有默认参数

// Default configurable parameters.
func DefaultConfig() *Config {
return &Config{
BaseConfig: DefaultBaseConfig(), // node基础相关配置
P2P: DefaultP2PConfig(), // p2p网络相关配置
Wallet: DefaultWalletConfig(), // 钱包相关配置
Auth: DefaultRPCAuthConfig(), // 验证相关配置
Web: DefaultWebConfig(), // web相关配置
}
}

后面的文章会一一介绍每个配置的作用

bytomd 守护进程启动与退出

** cmd/bytomd/commands/run_node.go **

func runNode(cmd *cobra.Command, args []string) error {
// Create & start node
n := node.NewNode(config)
if _, err := n.Start(); err != nil {
return fmt.Errorf("Failed to start node: %v", err)
} else {
log.WithField("nodeInfo", n.SyncManager().Switch().NodeInfo()).Info("Started node")
} // Trap signal, run forever.
n.RunForever() return nil
}

runNode函数有三步操作:

node.NewNode:初始化node运行环境

n.Start:启动node

n.RunForever:监听退出信号,收到ctrl+c操作则退出node。在linux中守进程一般监听SIGTERM信号(ctrl+c)作为退出守护进程的信号

初始化node运行环境

在bytomd中有五个db数据库存储在--root参数下的data目录

  • accesstoken.db // 存储token相关信息(钱包访问控制权限)
  • trusthistory.db // 存储p2p网络同步相关信息
  • txdb.db // 存储交易相关信息
  • txfeeds.db //
  • wallet.db // 存储钱包相关信息

** node/node.go **

func NewNode(config *cfg.Config) *Node {
ctx := context.Background()
initActiveNetParams(config)
// Get store 初始化txdb数据库
txDB := dbm.NewDB("txdb", config.DBBackend, config.DBDir())
store := leveldb.NewStore(txDB) // 初始化accesstoken数据库
tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
accessTokens := accesstoken.NewStore(tokenDB) // 初始化event事件调度器,也叫任务调度器。一个任务可以被多次调用
// Make event switch
eventSwitch := types.NewEventSwitch()
_, err := eventSwitch.Start()
if err != nil {
cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
} // 初始化交易池
txPool := protocol.NewTxPool()
chain, err := protocol.NewChain(store, txPool)
if err != nil {
cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
} var accounts *account.Manager = nil
var assets *asset.Registry = nil
var wallet *w.Wallet = nil
var txFeed *txfeed.Tracker = nil // 初始化txfeeds数据库
txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
txFeed = txfeed.NewTracker(txFeedDB, chain) if err = txFeed.Prepare(ctx); err != nil {
log.WithField("error", err).Error("start txfeed")
return nil
} // 初始化keystore
hsm, err := pseudohsm.New(config.KeysDir())
if err != nil {
cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
} // 初始化钱包,默认wallet是开启状态
if !config.Wallet.Disable {
walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
accounts = account.NewManager(walletDB, chain)
assets = asset.NewRegistry(walletDB, chain)
wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
if err != nil {
log.WithField("error", err).Error("init NewWallet")
} // Clean up expired UTXO reservations periodically.
go accounts.ExpireReservations(ctx, expireReservationsPeriod)
}
newBlockCh := make(chan *bc.Hash, maxNewBlockChSize) // 初始化网络节点同步管理
syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh) // 初始化pprof,pprof用于输出性能指标,需要制定--prof_laddr参数来开启,在文章开头我们已经开启该功能
// run the profile server
profileHost := config.ProfListenAddress
if profileHost != "" {
// Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
// go tool pprof http://profileHose/debug/pprof/heap
go func() {
http.ListenAndServe(profileHost, nil)
}()
} // 初始化节点,填充节点所需的所有参数环境
node := &Node{
config: config,
syncManager: syncManager,
evsw: eventSwitch,
accessTokens: accessTokens,
wallet: wallet,
chain: chain,
txfeed: txFeed,
miningEnable: config.Mining,
} // 初始化挖矿
node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh) node.BaseService = *cmn.NewBaseService(nil, "Node", node) return node
}

目前bytomd只支持cpu挖矿,所以在代码中只有cpuminer的初始化信息

启动node

** node/node.go **

// Lanch web broser or not
func lanchWebBroser() {
log.Info("Launching System Browser with :", webAddress)
if err := browser.Open(webAddress); err != nil {
log.Error(err.Error())
return
}
} func (n *Node) initAndstartApiServer() {
n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens) listenAddr := env.String("LISTEN", n.config.ApiAddress)
env.Parse()
n.api.StartServer(*listenAddr)
} func (n *Node) OnStart() error {
if n.miningEnable {
n.cpuMiner.Start()
}
n.syncManager.Start()
n.initAndstartApiServer()
if !n.config.Web.Closed {
lanchWebBroser()
} return nil
}

OnStart() 启动node进程如下:

  • 启动挖矿功能
  • 启动p2p网络同步
  • 启动http协议的apiserver服务
  • 打开浏览器访问bytond的交易页面

停止node

bytomd在启动时执行了n.RunForever()函数,该函数是由tendermint框架启动了监听信号的功能:

** vendor/github.com/tendermint/tmlibs/common/os.go **

func TrapSignal(cb func()) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
for sig := range c {
fmt.Printf("captured %v, exiting...\n", sig)
if cb != nil {
cb()
}
os.Exit(1)
}
}()
select {}
}

TrapSignal函数监听了SIGTERM信号,bytomd才能成为不退出的守护进程。只有当触发了ctrl+c或kill bytomd_pid才能终止bytomd进程退出。退出时bytomd执行如下操作

** node/node.go **

func (n *Node) OnStop() {
n.BaseService.OnStop()
if n.miningEnable {
n.cpuMiner.Stop()
}
n.syncManager.Stop()
log.Info("Stopping Node")
// TODO: gracefully disconnect from peers.
}

bytomd会将挖矿功能停止,p2p网络停止等操作。

Derek解读Bytom源码-启动与停止的更多相关文章

  1. Derek解读Bytom源码-持久化存储LevelDB

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  2. Derek解读Bytom源码-创世区块

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  3. Derek解读Bytom源码-Api Server接口服务

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  4. Derek解读Bytom源码-孤块管理

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  5. Derek解读Bytom源码-P2P网络 地址簿

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  6. Derek解读Bytom源码-protobuf生成比原核心代码

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  7. Derek解读Bytom源码-P2P网络 upnp端口映射

    作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchain/bytom ...

  8. RxJava系列6(从微观角度解读RxJava源码)

    RxJava系列1(简介) RxJava系列2(基本概念及使用介绍) RxJava系列3(转换操作符) RxJava系列4(过滤操作符) RxJava系列5(组合操作符) RxJava系列6(从微观角 ...

  9. 入口开始,解读Vue源码(一)-- 造物创世

    Why? 网上现有的Vue源码解析文章一搜一大批,但是为什么我还要去做这样的事情呢?因为觉得纸上得来终觉浅,绝知此事要躬行. 然后平时的项目也主要是Vue,在使用Vue的过程中,也对其一些约定产生了一 ...

随机推荐

  1. Swift 了解(3)

    类(Classes) 假设你是一个建筑师,你刚刚签了一个合同,要在一个新的小区修建20个相似的房子.在你派出建筑工队之前,你必须要画一个房子的设计图.这份设计图将会展现房子的外表和功能.把这份设计图当 ...

  2. LinkedList 底层实现原理

    LinkedList的底层实现原理 LinkedList 底层数据结构为双向链表,链表结构,基于一个个链表节点Node 1,Inner Class 内部类 private static class N ...

  3. python深拷贝和浅拷贝的区别

    首先深拷贝和浅拷贝都是对象的拷贝,都会生成一个看起来相同的对象,他们本质的区别是拷贝出来的对象的地址是否和原对象一样,也就是地址的复制还是值的复制的区别. 什么是可变对象,什么是不可变对象: 可变对象 ...

  4. 算法训练 P0505

    一个整数n的阶乘可以写成n!,它表示从1到n这n个整数的乘积.阶乘的增长速度非常快,例如,13!就已经比较大了,已经无法存放在一个整型变量中:而35!就更大了,它已经无法存放在一个浮点型变量中.因此, ...

  5. Codeforce 835B - The number on the board (贪心)

    Some natural number was written on the board. Its sum of digits was not less than k. But you were di ...

  6. 51Nod 1433 0和5

    小K手中有n张牌,每张牌上有一个一位数的数,这个字数不是0就是5.小K从这些牌在抽出任意张(不能抽0张),排成一行这样就组成了一个数.使得这个数尽可能大,而且可以被90整除. 注意: 1.这个数没有前 ...

  7. Autel MaxiSys Elite Diagnostic Tool Common problem solving methods

    1. updating MaxiFlash Elite to firmware 3.21? My maxisys communicate with the MaxiFlash J2534 but Ma ...

  8. Python基础(一)_数据类型、条件判断、循环、列表

    编译型语言(中文版)运行代码之前,要先编译.然后再运行编译时间比较长c.c++.c# 解释型语言(翻译版)运行的时候才去编译,运行一次编译.运行效率没有编译型语言快python.ruby.shell. ...

  9. django自定义错误响应

    在做一个web时,总是会出现各种错误,如400.403.404.500等.一般开发都要做对应的处理,给一些友好提示,或返回一些公益广告等. 在Django中,默认提供了常见的错误处理方式,比如: ha ...

  10. Linux centos7下php安装cphalcon扩展的方法

    说明: 操作系统:CentOS7 php安装目录:/usr/local/php php.ini配置文件路径:/usr/local/php/etc/php.ini 运行环境:LNMP ,PHP7 .安装 ...