OSDN Git Service

Merge pull request #1072 from Bytom/prod
[bytom/bytom.git] / node / node.go
1 package node
2
3 import (
4         "context"
5         "errors"
6         "net/http"
7         _ "net/http/pprof"
8         "os"
9         "path/filepath"
10         "time"
11
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"
17
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"
35 )
36
37 const (
38         webAddress               = "http://127.0.0.1:9888"
39         expireReservationsPeriod = time.Second
40         maxNewBlockChSize        = 1024
41 )
42
43 type Node struct {
44         cmn.BaseService
45
46         // config
47         config *cfg.Config
48
49         syncManager *netsync.SyncManager
50
51         evsw types.EventSwitch // pub/sub for services
52         //bcReactor    *bc.BlockchainReactor
53         wallet       *w.Wallet
54         accessTokens *accesstoken.CredentialStore
55         api          *api.API
56         chain        *protocol.Chain
57         txfeed       *txfeed.Tracker
58         cpuMiner     *cpuminer.CPUMiner
59         miningPool   *miningpool.MiningPool
60         miningEnable bool
61 }
62
63 func NewNode(config *cfg.Config) *Node {
64         ctx := context.Background()
65         if err := lockDataDirectory(config); err != nil {
66                 cmn.Exit("Error: " + err.Error())
67         }
68         initLogFile(config)
69         initActiveNetParams(config)
70         // Get store
71         coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
72         store := leveldb.NewStore(coreDB)
73
74         tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
75         accessTokens := accesstoken.NewStore(tokenDB)
76
77         // Make event switch
78         eventSwitch := types.NewEventSwitch()
79         if _, err := eventSwitch.Start(); err != nil {
80                 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
81         }
82
83         txPool := protocol.NewTxPool()
84         chain, err := protocol.NewChain(store, txPool)
85         if err != nil {
86                 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
87         }
88
89         var accounts *account.Manager = nil
90         var assets *asset.Registry = nil
91         var wallet *w.Wallet = nil
92         var txFeed *txfeed.Tracker = nil
93
94         txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
95         txFeed = txfeed.NewTracker(txFeedDB, chain)
96
97         if err = txFeed.Prepare(ctx); err != nil {
98                 log.WithField("error", err).Error("start txfeed")
99                 return nil
100         }
101
102         hsm, err := pseudohsm.New(config.KeysDir())
103         if err != nil {
104                 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
105         }
106
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)
112                 if err != nil {
113                         log.WithField("error", err).Error("init NewWallet")
114                 }
115
116                 // trigger rescan wallet
117                 if config.Wallet.Rescan {
118                         wallet.RescanBlocks()
119                 }
120
121                 // Clean up expired UTXO reservations periodically.
122                 go accounts.ExpireReservations(ctx, expireReservationsPeriod)
123         }
124         newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
125
126         syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
127
128         // get transaction from txPool and send it to syncManager and wallet
129         go newPoolTxListener(txPool, syncManager, wallet)
130
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
136                 go func() {
137                         http.ListenAndServe(profileHost, nil)
138                 }()
139         }
140
141         node := &Node{
142                 config:       config,
143                 syncManager:  syncManager,
144                 evsw:         eventSwitch,
145                 accessTokens: accessTokens,
146                 wallet:       wallet,
147                 chain:        chain,
148                 txfeed:       txFeed,
149                 miningEnable: config.Mining,
150         }
151
152         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
153         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
154
155         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
156
157         return node
158 }
159
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()
164
165         for {
166                 newTx := <-newTxCh
167                 syncManagerTxCh <- newTx
168                 if wallet != nil {
169                         wallet.GetNewTxCh() <- newTx
170                 }
171         }
172 }
173
174 // Lock data directory after daemonization
175 func lockDataDirectory(config *cfg.Config) error {
176         _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
177         if err != nil {
178                 return errors.New("datadir already used by another process")
179         }
180         return nil
181 }
182
183 func initActiveNetParams(config *cfg.Config) {
184         var exist bool
185         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
186         if !exist {
187                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
188         }
189 }
190
191 func initLogFile(config *cfg.Config) {
192         if config.LogFile == "" {
193                 return
194         }
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)
197         if err == nil {
198                 log.SetOutput(file)
199         } else {
200                 log.WithField("err", err).Info("using default")
201         }
202
203 }
204
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())
210                 return
211         }
212 }
213
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)
216
217         listenAddr := env.String("LISTEN", n.config.ApiAddress)
218         env.Parse()
219         n.api.StartServer(*listenAddr)
220 }
221
222 func (n *Node) OnStart() error {
223         if n.miningEnable {
224                 n.cpuMiner.Start()
225         }
226         if !n.config.VaultMode {
227                 n.syncManager.Start()
228         }
229         n.initAndstartApiServer()
230         if !n.config.Web.Closed {
231                 launchWebBrowser()
232         }
233         return nil
234 }
235
236 func (n *Node) OnStop() {
237         n.BaseService.OnStop()
238         if n.miningEnable {
239                 n.cpuMiner.Stop()
240         }
241         if !n.config.VaultMode {
242                 n.syncManager.Stop()
243         }
244 }
245
246 func (n *Node) RunForever() {
247         // Sleep forever and then...
248         cmn.TrapSignal(func() {
249                 n.Stop()
250         })
251 }
252
253 func (n *Node) EventSwitch() types.EventSwitch {
254         return n.evsw
255 }
256
257 func (n *Node) SyncManager() *netsync.SyncManager {
258         return n.syncManager
259 }
260
261 func (n *Node) MiningPool() *miningpool.MiningPool {
262         return n.miningPool
263 }