OSDN Git Service

add check point
[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         "strings"
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/mining/tensority"
31         "github.com/bytom/netsync"
32         "github.com/bytom/protocol"
33         "github.com/bytom/protocol/bc"
34         w "github.com/bytom/wallet"
35 )
36
37 const (
38         webHost           = "http://127.0.0.1"
39         maxNewBlockChSize = 1024
40 )
41
42 type Node struct {
43         cmn.BaseService
44
45         // config
46         config *cfg.Config
47
48         syncManager *netsync.SyncManager
49
50         //bcReactor    *bc.BlockchainReactor
51         wallet       *w.Wallet
52         accessTokens *accesstoken.CredentialStore
53         api          *api.API
54         chain        *protocol.Chain
55         txfeed       *txfeed.Tracker
56         cpuMiner     *cpuminer.CPUMiner
57         miningPool   *miningpool.MiningPool
58         miningEnable bool
59 }
60
61 func NewNode(config *cfg.Config) *Node {
62         ctx := context.Background()
63         if err := lockDataDirectory(config); err != nil {
64                 cmn.Exit("Error: " + err.Error())
65         }
66         initLogFile(config)
67         initActiveNetParams(config)
68         // Get store
69         coreDB := dbm.NewDB("core", config.DBBackend, config.DBDir())
70         store := leveldb.NewStore(coreDB)
71
72         tokenDB := dbm.NewDB("accesstoken", config.DBBackend, config.DBDir())
73         accessTokens := accesstoken.NewStore(tokenDB)
74
75         txPool := protocol.NewTxPool(store)
76         chain, err := protocol.NewChain(store, txPool)
77         if err != nil {
78                 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
79         }
80
81         var accounts *account.Manager = nil
82         var assets *asset.Registry = nil
83         var wallet *w.Wallet = nil
84         var txFeed *txfeed.Tracker = nil
85
86         txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
87         txFeed = txfeed.NewTracker(txFeedDB, chain)
88
89         if err = txFeed.Prepare(ctx); err != nil {
90                 log.WithField("error", err).Error("start txfeed")
91                 return nil
92         }
93
94         hsm, err := pseudohsm.New(config.KeysDir())
95         if err != nil {
96                 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
97         }
98
99         if !config.Wallet.Disable {
100                 walletDB := dbm.NewDB("wallet", config.DBBackend, config.DBDir())
101                 accounts = account.NewManager(walletDB, chain)
102                 assets = asset.NewRegistry(walletDB, chain)
103                 wallet, err = w.NewWallet(walletDB, accounts, assets, hsm, chain)
104                 if err != nil {
105                         log.WithField("error", err).Error("init NewWallet")
106                 }
107
108                 // trigger rescan wallet
109                 if config.Wallet.Rescan {
110                         wallet.RescanBlocks()
111                 }
112         }
113         newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
114
115         syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
116
117         // get transaction from txPool and send it to syncManager and wallet
118         go newPoolTxListener(txPool, syncManager, wallet)
119
120         // run the profile server
121         profileHost := config.ProfListenAddress
122         if profileHost != "" {
123                 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
124                 // go tool pprof http://profileHose/debug/pprof/heap
125                 go func() {
126                         http.ListenAndServe(profileHost, nil)
127                 }()
128         }
129
130         node := &Node{
131                 config:       config,
132                 syncManager:  syncManager,
133                 accessTokens: accessTokens,
134                 wallet:       wallet,
135                 chain:        chain,
136                 txfeed:       txFeed,
137                 miningEnable: config.Mining,
138         }
139
140         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
141         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
142
143         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
144
145         if config.Simd.Enable {
146                 tensority.UseSIMD = true
147         }
148
149         return node
150 }
151
152 // newPoolTxListener listener transaction from txPool, and send it to syncManager and wallet
153 func newPoolTxListener(txPool *protocol.TxPool, syncManager *netsync.SyncManager, wallet *w.Wallet) {
154         txMsgCh := txPool.GetMsgCh()
155         syncManagerTxCh := syncManager.GetNewTxCh()
156
157         for {
158                 msg := <-txMsgCh
159                 switch msg.MsgType {
160                 case protocol.MsgNewTx:
161                         syncManagerTxCh <- msg.Tx
162                         if wallet != nil {
163                                 wallet.AddUnconfirmedTx(msg.TxDesc)
164                         }
165                 case protocol.MsgRemoveTx:
166                         if wallet != nil {
167                                 wallet.RemoveUnconfirmedTx(msg.TxDesc)
168                         }
169                 default:
170                         log.Warn("got unknow message type from the txPool channel")
171                 }
172         }
173 }
174
175 // Lock data directory after daemonization
176 func lockDataDirectory(config *cfg.Config) error {
177         _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
178         if err != nil {
179                 return errors.New("datadir already used by another process")
180         }
181         return nil
182 }
183
184 func initActiveNetParams(config *cfg.Config) {
185         var exist bool
186         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
187         if !exist {
188                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
189         }
190 }
191
192 func initLogFile(config *cfg.Config) {
193         if config.LogFile == "" {
194                 return
195         }
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)
198         if err == nil {
199                 log.SetOutput(file)
200         } else {
201                 log.WithField("err", err).Info("using default")
202         }
203
204 }
205
206 // Lanch web broser or not
207 func launchWebBrowser(port string) {
208         webAddress := webHost + ":" + port
209         log.Info("Launching System Browser with :", webAddress)
210         if err := browser.Open(webAddress); err != nil {
211                 log.Error(err.Error())
212                 return
213         }
214 }
215
216 func (n *Node) initAndstartApiServer() {
217         n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
218
219         listenAddr := env.String("LISTEN", n.config.ApiAddress)
220         env.Parse()
221         n.api.StartServer(*listenAddr)
222 }
223
224 func (n *Node) OnStart() error {
225         if n.miningEnable {
226                 if _, err := n.wallet.AccountMgr.GetMiningAddress(); err != nil {
227                         n.miningEnable = false
228                         log.Error(err)
229                 } else {
230                         n.cpuMiner.Start()
231                 }
232         }
233         if !n.config.VaultMode {
234                 n.syncManager.Start()
235         }
236         n.initAndstartApiServer()
237         if !n.config.Web.Closed {
238                 s := strings.Split(n.config.ApiAddress, ":")
239                 if len(s) != 2 {
240                         log.Error("Invalid api address")
241                 }
242                 launchWebBrowser(s[1])
243         }
244         return nil
245 }
246
247 func (n *Node) OnStop() {
248         n.BaseService.OnStop()
249         if n.miningEnable {
250                 n.cpuMiner.Stop()
251         }
252         if !n.config.VaultMode {
253                 n.syncManager.Stop()
254         }
255 }
256
257 func (n *Node) RunForever() {
258         // Sleep forever and then...
259         cmn.TrapSignal(func() {
260                 n.Stop()
261         })
262 }
263
264 func (n *Node) SyncManager() *netsync.SyncManager {
265         return n.syncManager
266 }
267
268 func (n *Node) MiningPool() *miningpool.MiningPool {
269         return n.miningPool
270 }