13 "github.com/prometheus/prometheus/util/flock"
14 log "github.com/sirupsen/logrus"
15 cmn "github.com/tendermint/tmlibs/common"
16 dbm "github.com/tendermint/tmlibs/db"
17 browser "github.com/toqueteos/webbrowser"
19 "github.com/bytom/accesstoken"
20 "github.com/bytom/account"
21 "github.com/bytom/api"
22 "github.com/bytom/asset"
23 "github.com/bytom/blockchain/pseudohsm"
24 "github.com/bytom/blockchain/txfeed"
25 cfg "github.com/bytom/config"
26 "github.com/bytom/consensus"
27 "github.com/bytom/database/leveldb"
28 "github.com/bytom/env"
29 "github.com/bytom/mining/cpuminer"
30 "github.com/bytom/mining/miningpool"
31 "github.com/bytom/netsync"
32 "github.com/bytom/protocol"
33 "github.com/bytom/protocol/bc"
34 "github.com/bytom/types"
35 w "github.com/bytom/wallet"
39 webAddress = "http://127.0.0.1:9888"
40 expireReservationsPeriod = time.Second
41 maxNewBlockChSize = 1024
50 syncManager *netsync.SyncManager
52 evsw types.EventSwitch // pub/sub for services
53 //bcReactor *bc.BlockchainReactor
55 accessTokens *accesstoken.CredentialStore
58 txfeed *txfeed.Tracker
59 cpuMiner *cpuminer.CPUMiner
60 miningPool *miningpool.MiningPool
64 func NewNode(config *cfg.Config) *Node {
65 ctx := context.Background()
66 if err := lockDataDirectory(config); err != nil {
67 cmn.Exit("Error: " + err.Error())
70 initActiveNetParams(config)
72 coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
73 store := leveldb.NewStore(coreDB)
75 tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
76 accessTokens := accesstoken.NewStore(tokenDB)
79 eventSwitch := types.NewEventSwitch()
80 if _, err := eventSwitch.Start(); err != nil {
81 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
84 txPool := protocol.NewTxPool()
85 chain, err := protocol.NewChain(store, txPool)
87 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
90 var accounts *account.Manager = nil
91 var assets *asset.Registry = nil
92 var wallet *w.Wallet = nil
93 var txFeed *txfeed.Tracker = nil
95 txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
96 txFeed = txfeed.NewTracker(txFeedDB, chain)
98 if err = txFeed.Prepare(ctx); err != nil {
99 log.WithField("error", err).Error("start txfeed")
103 hsm, err := pseudohsm.New(config.KeysDir())
105 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
108 if !config.Wallet.Disable {
109 walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
110 accounts = account.NewManager(walletDB, chain)
111 assets = asset.NewRegistry(walletDB, chain)
112 wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
114 log.WithField("error", err).Error("init NewWallet")
117 // trigger rescan wallet
118 if config.Wallet.Rescan {
119 wallet.RescanBlocks()
122 // Clean up expired UTXO reservations periodically.
123 go accounts.ExpireReservations(ctx, expireReservationsPeriod)
125 newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
127 syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
129 // run the profile server
130 profileHost := config.ProfListenAddress
131 if profileHost != "" {
132 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
133 // go tool pprof http://profileHose/debug/pprof/heap
135 http.ListenAndServe(profileHost, nil)
141 syncManager: syncManager,
143 accessTokens: accessTokens,
147 miningEnable: config.Mining,
150 node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
151 node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
153 node.BaseService = *cmn.NewBaseService(nil, "Node", node)
158 // Lock data directory after daemonization
159 func lockDataDirectory(config *cfg.Config) error {
160 _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
162 return errors.New("datadir already used by another process")
167 func initActiveNetParams(config *cfg.Config) {
169 consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
171 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
175 func initLogFile(config *cfg.Config) {
176 logFilePath := filepath.Join(config.RootDir, "log")
177 cmn.EnsureDir(logFilePath, 0700)
178 logFileName := path.Join(logFilePath, config.LogName)
179 file, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
183 log.Info("Failed to open log file, using default")
187 // Lanch web broser or not
188 func launchWebBrowser() {
189 log.Info("Launching System Browser with :", webAddress)
190 if err := browser.Open(webAddress); err != nil {
191 log.Error(err.Error())
196 func (n *Node) initAndstartApiServer() {
197 n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
199 listenAddr := env.String("LISTEN", n.config.ApiAddress)
201 n.api.StartServer(*listenAddr)
204 func (n *Node) OnStart() error {
208 if !n.config.VaultMode {
209 n.syncManager.Start()
211 n.initAndstartApiServer()
212 if !n.config.Web.Closed {
219 func (n *Node) OnStop() {
220 n.BaseService.OnStop()
224 if !n.config.VaultMode {
229 func (n *Node) RunForever() {
230 // Sleep forever and then...
231 cmn.TrapSignal(func() {
236 func (n *Node) EventSwitch() types.EventSwitch {
240 func (n *Node) SyncManager() *netsync.SyncManager {
244 func (n *Node) MiningPool() *miningpool.MiningPool {