OSDN Git Service

move connection to it's folder
[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         // run the profile server
129         profileHost := config.ProfListenAddress
130         if profileHost != "" {
131                 // Profiling bytomd programs.see (https://blog.golang.org/profiling-go-programs)
132                 // go tool pprof http://profileHose/debug/pprof/heap
133                 go func() {
134                         http.ListenAndServe(profileHost, nil)
135                 }()
136         }
137
138         node := &Node{
139                 config:       config,
140                 syncManager:  syncManager,
141                 evsw:         eventSwitch,
142                 accessTokens: accessTokens,
143                 wallet:       wallet,
144                 chain:        chain,
145                 txfeed:       txFeed,
146                 miningEnable: config.Mining,
147         }
148
149         node.cpuMiner = cpuminer.NewCPUMiner(chain, accounts, txPool, newBlockCh)
150         node.miningPool = miningpool.NewMiningPool(chain, accounts, txPool, newBlockCh)
151
152         node.BaseService = *cmn.NewBaseService(nil, "Node", node)
153
154         return node
155 }
156
157 // Lock data directory after daemonization
158 func lockDataDirectory(config *cfg.Config) error {
159         _, _, err := flock.New(filepath.Join(config.RootDir, "LOCK"))
160         if err != nil {
161                 return errors.New("datadir already used by another process")
162         }
163         return nil
164 }
165
166 func initActiveNetParams(config *cfg.Config) {
167         var exist bool
168         consensus.ActiveNetParams, exist = consensus.NetParams[config.ChainID]
169         if !exist {
170                 cmn.Exit(cmn.Fmt("chain_id[%v] don't exist", config.ChainID))
171         }
172 }
173
174 func initLogFile(config *cfg.Config) {
175         if config.LogFile == "" {
176                 return
177         }
178         cmn.EnsureDir(filepath.Dir(config.LogFile), 0700)
179         file, err := os.OpenFile(config.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
180         if err == nil {
181                 log.SetOutput(file)
182         } else {
183                 log.WithField("err", err).Info("using default")
184         }
185
186 }
187
188 // Lanch web broser or not
189 func launchWebBrowser() {
190         log.Info("Launching System Browser with :", webAddress)
191         if err := browser.Open(webAddress); err != nil {
192                 log.Error(err.Error())
193                 return
194         }
195 }
196
197 func (n *Node) initAndstartApiServer() {
198         n.api = api.NewAPI(n.syncManager, n.wallet, n.txfeed, n.cpuMiner, n.miningPool, n.chain, n.config, n.accessTokens)
199
200         listenAddr := env.String("LISTEN", n.config.ApiAddress)
201         env.Parse()
202         n.api.StartServer(*listenAddr)
203 }
204
205 func (n *Node) OnStart() error {
206         if n.miningEnable {
207                 n.cpuMiner.Start()
208         }
209         if !n.config.VaultMode {
210                 n.syncManager.Start()
211         }
212         n.initAndstartApiServer()
213         if !n.config.Web.Closed {
214                 launchWebBrowser()
215         }
216
217         return nil
218 }
219
220 func (n *Node) OnStop() {
221         n.BaseService.OnStop()
222         if n.miningEnable {
223                 n.cpuMiner.Stop()
224         }
225         if !n.config.VaultMode {
226                 n.syncManager.Stop()
227         }
228 }
229
230 func (n *Node) RunForever() {
231         // Sleep forever and then...
232         cmn.TrapSignal(func() {
233                 n.Stop()
234         })
235 }
236
237 func (n *Node) EventSwitch() types.EventSwitch {
238         return n.evsw
239 }
240
241 func (n *Node) SyncManager() *netsync.SyncManager {
242         return n.syncManager
243 }
244
245 func (n *Node) MiningPool() *miningpool.MiningPool {
246         return n.miningPool
247 }