12 "github.com/prometheus/prometheus/util/flock"
13 log "github.com/sirupsen/logrus"
14 cmn "github.com/tendermint/tmlibs/common"
15 dbm "github.com/tendermint/tmlibs/db"
16 browser "github.com/toqueteos/webbrowser"
18 "github.com/bytom/accesstoken"
19 "github.com/bytom/account"
20 "github.com/bytom/api"
21 "github.com/bytom/asset"
22 "github.com/bytom/blockchain/pseudohsm"
23 "github.com/bytom/blockchain/txfeed"
24 cfg "github.com/bytom/config"
25 "github.com/bytom/consensus"
26 "github.com/bytom/database/leveldb"
27 "github.com/bytom/env"
28 "github.com/bytom/mining/cpuminer"
29 "github.com/bytom/mining/miningpool"
30 "github.com/bytom/netsync"
31 "github.com/bytom/protocol"
32 "github.com/bytom/protocol/bc"
33 "github.com/bytom/protocol/bc/types"
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 // get transaction from txPool and send it to syncManager and wallet
130 go newPoolTxListener(txPool, syncManager, wallet)
132 // run the profile server
133 profileHost := config.ProfListenAddress
134 if profileHost != "" {
135 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
136 // go tool pprof http://profileHose/debug/pprof/heap
138 http.ListenAndServe(profileHost, nil)
144 syncManager: syncManager,
146 accessTokens: accessTokens,
150 miningEnable: config.Mining,
153 node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
154 node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
156 node.BaseService = *cmn.NewBaseService(nil, "Node", node)
161 // newPoolTxListener listener transaction from txPool, and send it to syncManager and wallet
162 func newPoolTxListener(txPool *protocol.TxPool, syncManager *netsync.SyncManager, wallet *w.Wallet) {
163 newTxCh := txPool.GetNewTxCh()
164 syncManagerTxCh := syncManager.GetNewTxCh()
168 syncManagerTxCh <- newTx
170 wallet.GetNewTxCh() <- newTx
175 // Lock data directory after daemonization
176 func lockDataDirectory(config *cfg.Config) error {
177 _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
179 return errors.New("datadir already used by another process")
184 func initActiveNetParams(config *cfg.Config) {
186 consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
188 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
192 func initLogFile(config *cfg.Config) {
193 if config.LogFile == "" {
196 cmn.EnsureDir(filepath.Dir(config.LogFile), 0700)
197 file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
201 log.WithField("err", err).Info("using default")
206 // Lanch web broser or not
207 func launchWebBrowser() {
208 log.Info("Launching System Browser with :", webAddress)
209 if err := browser.Open(webAddress); err != nil {
210 log.Error(err.Error())
215 func (n *Node) initAndstartApiServer() {
216 n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
218 listenAddr := env.String("LISTEN", n.config.ApiAddress)
220 n.api.StartServer(*listenAddr)
223 func (n *Node) OnStart() error {
227 if !n.config.VaultMode {
228 n.syncManager.Start()
230 n.initAndstartApiServer()
231 if !n.config.Web.Closed {
238 func (n *Node) OnStop() {
239 n.BaseService.OnStop()
243 if !n.config.VaultMode {
248 func (n *Node) RunForever() {
249 // Sleep forever and then...
250 cmn.TrapSignal(func() {
255 func (n *Node) EventSwitch() types.EventSwitch {
259 func (n *Node) SyncManager() *netsync.SyncManager {
263 func (n *Node) MiningPool() *miningpool.MiningPool {