OSDN Git Service

estimate gas support multi-sign (#1126)
[bytom/bytom-spv.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
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"
16
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"
34 )
35
36 const (
37         webAddress        = "http://127.0.0.1:9888"
38         maxNewBlockChSize = 1024
39 )
40
41 type Node struct {
42         cmn.BaseService
43
44         // config
45         config *cfg.Config
46
47         syncManager *netsync.SyncManager
48
49         evsw types.EventSwitch // pub/sub for services
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         // Make event switch
76         eventSwitch := types.NewEventSwitch()
77         if _, err := eventSwitch.Start(); err != nil {
78                 cmn.Exit(cmn.Fmt("Failed to start switch: %v", err))
79         }
80
81         txPool := protocol.NewTxPool()
82         chain, err := protocol.NewChain(store, txPool)
83         if err != nil {
84                 cmn.Exit(cmn.Fmt("Failed to create chain structure: %v", err))
85         }
86
87         var accounts *account.Manager = nil
88         var assets *asset.Registry = nil
89         var wallet *w.Wallet = nil
90         var txFeed *txfeed.Tracker = nil
91
92         txFeedDB := dbm.NewDB("txfeeds", config.DBBackend, config.DBDir())
93         txFeed = txfeed.NewTracker(txFeedDB, chain)
94
95         if err = txFeed.Prepare(ctx); err != nil {
96                 log.WithField("error", err).Error("start txfeed")
97                 return nil
98         }
99
100         hsm, err := pseudohsm.New(config.KeysDir())
101         if err != nil {
102                 cmn.Exit(cmn.Fmt("initialize HSM failed: %v", err))
103         }
104
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)
110                 if err != nil {
111                         log.WithField("error", err).Error("init NewWallet")
112                 }
113
114                 // trigger rescan wallet
115                 if config.Wallet.Rescan {
116                         wallet.RescanBlocks()
117                 }
118         }
119         newBlockCh := make(chan *bc.Hash, maxNewBlockChSize)
120
121         syncManager, _ := netsync.NewSyncManager(config, chain, txPool, newBlockCh)
122
123         // get transaction from txPool and send it to syncManager and wallet
124         go newPoolTxListener(txPool, syncManager, wallet)
125
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
131                 go func() {
132                         http.ListenAndServe(profileHost, nil)
133                 }()
134         }
135
136         node := &Node{
137                 config:       config,
138                 syncManager:  syncManager,
139                 evsw:         eventSwitch,
140                 accessTokens: accessTokens,
141                 wallet:       wallet,
142                 chain:        chain,
143                 txfeed:       txFeed,
144                 miningEnable: config.Mining,
145         }
146
147         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
148         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
149
150         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
151
152         return node
153 }
154
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()
159
160         for {
161                 msg := <-txMsgCh
162                 switch msg.MsgType {
163                 case protocol.MsgNewTx:
164                         syncManagerTxCh <- msg.Tx
165                         if wallet != nil {
166                                 wallet.AddUnconfirmedTx(msg.TxDesc)
167                         }
168                 case protocol.MsgRemoveTx:
169                         if wallet != nil {
170                                 wallet.RemoveUnconfirmedTx(msg.TxDesc)
171                         }
172                 default:
173                         log.Warn("got unknow message type from the txPool channel")
174                 }
175         }
176 }
177
178 // Lock data directory after daemonization
179 func lockDataDirectory(config *cfg.Config) error {
180         _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
181         if err != nil {
182                 return errors.New("datadir already used by another process")
183         }
184         return nil
185 }
186
187 func initActiveNetParams(config *cfg.Config) {
188         var exist bool
189         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
190         if !exist {
191                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
192         }
193 }
194
195 func initLogFile(config *cfg.Config) {
196         if config.LogFile == "" {
197                 return
198         }
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)
201         if err == nil {
202                 log.SetOutput(file)
203         } else {
204                 log.WithField("err", err).Info("using default")
205         }
206
207 }
208
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())
214                 return
215         }
216 }
217
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)
220
221         listenAddr := env.String("LISTEN", n.config.ApiAddress)
222         env.Parse()
223         n.api.StartServer(*listenAddr)
224 }
225
226 func (n *Node) OnStart() error {
227         if n.miningEnable {
228                 n.cpuMiner.Start()
229         }
230         if !n.config.VaultMode {
231                 n.syncManager.Start()
232         }
233         n.initAndstartApiServer()
234         if !n.config.Web.Closed {
235                 launchWebBrowser()
236         }
237         return nil
238 }
239
240 func (n *Node) OnStop() {
241         n.BaseService.OnStop()
242         if n.miningEnable {
243                 n.cpuMiner.Stop()
244         }
245         if !n.config.VaultMode {
246                 n.syncManager.Stop()
247         }
248 }
249
250 func (n *Node) RunForever() {
251         // Sleep forever and then...
252         cmn.TrapSignal(func() {
253                 n.Stop()
254         })
255 }
256
257 func (n *Node) EventSwitch() types.EventSwitch {
258         return n.evsw
259 }
260
261 func (n *Node) SyncManager() *netsync.SyncManager {
262         return n.syncManager
263 }
264
265 func (n *Node) MiningPool() *miningpool.MiningPool {
266         return n.miningPool
267 }