11 "github.com/prometheus/prometheus/util/flock"
12 log "github.com/sirupsen/logrus"
13 cmn "github.com/tendermint/tmlibs/common"
14 dbm "github.com/tendermint/tmlibs/db"
15 browser "github.com/toqueteos/webbrowser"
17 "github.com/bytom/accesstoken"
18 "github.com/bytom/account"
19 "github.com/bytom/api"
20 "github.com/bytom/asset"
21 "github.com/bytom/blockchain/pseudohsm"
22 "github.com/bytom/blockchain/txfeed"
23 cfg "github.com/bytom/config"
24 "github.com/bytom/consensus"
25 "github.com/bytom/database/leveldb"
26 "github.com/bytom/env"
27 "github.com/bytom/mining/cpuminer"
28 "github.com/bytom/mining/miningpool"
29 "github.com/bytom/netsync"
30 "github.com/bytom/protocol"
31 "github.com/bytom/protocol/bc"
32 "github.com/bytom/types"
33 w "github.com/bytom/wallet"
37 webAddress = "http://127.0.0.1:9888"
38 maxNewBlockChSize = 1024
47 syncManager *netsync.SyncManager
49 evsw types.EventSwitch // pub/sub for services
50 //bcReactor *bc.BlockchainReactor
52 accessTokens *accesstoken.CredentialStore
55 txfeed *txfeed.Tracker
56 cpuMiner *cpuminer.CPUMiner
57 miningPool *miningpool.MiningPool
61 func NewNode(config *cfg.Config) *Node {
62 ctx := context.Background()
63 if err := lockDataDirectory(config); err != nil {
64 cmn.Exit("Error: " + err.Error())
67 initActiveNetParams(config)
69 coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
70 store := leveldb.NewStore(coreDB)
72 tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
73 accessTokens := accesstoken.NewStore(tokenDB)
76 eventSwitch := types.NewEventSwitch()
77 if _, err := eventSwitch.Start(); err != nil {
78 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
81 txPool := protocol.NewTxPool()
82 chain, err := protocol.NewChain(store, txPool)
84 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
87 var accounts *account.Manager = nil
88 var assets *asset.Registry = nil
89 var wallet *w.Wallet = nil
90 var txFeed *txfeed.Tracker = nil
92 txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
93 txFeed = txfeed.NewTracker(txFeedDB, chain)
95 if err = txFeed.Prepare(ctx); err != nil {
96 log.WithField("error", err).Error("start txfeed")
100 hsm, err := pseudohsm.New(config.KeysDir())
102 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
105 if !config.Wallet.Disable {
106 walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
107 accounts = account.NewManager(walletDB, chain)
108 assets = asset.NewRegistry(walletDB, chain)
109 wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
111 log.WithField("error", err).Error("init NewWallet")
114 // trigger rescan wallet
115 if config.Wallet.Rescan {
116 wallet.RescanBlocks()
119 newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
121 syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
123 // get transaction from txPool and send it to syncManager and wallet
124 go newPoolTxListener(txPool, syncManager, wallet)
126 // run the profile server
127 profileHost := config.ProfListenAddress
128 if profileHost != "" {
129 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
130 // go tool pprof http://profileHose/debug/pprof/heap
132 http.ListenAndServe(profileHost, nil)
138 syncManager: syncManager,
140 accessTokens: accessTokens,
144 miningEnable: config.Mining,
147 node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
148 node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
150 node.BaseService = *cmn.NewBaseService(nil, "Node", node)
155 // newPoolTxListener listener transaction from txPool, and send it to syncManager and wallet
156 func newPoolTxListener(txPool *protocol.TxPool, syncManager *netsync.SyncManager, wallet *w.Wallet) {
157 txMsgCh := txPool.GetMsgCh()
158 syncManagerTxCh := syncManager.GetNewTxCh()
163 case protocol.MsgNewTx:
164 syncManagerTxCh <- msg.Tx
166 wallet.AddUnconfirmedTx(msg.TxDesc)
168 case protocol.MsgRemoveTx:
170 wallet.RemoveUnconfirmedTx(msg.TxDesc)
173 log.Warn("got unknow message type from the txPool channel")
178 // Lock data directory after daemonization
179 func lockDataDirectory(config *cfg.Config) error {
180 _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
182 return errors.New("datadir already used by another process")
187 func initActiveNetParams(config *cfg.Config) {
189 consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
191 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
195 func initLogFile(config *cfg.Config) {
196 if config.LogFile == "" {
199 cmn.EnsureDir(filepath.Dir(config.LogFile), 0700)
200 file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
204 log.WithField("err", err).Info("using default")
209 // Lanch web broser or not
210 func launchWebBrowser() {
211 log.Info("Launching System Browser with :", webAddress)
212 if err := browser.Open(webAddress); err != nil {
213 log.Error(err.Error())
218 func (n *Node) initAndstartApiServer() {
219 n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
221 listenAddr := env.String("LISTEN", n.config.ApiAddress)
223 n.api.StartServer(*listenAddr)
226 func (n *Node) OnStart() error {
230 if !n.config.VaultMode {
231 n.syncManager.Start()
233 n.initAndstartApiServer()
234 if !n.config.Web.Closed {
240 func (n *Node) OnStop() {
241 n.BaseService.OnStop()
245 if !n.config.VaultMode {
250 func (n *Node) RunForever() {
251 // Sleep forever and then...
252 cmn.TrapSignal(func() {
257 func (n *Node) EventSwitch() types.EventSwitch {
261 func (n *Node) SyncManager() *netsync.SyncManager {
265 func (n *Node) MiningPool() *miningpool.MiningPool {