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/types"
34 w "github.com/bytom/wallet"
38 webAddress = "http://127.0.0.1:9888"
39 expireReservationsPeriod = time.Second
40 maxNewBlockChSize = 1024
49 syncManager *netsync.SyncManager
51 evsw types.EventSwitch // pub/sub for services
52 //bcReactor *bc.BlockchainReactor
54 accessTokens *accesstoken.CredentialStore
57 txfeed *txfeed.Tracker
58 cpuMiner *cpuminer.CPUMiner
59 miningPool *miningpool.MiningPool
63 func NewNode(config *cfg.Config) *Node {
64 ctx := context.Background()
65 if err := lockDataDirectory(config); err != nil {
66 cmn.Exit("Error: " + err.Error())
69 initActiveNetParams(config)
71 coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
72 store := leveldb.NewStore(coreDB)
74 tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
75 accessTokens := accesstoken.NewStore(tokenDB)
78 eventSwitch := types.NewEventSwitch()
79 if _, err := eventSwitch.Start(); err != nil {
80 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
83 txPool := protocol.NewTxPool()
84 chain, err := protocol.NewChain(store, txPool)
86 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
89 var accounts *account.Manager = nil
90 var assets *asset.Registry = nil
91 var wallet *w.Wallet = nil
92 var txFeed *txfeed.Tracker = nil
94 txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
95 txFeed = txfeed.NewTracker(txFeedDB, chain)
97 if err = txFeed.Prepare(ctx); err != nil {
98 log.WithField("error", err).Error("start txfeed")
102 hsm, err := pseudohsm.New(config.KeysDir())
104 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
107 if !config.Wallet.Disable {
108 walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
109 accounts = account.NewManager(walletDB, chain)
110 assets = asset.NewRegistry(walletDB, chain)
111 wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
113 log.WithField("error", err).Error("init NewWallet")
116 // trigger rescan wallet
117 if config.Wallet.Rescan {
118 wallet.RescanBlocks()
121 // Clean up expired UTXO reservations periodically.
122 go accounts.ExpireReservations(ctx, expireReservationsPeriod)
124 newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
126 syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
128 // get transaction from txPool and send it to syncManager and wallet
129 go newPoolTxListener(txPool, syncManager, wallet)
131 // run the profile server
132 profileHost := config.ProfListenAddress
133 if profileHost != "" {
134 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
135 // go tool pprof http://profileHose/debug/pprof/heap
137 http.ListenAndServe(profileHost, nil)
143 syncManager: syncManager,
145 accessTokens: accessTokens,
149 miningEnable: config.Mining,
152 node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
153 node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
155 node.BaseService = *cmn.NewBaseService(nil, "Node", node)
160 // newPoolTxListener listener transaction from txPool, and send it to syncManager and wallet
161 func newPoolTxListener(txPool *protocol.TxPool, syncManager *netsync.SyncManager, wallet *w.Wallet) {
162 newTxCh := txPool.GetNewTxCh()
163 syncManagerTxCh := syncManager.GetNewTxCh()
167 syncManagerTxCh <- newTx
169 wallet.GetNewTxCh() <- newTx
174 // Lock data directory after daemonization
175 func lockDataDirectory(config *cfg.Config) error {
176 _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
178 return errors.New("datadir already used by another process")
183 func initActiveNetParams(config *cfg.Config) {
185 consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
187 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
191 func initLogFile(config *cfg.Config) {
192 if config.LogFile == "" {
195 cmn.EnsureDir(filepath.Dir(config.LogFile), 0700)
196 file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
200 log.WithField("err", err).Info("using default")
205 // Lanch web broser or not
206 func launchWebBrowser() {
207 log.Info("Launching System Browser with :", webAddress)
208 if err := browser.Open(webAddress); err != nil {
209 log.Error(err.Error())
214 func (n *Node) initAndstartApiServer() {
215 n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
217 listenAddr := env.String("LISTEN", n.config.ApiAddress)
219 n.api.StartServer(*listenAddr)
222 func (n *Node) OnStart() error {
226 if !n.config.VaultMode {
227 n.syncManager.Start()
229 n.initAndstartApiServer()
230 if !n.config.Web.Closed {
236 func (n *Node) OnStop() {
237 n.BaseService.OnStop()
241 if !n.config.VaultMode {
246 func (n *Node) RunForever() {
247 // Sleep forever and then...
248 cmn.TrapSignal(func() {
253 func (n *Node) EventSwitch() types.EventSwitch {
257 func (n *Node) SyncManager() *netsync.SyncManager {
261 func (n *Node) MiningPool() *miningpool.MiningPool {